Programs & Examples On #Estimation

This tag should be applied to questions related to tips and techniques about software project estimations: development time, effort, team size, software size, execution time, run time resource usage. Please ask on http://programmers.stackexchange.com/help/on-topic if your question is not directly related to code.

estimating of testing effort as a percentage of development time

When you speak of tests, you could mean waterfall or agile test development. In an agile environment, developers should spend 50% of their time developing and maintaining tests.

But that 50% extra will save you time when the re-factoring and manual verification time comes.

Printing everything except the first field with awk

A first stab at it seems to work for your particular case.

awk '{ f = $1; i = $NF; while (i <= 0); gsub(/^[A-Z][A-Z][ ][ ]/,""); print $i, f; }'

MySQL CONCAT returns NULL if any field contain NULL

you can use if statement like below

select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices

Disable Logback in SpringBoot

Correct way to exclude default logging, and configure log4j for logging.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter</artifactId>
 <exclusions>
     <exclusion>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-logging</artifactId>
     </exclusion>
 </exclusions>
</dependency>

Refer Spring Logging - How To.

In gradle, I needed to do this with several other dependencies:

configurations {
    all*.exclude module : 'spring-boot-starter-logging'
    all*.exclude module : 'logback-classic'
}

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

Get fragment (value after hash '#') from a URL in php

Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.

A. setup your strings with a div id, so the name anchor goes where its supposed to and the javascript can change the text colors

<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>

B. Use Javascript to do the heavy work, on the server side, inserted in your PHP page, or wherever..

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

C. I am launching the java function automatically when the page is loaded.

<script>
$( document ).ready(function() {

D. get the anchor (#tesla) from the url received by the server

var myhash1 = $(location).attr('hash'); //myhash1 == #tesla

E. trim the hash sign off of it

myhash1 = myhash1.substr(1)  //myhash1 == tesla

F. I need to highlight the term and the description so i create a new var

var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1

G. Now I can manipulate the text color for the term and description

var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>

H. This works. client clicks link on client side (xyz.com#tesla) and goes right to the term. the term and the description are highlighted in blue by javascript for quick reading .. all other entries left in black..

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

How to print a string multiple times?

So I take it if the user enters 2, you want the output to be something like:

!!
!!
!!
!!

Correct?

To get that, you would need something like:

rows = 4
times_to_repeat = int(raw_input("How many times to repeat per row? ")

for i in range(rows):
    print "!" * times_to_repeat

That would result in:

How many times to repeat per row?
>> 4
!!!!
!!!!
!!!!
!!!!

I have not tested this, but it should run error free.

LEFT OUTER JOIN in LINQ

Here is a fairly easy to understand version using method syntax:

IEnumerable<JoinPair> outerLeft =
    lefts.SelectMany(l => 
        rights.Where(r => l.Key == r.Key)
              .DefaultIfEmpty(new Item())
              .Select(r => new JoinPair { LeftId = l.Id, RightId = r.Id }));

Apache Tomcat :java.net.ConnectException: Connection refused

you can try to stop and start again with :

$ cd /path/apache-tomcat x.x.x/bin

then

$ sh shutdown.sh

when succesfully done the last step you must turn on your tomcat and catalina with command

$ sh startup.sh

I managed to resolve my problem with this way

presentViewController and displaying navigation bar

It is true that if you present a view controller modally on the iPhone, it will always be presented full screen no matter how you present it on the top view controller of a navigation controller or any other way around. But you can always show the navigation bar with the following workaround way:

Rather than presenting that view controller modally present a navigation controller modally with its root view controller set as the view controller you want:

MyViewController *myViewController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navigationController = 
    [[UINavigationController alloc] initWithRootViewController:myViewController];

//now present this navigation controller modally 
[self presentViewController:navigationController
                   animated:YES
                   completion:^{

                        }];

You should see a navigation bar when your view is presented modally.

Sending command line arguments to npm script

You could also do that:

In package.json:

"scripts": {
    "cool": "./cool.js"
}

In cool.js:

 console.log({ myVar: process.env.npm_config_myVar });

In CLI:

npm --myVar=something run-script cool

Should output:

{ myVar: 'something' }

Update: Using npm 3.10.3, it appears that it lowercases the process.env.npm_config_ variables? I'm also using better-npm-run, so I'm not sure if this is vanilla default behavior or not, but this answer is working. Instead of process.env.npm_config_myVar, try process.env.npm_config_myvar

SQL Server Convert Varchar to Datetime

Try the below

select Convert(Varchar(50),yourcolumn,103) as Converted_Date from yourtbl

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

How to darken an image on mouseover?

Put a black, semitransparent, div on top of it.

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

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

When you declare

var a=[];

you are declaring a empty array.

But when you are declaring

var a={};

you are declaring a Object .

Although Array is also Object in Javascript but it is numeric key paired values. Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.

So if you want Some values where you need to use numeric keys use Array. else use object. you can Create object like:

var a={name:"abc",age:"14"}; 

And can access values like

console.log(a.name);

Finding duplicate integers in an array and display how many times they occurred

static void printRepeating(int []arr, int size) { int i;

    Console.Write("The repeating" +  
                   " elements are : "); 

    for (i = 0; i < size; i++) 
    { 
        if (arr[ Math.Abs(arr[i])] >= 0) 
            arr[ Math.Abs(arr[i])] = 
                -arr[ Math.Abs(arr[i])]; 
        else
            Console.Write(Math.Abs(arr[i]) + " "); 
    }          
}  

How to make a JSON call to a url?

It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

Visual Studio Code - Convert spaces to tabs

To change tab settings, click the text area right to the Ln/Col text in the status bar on the bottom right of vscode window.

The name can be Tab Size or Spaces.

A menu will pop up with all available actions and settings.

enter image description here

Could not find or load main class

javac should know where to search for classes. Try this:

javac -cp . p1.java

You shouldn't need to specify classpath. Are you sure the file p1.java exists?

Get yesterday's date in bash on Linux, DST-safe

date -d "yesterday" '+%Y-%m-%d'

To use this later:

date=$(date -d "yesterday" '+%Y-%m-%d')

How to find all occurrences of a substring?

src = input() # we will find substring in this string
sub = input() # substring

res = []
pos = src.find(sub)
while pos != -1:
    res.append(pos)
    pos = src.find(sub, pos + 1)

Remove duplicates from an array of objects in JavaScript

If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.uniq function in their libraries. From lodash:

_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])

Basically, you pass in the array that in here is an object literal and you pass in the attribute that you want to remove duplicates with in the original data array, like this:

var data = [{'name': 'Amir', 'surname': 'Rahnama'}, {'name': 'Amir', 'surname': 'Stevens'}];
var non_duplidated_data = _.uniq(data, 'name'); 

UPDATE: Lodash now has introduced a .uniqBy as well.

WPF Check box: Check changed handling

What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.

Jquery UI tooltip does not support html content

$(function () {
         $.widget("ui.tooltip", $.ui.tooltip, {
             options: {
                 content: function () {
                     return $(this).prop('title');
                 }
             }
         });

         $('[rel=tooltip]').tooltip({
             position: {
                 my: "center bottom-20",
                 at: "center top",
                 using: function (position, feedback) {
                     $(this).css(position);
                     $("<div>")
                         .addClass("arrow")
                         .addClass(feedback.vertical)
                         .addClass(feedback.horizontal)
                         .appendTo(this);
                 }
             }
         });
     });

thanks for post and solution above.

I have updated the code little bit. Hope this might help you.

http://jsfiddle.net/pragneshkaria/Qv6L2/49/

Selected value for JSP drop down using JSTL

If you don't mind using jQuery you can use the code bellow:

    <script>
     $(document).ready(function(){
           $("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
     });
     </script>


    <select id="department" name="department">
      <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
      </c:forEach>
    </select>

In the your Servlet add the following:

        request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

What are the obj and bin folders (created by Visual Studio) used for?

Be careful with setup projects if you're using them; Visual Studio setup projects Primary Output pulls from the obj folder rather than the bin.

I was releasing applications I thought were obfuscated and signed in msi setups for quite a while before I discovered that the deployed application files were actually neither obfuscated nor signed as I as performing the post-build procedure on the bin folder assemblies and should have been targeting the obj folder assemblies instead.

This is far from intuitive imho, but the general setup approach is to use the Primary Output of the project and this is the obj folder. I'd love it if someone could shed some light on this btw.

Creating a SOAP call using PHP with an XML body

First off, you have to specify you wish to use Document Literal style:

$client = new SoapClient(NULL, array(
    'location' => 'https://example.com/path/to/service',
    'uri' => 'http://example.com/wsdl',
    'trace' => 1,
    'use' => SOAP_LITERAL)
);

Then, you need to transform your data into a SoapVar; I've written a simple transform function:

function soapify(array $data)
{
        foreach ($data as &$value) {
                if (is_array($value)) {
                        $value = soapify($value);
                }
        }

        return new SoapVar($data, SOAP_ENC_OBJECT);
}

Then, you apply this transform function onto your data:

$data = soapify(array(
    'Acquirer' => array(
        'Id' => 'MyId',
        'UserId' => 'MyUserId',
        'Password' => 'MyPassword',
    ),
));

Finally, you call the service passing the Data parameter:

$method = 'Echo';

$result = $client->$method(new SoapParam($data, 'Data'));

python: urllib2 how to send cookie with urlopen request

Maybe using cookielib.CookieJar can help you. For instance when posting to a page containing a form:

import urllib2
import urllib
from cookielib import CookieJar

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()

EDIT:

After Piotr's comment I'll elaborate a bit. From the docs:

The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

So whatever requests you make with your CookieJar instance, all cookies will be handled automagically. Kinda like your browser does :)

I can only speak from my own experience and my 99% use-case for cookies is to receive a cookie and then need to send it with all subsequent requests in that session. The code above handles just that, and it does so transparently.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

Follow the steps below.

Install Entity Framework Core Design and SQL Server database provider for Entity Framework Core:

dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Import Entity Framework Core:

using Microsoft.EntityFrameworkCore;

And configure your DbContext:

var connectionString = Configuration.GetConnectionString("myDb");
services.AddDbContext<MyDbContext>(options => 
    options.UseSqlServer(connectionString)
);

.NET - How do I retrieve specific items out of a Dataset?

You can do like...

If you want to access using ColumnName

Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0]["column4Name"].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0]["column5Name"].ToString());

OR, if you want to access using Index

Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0][4].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0][5].ToString());

Path of assets in CSS files in Symfony 2

If it can help someone, we have struggled a lot with Assetic, and we are now doing the following in development mode:

  • Set up like in Dumping Asset Files in the dev Environmen so in config_dev.yml, we have commented:

    #assetic:
    #    use_controller: true
    

    And in routing_dev.yml

    #_assetic:
    #    resource: .
    #    type:     assetic
    
  • Specify the URL as absolute from the web root. For example, background-image: url("/bundles/core/dynatree/skins/skin/vline.gif"); Note: our vhost web root is pointing on web/.

  • No usage of cssrewrite filter

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

Where you have written the code

public class Main {
    public static void main(String args[])
    {
        Calculate obj = new Calculate(1,2,'+');
        obj.getAnswer();
    }
}

Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.

Datatable vs Dataset

There are some optimizations you can use when filling a DataTable, such as calling BeginLoadData(), inserting the data, then calling EndLoadData(). This turns off some internal behavior within the DataTable, such as index maintenance, etc. See this article for further details.

How to initialize a vector with fixed length in R

?vector

X <- vector(mode="character", length=10)

This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.

>  X[5] <- "character element in 5th position"

>  X
 [1] ""                                  ""                                 
 [3] ""                                  ""                                 
 [5] "character element in 5th position" ""                                 
 [7] ""                                  ""                                 
 [9] ""                                  "" 
>  nchar(X)
 [1]  0  0  0  0 33  0  0  0  0  0

> length(X)
[1] 10

iOS - UIImageView - how to handle UIImage image orientation

This method first checks the current orientation of UIImage and then it changes the orientation in a clockwise way and return UIImage.You can show this image as

self.imageView.image = rotateImage(currentUIImage)

   func rotateImage(image:UIImage)->UIImage
    {
        var rotatedImage = UIImage();
        switch image.imageOrientation
        {
            case UIImageOrientation.Right:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Down);

           case UIImageOrientation.Down:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Left);

            case UIImageOrientation.Left:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Up);

             default:
            rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Right);
        }
        return rotatedImage;
    }

Swift 4 version

func rotateImage(image:UIImage) -> UIImage
    {
        var rotatedImage = UIImage()
        switch image.imageOrientation
        {
        case .right:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .down)

        case .down:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .left)

        case .left:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .up)

        default:
            rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .right)
        }

        return rotatedImage
    }

Best Practice: Access form elements by HTML id or name attribute?

name field works well. It provides a reference to the elements.

parent.children - Will list all elements with a name field of the parent. parent.elements - Will list only form elements such as input-text, text-area, etc

_x000D_
_x000D_
var form = document.getElementById('form-1');_x000D_
console.log(form.children.firstname)_x000D_
console.log(form.elements.firstname)_x000D_
console.log(form.elements.progressBar); // undefined_x000D_
console.log(form.children.progressBar);_x000D_
console.log(form.elements.submit); // undefined
_x000D_
<form id="form-1">_x000D_
  <input type="text" name="firstname" />_x000D_
  <input type="file" name="file" />_x000D_
  <progress name="progressBar" value="20" min="0" max="100" />_x000D_
  <textarea name="address"></textarea>_x000D_
  <input type="submit" name="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Note: For .elements to work, the parent needs to be a <form> tag. Whereas, .children will work on any HTML-element - such as <div>, <span>, etc.

Good Luck...

Pandas "Can only compare identically-labeled DataFrame objects" error

When you compare two DataFrames, you must ensure that the number of records in the first DataFrame matches with the number of records in the second DataFrame. In our example, each of the two DataFrames had 4 records, with 4 products and 4 prices.

If, for example, one of the DataFrames had 5 products, while the other DataFrame had 4 products, and you tried to run the comparison, you would get the following error:

ValueError: Can only compare identically-labeled Series objects

this should work

import pandas as pd
import numpy as np

firstProductSet = {'Product1': ['Computer','Phone','Printer','Desk'],
                   'Price1': [1200,800,200,350]
                   }
df1 = pd.DataFrame(firstProductSet,columns= ['Product1', 'Price1'])


secondProductSet = {'Product2': ['Computer','Phone','Printer','Desk'],
                    'Price2': [900,800,300,350]
                    }
df2 = pd.DataFrame(secondProductSet,columns= ['Product2', 'Price2'])


df1['Price2'] = df2['Price2'] #add the Price2 column from df2 to df1

df1['pricesMatch?'] = np.where(df1['Price1'] == df2['Price2'], 'True', 'False')  #create new column in df1 to check if prices match
df1['priceDiff?'] = np.where(df1['Price1'] == df2['Price2'], 0, df1['Price1'] - df2['Price2']) #create new column in df1 for price diff 
print (df1)

example from https://datatofish.com/compare-values-dataframes/

How to check if running as root in a bash script

As far as I know the correct way to check it is:

if [ $(id -u) = "0" ]; then
    echo "You are root"
else
    echo "You are NOT root"
fi

See "Testing For Root" section here:

http://linuxcommand.org/lc3_wss0080.php

Is there an easy way to convert Android Application to IPad, IPhone

I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.

As iOS does not use Java like Android, your options are quite limited:

1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).

2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.

3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.

The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.

Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.

As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.

How do I sort a table in Excel if it has cell references in it?

Put a dollar sign in front of the row and/or column of the cell you want to remain constant.

Fixed it for me!

GetType used in PowerShell, difference between variables

First of all, you lack parentheses to call GetType. What you see is the MethodInfo describing the GetType method on [DayOfWeek]. To actually call GetType, you should do:

$a.GetType();
$b.GetType();

You should see that $a is a [DayOfWeek], and $b is a custom object generated by the Select-Object cmdlet to capture only the DayOfWeek property of a data object. Hence, it's an object with a DayOfWeek property only:

C:\> $b.DayOfWeek -eq $a
True

Plotting histograms from grouped data in a pandas DataFrame

Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist() it's trying to make a histogram of both columns hence the str error.

This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.

df.reset_index().pivot('index','Letter','N').hist()

The reset_index() is just to shove the current index into a column called index. Then pivot will take your data frame, collect all of the values N for each Letter and make them a column. The resulting data frame as 400 rows (fills missing values with NaN) and three columns (A, B, C). hist() will then produce one histogram per column and you get format the plots as needed.

Uncaught TypeError: Cannot assign to read only property

If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.

var globalObject = {
    name:"a",
    age:20
}
function() {
    let localObject = {
    name:'a',
    age:21
    }
    this.globalObject = localObject;
}

PHP - concatenate or directly insert variables in string

I prefer this all the time and found it much easier.

echo "Welcome {$name}!"

How to add a line to a multiline TextBox?

Append a \r\n to the string to put the text on a new line.

textBox1.Text += ("brown\r\n");
textBox1.Text += ("brwn");

This will produce the two entries on separate lines.

"Could not find a version that satisfies the requirement opencv-python"

It happened with me on Windows, pip was not able to install opencv-python==3.4.0.12.

Later found out that it was due to the Python version, Python 3.7 has some issue with not getting linked to https://github.com/skvark/opencv-python.

Downgraded to Python 3.6 and it worked with:

pip3 install opencv-python

How to set a parameter in a HttpServletRequest?

The missing getParameterMap override ended up being a real problem for me. So this is what I ended up with:

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/***
 * Request wrapper enabling the update of a request-parameter.
 * 
 * @author E.K. de Lang
 *
 */
final class HttpServletRequestReplaceParameterWrapper
    extends HttpServletRequestWrapper
{

    private final Map<String, String[]> keyValues;

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, String key, String value)
    {
        super(request);

        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        // Can override the values in the request
        keyValues.put(key, new String[] { value });

    }

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, Map<String, String> additionalRequestParameters)
    {
        super(request);
        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        for (Map.Entry<String, String> entry : additionalRequestParameters.entrySet()) {
            keyValues.put(entry.getKey(), new String[] { entry.getValue() });
        }

    }

    @Override
    public String getParameter(String name)
    {
        if (keyValues.containsKey(name)) {
            String[] strings = keyValues.get(name);
            if (strings == null || strings.length == 0) {
                return null;
            }
            else {
                return strings[0];
            }
        }
        else {
            // Just in case the request has some tricks of it's own.
            return super.getParameter(name);
        }
    }

    @Override
    public String[] getParameterValues(String name)
    {
        String[] value = this.keyValues.get(name);
        if (value == null) {
            // Just in case the request has some tricks of it's own.
            return super.getParameterValues(name);
        }
        else {
            return value;
        }
    }

    @Override
    public Map<String, String[]> getParameterMap()
    {
        return this.keyValues;
    }

}

How to horizontally center an element

You can apply this CSS to the inner <div>:

#inner {
  width: 50%;
  margin: 0 auto;
}

Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.

If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:

#inner {
  display: table;
  margin: 0 auto;
}

It will make the inner element center horizontally and it works without setting a specific width.

Working example here:

_x000D_
_x000D_
#inner {
  display: table;
  margin: 0 auto;
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%
}
_x000D_
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
_x000D_
_x000D_
_x000D_


EDIT

With flexbox it is very easy to style the div horizontally and vertically centered.

_x000D_
_x000D_
#inner {  
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%;
  display: flex;
  justify-content: center;
}
_x000D_
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
_x000D_
_x000D_
_x000D_

To align the div vertically centered, use the property align-items: center.

Java: Convert String to TimeStamp

can you try it once...

String dob="your date String";
String dobis=null;
final DateFormat df = new SimpleDateFormat("yyyy-MMM-dd");
final Calendar c = Calendar.getInstance();
try {
    if(dob!=null && !dob.isEmpty() && dob != "")
    {
    c.setTime(df.parse(dob));
    int month=c.get(Calendar.MONTH);
    month=month+1;
    dobis=c.get(Calendar.YEAR)+"-"+month+"-"+c.get(Calendar.DAY_OF_MONTH);
    }

}

Intro to GPU programming

  1. You get programmable vertex and pixel shaders that allow execution of code directly on the GPU to manipulate the buffers that are to be drawn. These languages (i.e. OpenGL's GL Shader Lang and High Level Shader Lang and DirectX's equivalents ), are C style syntax, and really easy to use. Some examples of HLSL can be found here for XNA game studio and Direct X. I don't have any decent GLSL references, but I'm sure there are a lot around. These shader languages give an immense amount of power to manipulate what gets drawn at a per-vertex or per-pixel level, directly on the graphics card, making things like shadows, lighting, and bloom really easy to implement.
  2. The second thing that comes to mind is using openCL to code for the new lines of general purpose GPU's. I'm not sure how to use this, but my understanding is that openCL gives you the beginnings of being able to access processors on both the graphics card and normal cpu. This is not mainstream technology yet, and seems to be driven by Apple.
  3. CUDA seems to be a hot topic. CUDA is nVidia's way of accessing the GPU power. Here are some intros

How to check what version of jQuery is loaded?

In one line and the minimum of keystrokes (oops!):

alert($().jquery);

How to use ADB in Android Studio to view an SQLite DB

The issue you are having is common and not explained well in the documentation. Normal devices do not include the sqlite3 database binary which is why you are getting an error. the Android Emeulator, OSX, Linux (if installed) and Windows (after installed) have the binary so you can open a database locally on your machine.

The workaround is to copy the Database from your device to your local machine. This can be accomplished with ADB but requires a number of steps.

Before you start you will need some information:

  • path of the SDK (if not included in your OS environment)
  • your <package name>, for example, com.example.application
  • a <local path> to place your database, eg. ~/Desktop or %userprofile%\Desktop

Next you will need to understand what terminal each command gets written to the first character in the examples below does not get typed but lets you know what shell we are in:

  • > = you OS command prompt
  • $ = ADB shell command Prompt
  • ! = ADB shell as admin command prompt
  • %

Next enter the following commands from Terminal or Command (don't enter first character or text in ())

> adb shell
$ su
! cp /data/data/<package name>/Databases/<database name> /sdcard
! exit
$ exit
> adb pull /sdcard/<database name> <local path>
> sqlite3 <local db path>
% .dump
% .exit  (to exit sqldb)

This is a really round about way of copying the database to your local machine and locally reading the database. There are SO and other resources explaining how to install the sqlite3 binary onto your device from an emulator but for one time access this process works.

If you need to access the database interactively I would suggest running your app in an emulator (that already had sqlite3) or installing sqlite onto your devices /xbin path.

What is "406-Not Acceptable Response" in HTTP?

"Sometimes" this can mean that the server had an internal error, and wanted to respond with an error message (ex: 500 with JSON payload) but since the request headers didn't say it accepted JSON, it returns a 406 instead. Go figure. (in this case: spring boot webapp).

In which case, your operation did fail. But the failure message was obscured by another.

Tomcat manager/html is not available?

I've faced this issue today. I am using Centos7, the solution was to install tomcat-admin-webapp package.

yum install tomcat-webapps tomcat-admin-webapps

Can I try/catch a warning?

try checking whether it returns some boolean value then you can simply put it as a condition. I encountered this with the oci_execute(...) which was returning some violation with my unique keys.

ex.
oci_parse($res, "[oracle pl/sql]");
if(oci_execute){
...do something
}

How can I return the sum and average of an int array?

customerssalary.Average();
customerssalary.Sum();

Video 100% width and height

You can use Javascript to dynamically set the height to 100% of the window and then center it using a negative left margin based on the ratio of video width to window width.

http://jsfiddle.net/RfV5C/

var $video  = $('video'),
    $window = $(window); 

$(window).resize(function(){
    var height = $window.height();
    $video.css('height', height);

    var videoWidth = $video.width(),
        windowWidth = $window.width(),
    marginLeftAdjust =   (windowWidth - videoWidth) / 2;

    $video.css({
        'height': height, 
        'marginLeft' : marginLeftAdjust
    });
}).resize();

Div side by side without float

A div is a block level element, meaning that will behave as a block, and blocks can't stay side by side without being floated. You can however set them to inline elements with:

display:inline-block;

Give it a try...


Another way is to place them using:

position:absolute;
left:0;

and/or

position:absolute;
right:0;

Note: For this to work as expected, the wrapper element must have a position:relative; so that the elements with absolute positioning stay relative to their wrapper element.

Sleeping in a batch file

In Notepad, write:

@echo off
set /a WAITTIME=%1+1
PING 127.0.0.1 -n %WAITTIME% > nul
goto:eof

Now save as wait.bat in the folder C:\WINDOWS\System32, then whenever you want to wait, use:

CALL WAIT.bat <whole number of seconds without quotes>

Change the value in app.config file dynamically

 XmlReaderSettings _configsettings = new XmlReaderSettings();
 _configsettings.IgnoreComments = true;

 XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
 XmlDocument doc_config = new XmlDocument();
 doc_config.Load(_configreader);
 _configreader.Close();

 foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
 {
     if (RootName.LocalName == "appSettings")
     {
         if (RootName.HasChildNodes)
         {
             foreach (XmlNode _child in RootName.ChildNodes)
             {
                 if (_child.Attributes["key"].Value == "HostName")
                 {
                     if (_child.Attributes["value"].Value == "false")
                         _child.Attributes["value"].Value = "true";
                 }
             }
         }
     }
 }
 doc_config.Save(ConfigFilePath);

How do I convert a Django QuerySet into list of dicts?

Type Cast to List

    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))

How do I test a private function or a class that has private methods, fields or inner classes?

My team and I are using Typemock, which has an API that allows you to fake non-public methods. Recently they added the ability to fake non-visible types and to use XUnit.

Adding POST parameters before submit

PURE JavaScript:

Creating the XMLHttpRequest:

function getHTTPObject() {
    /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, 
       por lo que se puede copiar tal como esta aqui */
    var xmlhttp = false;
    /* No mas soporte para Internet Explorer
    try { // Creacion del objeto AJAX para navegadores no IE
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(nIE) {
        try { // Creacion del objet AJAX para IE
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(IE) {
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
                xmlhttp = new XMLHttpRequest();
        }
    }
    */
    xmlhttp = new XMLHttpRequest();
    return xmlhttp; 
}

JavaScript function to Send the info via POST:

function sendInfo() {
    var URL = "somepage.html"; //depends on you
    var Params = encodeURI("var1="+val1+"var2="+val2+"var3="+val3);
    console.log(Params);
    var ajax = getHTTPObject();     
    ajax.open("POST", URL, true); //True:Sync - False:ASync
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax.setRequestHeader("Content-length", Params.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.onreadystatechange = function() { 
        if (ajax.readyState == 4 && ajax.status == 200) {
            alert(ajax.responseText);
        } 
    }
    ajax.send(Params);
}

Package structure for a Java project?

I usually like to have the following:

  • bin (Binaries)
  • doc (Documents)
  • inf (Information)
  • lib (Libraries)
  • res (Resources)
  • src (Source)
  • tst (Test)

These may be considered unconventional, but I find it to be a very nice way to organize things.

Webpack "OTS parsing error" loading fonts

For me the problem was my regex expression. The below did the trick to get bootstrap working:

{
    test: /\.(woff|ttf|eot|svg)(\?v=[a-z0-9]\.[a-z0-9]\.[a-z0-9])?$/,
    loader: 'url-loader?limit=100000'
},

How does OkHttp get Json string?

I am also faced the same issue

use this code:

// notice string() call
String resStr = response.body().string();    
JSONObject json = new JSONObject(resStr);

it definitely works

Mysql where id is in array

Change

$array=array_map('intval', explode(',', $string));

To:

$array= implode(',', array_map('intval', explode(',', $string)));

array_map returns an array, not a string. You need to convert the array to a comma separated string in order to use in the WHERE clause.

How do I find the last column with data?

Lots of ways to do this. The most reliable is find.

Dim rLastCell As Range

Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)

MsgBox ("The last used column is: " & rLastCell.Column)

If you want to find the last column used in a particular row you can use:

Dim lColumn As Long

lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column

Using used range (less reliable):

Dim lColumn As Long

lColumn = ws.UsedRange.Columns.Count

Using used range wont work if you have no data in column A. See here for another issue with used range:

See Here regarding resetting used range.

How to set adaptive learning rate for GradientDescentOptimizer?

If you want to set specific learning rates for intervals of epochs like 0 < a < b < c < .... Then you can define your learning rate as a conditional tensor, conditional on the global step, and feed this as normal to the optimiser.

You could achieve this with a bunch of nested tf.cond statements, but its easier to build the tensor recursively:

def make_learning_rate_tensor(reduction_steps, learning_rates, global_step):
    assert len(reduction_steps) + 1 == len(learning_rates)
    if len(reduction_steps) == 1:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: learning_rates[1]
        )
    else:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: make_learning_rate_tensor(
                reduction_steps[1:],
                learning_rates[1:],
                global_step,)
            )

Then to use it you need to know how many training steps there are in a single epoch, so that we can use the global step to switch at the right time, and finally define the epochs and learning rates you want. So if I want the learning rates [0.1, 0.01, 0.001, 0.0001] during the epoch intervals of [0, 19], [20, 59], [60, 99], [100, \infty] respectively, I would do:

global_step = tf.train.get_or_create_global_step()
learning_rates = [0.1, 0.01, 0.001, 0.0001]
steps_per_epoch = 225
epochs_to_switch_at = [20, 60, 100]
epochs_to_switch_at = [x*steps_per_epoch for x in epochs_to_switch_at ]
learning_rate = make_learning_rate_tensor(epochs_to_switch_at , learning_rates, global_step)

Equivalent of shell 'cd' command to change the working directory?

import os

abs_path = 'C://a/b/c'
rel_path = './folder'

os.chdir(abs_path)
os.chdir(rel_path)

You can use both with os.chdir(abs_path) or os.chdir(rel_path), there's no need to call os.getcwd() to use a relative path.

How can I view the source code for a function?

It gets revealed when you debug using the debug() function. Suppose you want to see the underlying code in t() transpose function. Just typing 't', doesn't reveal much.

>t 
function (x) 
UseMethod("t")
<bytecode: 0x000000003085c010>
<environment: namespace:base>

But, Using the 'debug(functionName)', it reveals the underlying code, sans the internals.

> debug(t)
> t(co2)
debugging in: t(co2)
debug: UseMethod("t")
Browse[2]> 
debugging in: t.ts(co2)
debug: {
    cl <- oldClass(x)
    other <- !(cl %in% c("ts", "mts"))
    class(x) <- if (any(other)) 
        cl[other]
    attr(x, "tsp") <- NULL
    t(x)
}
Browse[3]> 
debug: cl <- oldClass(x)
Browse[3]> 
debug: other <- !(cl %in% c("ts", "mts"))
Browse[3]> 
debug: class(x) <- if (any(other)) cl[other]
Browse[3]>  
debug: attr(x, "tsp") <- NULL
Browse[3]> 
debug: t(x)

EDIT: debugonce() accomplishes the same without having to use undebug()

How to get JSON object from Razor Model object in javascript

In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().

It should be as simple as:

<script>
  var json = @Json.Serialize(Model.CollegeInformationlist);
</script>

PDOException “could not find driver”

I spent the last day trying to figure out why I was getting the following error. I am running Ubuntu 14.04.

The Problem:
I noticed that my PHP-CLI version was running php7.0 but php_info() (the web version) was displaying php 5.5.9. Even though php_info() said pdo was enabled, using the command line (CLI) wasn't recognizing the pdo_mysql command. It turns out that mysql was enabled for my old version but not the CLI version. All I did was install mysql for php7.0 and it was able to work.

This is what worked:

To check the version:

php -v

To install mysql for php7.0

sudo apt-get install php7.0-mysql

1) make sure your CLI version is the same as your web version
2) If they are different, make sure your CLI version has the mysql plug-in since it doesn't come with it as a default.

Why is quicksort better than mergesort?

Quicksort is NOT better than mergesort. With O(n^2) (worst case that rarely happens), quicksort is potentially far slower than the O(nlogn) of the merge sort. Quicksort has less overhead, so with small n and slow computers, it is better. But computers are so fast today that the additional overhead of a mergesort is negligible, and the risk of a very slow quicksort far outweighs the insignificant overhead of a mergesort in most cases.

In addition, a mergesort leaves items with identical keys in their original order, a useful attribute.

How can I execute PHP code from the command line?

You can use:

 echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php

The short tag "< ?=" can be helpful too:

 echo '<?= function_exists("foo") ? "yes" : "no";' | php
 echo '<?= 8+7+9 ;' | php

The closing tag "?>" is optional, but don't forget the final ";"!

How do I include a pipe | in my linux find -exec command?

If you are looking for a simple alternative, this can be done using a loop:

for i in $(find -name 'file_*' -follow -type f); do
  zcat $i | agrep -dEOE 'grep'
done

or, more general and easy to understand form:

for i in $(YOUR_FIND_COMMAND); do
  YOUR_EXEC_COMMAND_AND_PIPES
done

and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES

How to simulate POST request?

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done

How to multi-line "Replace in files..." in Notepad++

The workaround is

  1. search and replace \r\n to thisismynewlineword

(this will remove all the new lines and there should be whole one line)

  1. now perform your replacements

  2. search and replace thisismynewlineword to \r\n

(to undo the step 1)

Restart container within pod

There was an issue in coredns pod, I deleted such pod by

kubectl delete pod -n=kube-system coredns-fb8b8dccf-8ggcf

Its pod will restart automatically.

Using JSON POST Request

An example using jQuery is below. Hope this helps

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

    $.ajax({
        url: "https://example.com/api/",
        type: "POST",
        data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
};

</script>
</head>
<body>

<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>

</body>
</html> 

Firebug debug process

Firebug XHR debug process

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

How to move child element from one parent to another using jQuery

Based on the answers provided, I decided to make a quick plugin to do this:

(function($){
    $.fn.moveTo = function(selector){
        return this.each(function(){
            var cl = $(this).clone();
            $(cl).appendTo(selector);
            $(this).remove();
        });
    };
})(jQuery);

Usage:

$('#nodeToMove').moveTo('#newParent');

Warning: push.default is unset; its implicit value is changing in Git 2.0

If you get a message from git complaining about the value 'simple' in the configuration, check your git version.

After upgrading Xcode (on a Mac running Mountain Lion), which also upgraded git from 1.7.4.4 to 1.8.3.4, shells started before the upgrade were still running git 1.7.4.4 and complained about the value 'simple' for push.default in the global config.

The solution was to close the shells running the old version of git and use the new version.

angularjs getting previous route path

This is how I currently store a reference to the previous path in the $rootScope:

run(['$rootScope', function($rootScope) {
        $rootScope.$on('$locationChangeStart', function() {
            $rootScope.previousPage = location.pathname;
        });
}]);

Configuring ObjectMapper in Spring

Above Spring 4, there is no need to configure MappingJacksonHttpMessageConverter if you only intend to configure ObjectMapper.

(configure MappingJacksonHttpMessageConverter will cause you to lose other MessageConverter)

You just need to do:

public class MyObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 4219938065516862637L;

    public MyObjectMapper() {
        super();
        enable(SerializationFeature.INDENT_OUTPUT);
    }       
}

And in your Spring configuration, create this bean:

@Bean 
public MyObjectMapper myObjectMapper() {        
    return new MyObjectMapper();
}

jQuery UI - Close Dialog When Clicked Outside

I had to do two parts. First the outside click-handler:

$(document).on('click', function(e){
    if ($(".ui-dialog").length) {
        if (!$(e.target).parents().filter('.ui-dialog').length) {
            $('.ui-dialog-content').dialog('close');
        }
    }
}); 

This calls dialog('close') on the generic ui-dialog-content class, and so will close all dialogs if the click didn't originate in one. It will work with modal dialogs too, since the overlay is not part of the .ui-dialog box.

The problem is:

  1. Most dialogs are created because of clicks outside of a dialog
  2. This handler runs after those clicks have created a dialog and bubbled up to the document, so it immediately closes them.

To fix this, I had to add stopPropagation to those click handlers:

moreLink.on('click', function (e) {
    listBox.dialog();
    e.stopPropagation(); //Don't trigger the outside click handler
});

Run class in Jar file

You want:

java -cp myJar.jar myClass

The Documentation gives the following example:

C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

If you have access to the element which the event is attached to inside the mouseout method, you can use contains() to see if the event.relatedTarget is a child element or not.

As event.relatedTarget is the element to which the mouse has passed into, if it isn't a child element, you have moused out of the element.

div.onmouseout = function (event) {
    if (!div.contains(event.relatedTarget)) {
        // moused out of div
    }
}

How do I check to see if my array includes an object?

This ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.exists?(horse.id)
   @suggested_horses<< horse
end

Should probably be this ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.include?(horse)
   @suggested_horses<< horse
end

How to set layout_weight attribute dynamically from code?

Any of LinearLayout.LayoutParams and TableLayout.LayoutParams worked for me, for buttons the right one is TableRow.LayoutParams. That is:

            TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
                    TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT, 1f);

About using MATCH_PARENT or WRAP_CONTENT be the same.

Clone contents of a GitHub repository (without the folder itself)

this worker for me

git clone <repository> .

How to get the selected date of a MonthCalendar control in C#

For those who are still trying, this link helped me out, too; it just puts it all together:

http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx

private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);

//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;

//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}

In Windows cmd, how do I prompt for user input and use the result in another command?

Just to keep a default value of the variable. Press Enter to use default from the recent run of your .bat:

@echo off
set /p Var1=<Var1.txt
set /p Var1="Enter new value ("%Var1%") "
echo %Var1%> Var1.txt

rem YourApp %Var1%

In the first run just ignore the message about lack of file with the initial value of the variable (or do create the Var1.txt manually).

API Gateway CORS: no 'Access-Control-Allow-Origin' header

I found a simple solution within

API Gateway > Select your API endpoint > Select the method (in my case it was the POST)

Now there is a dropdown ACTIONS > Enable CORS .. select it.

Now select the dropdown ACTIONS again > Deploy API (re-deploy it)

enter image description here

It worked !

Getting value from appsettings.json in .net core

In the constructor of Startup class, you can access appsettings.json and many other settings using the injected IConfiguration object:

Startup.cs Constructor

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;

        //here you go
        var myvalue = Configuration["Grandfather:Father:Child"];

    }

public IConfiguration Configuration { get; }

Contents of appsettings.json

  {
  "Grandfather": {
    "Father": {
      "Child": "myvalue"
    }
  }

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

If you need disable clicking outside but enable pressing escape

$('#myModal').modal({
    backdrop: 'static',   // This disable for click outside event
    keyboard: true        // This for keyboard event
})

How to add class active on specific li on user click with jQuery

 $(document).ready(function () {
    $('.dates li a').click(function (e) {

        $('.dates li a').removeClass('active');

        var $parent = $(this);
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
        e.preventDefault();
    });
});

Using the "start" command with parameters passed to the started program

The spaces are DOSs/CMDs Problems so you should go to the Path via:

cd "c:\program files\Microsoft Virtual PC"

and then simply start VPC via:

start Virtual~1.exe -pc MY-PC -launch

~1 means the first exe with "Virtual" at the beginning. So if there is a "Virtual PC.exe" and a "Virtual PC1.exe" the first would be the Virtual~1.exe and the second Virtual~2.exe and so on.

Or use a VNC-Client like VirtualBox.

Can Flask have optional URL parameters?

Almost the same as skornos, but with variable declarations for a more explicit answer. It can work with Flask-RESTful extension:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class UserAPI(Resource):
    def show(userId, username=None):
    pass

api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint='user')

if __name__ == '__main__':
    app.run()

The add_resource method allows pass multiples URLs. Each one will be routed to your Resource.

sorting a List of Map<String, String>

try {
        java.util.Collections.sort(data,
                new Comparator<Map<String, String>>() {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                            "MM/dd/yyyy");

                    public int compare(final Map<String, String> map1,
                            final Map<String, String> map2) {
                        Date date1 = null, date2 = null;
                        try {
                            date1 = sdf.parse(map1.get("Date"));
                            date2 = sdf.parse(map2.get("Date"));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (date1.compareTo(date2) > 0) {
                            return +1;
                        } else if (date1.compareTo(date2) == 0) {
                            return 0;
                        } else {
                            return -1;
                        }
                    }
                });

    } catch (Exception e) {

    }

Transform char array into String

Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:

void setup() {
  // turn on Serial so we can see...
  Serial.begin(9600);

  // the culprit:
  uint8_t my_str[6];    // an array big enough for a 5 character string

  // give it something so we can see what it's doing
  my_str[0] = 'H';
  my_str[1] = 'e';
  my_str[2] = 'l';
  my_str[3] = 'l';
  my_str[4] = 'o';
  my_str[5] = 0;  // be sure to set the null terminator!!!

  // can we see it?
  Serial.println((char*)my_str);

  // can we do logical operations with it as-is?
  Serial.println((char*)my_str == 'Hello');

  // okay, it can't; wrong data type (and no terminator!), so let's do this:
  String str((char*)my_str);

  // can we see it now?
  Serial.println(str);

  // make comparisons
  Serial.println(str == 'Hello');

  // one more time just because
  Serial.println(str == "Hello");

  // one last thing...!
  Serial.println(sizeof(str));
}

void loop() {
  // nothing
}

And we get:

Hello    // as expected
0        // no surprise; wrong data type and no terminator in comparison value
Hello    // also, as expected
1        // YAY!
1        // YAY!
6        // as expected

Hope this helps someone!

Changing the width of Bootstrap popover

container: 'body' normally does the trick (see JustAnil's answer above), but there's a problem if your popover is in a modal. The z-index places it behind the modal when the popover's attached to body. This seems to be related to BS2 issue 5014, but I'm getting it on 3.1.1. You're not meant to use a container of body, but if you fix the code to

   $('#fubar').popover({
   trigger : 'hover',
   html    : true,
   dataContainer : '.modal-body',
   ...etc });

then you fix the z-index problem, but the popover width is still wrong.

The only fix I can find is to use container: 'body' and to add some extra css:

.popover { 
  max-width : 400px;
  z-index   : 1060;
}

Note that css solutions by themselves won't work.

I can't access http://localhost/phpmyadmin/

when you run Xampp, check the apache port no. ex: if it is displaying port 80, then type

http://localhost:80/phpmyadmin/

After that it will display automatically

http://localhost/phpmyadmin/

How to make a JFrame button open another JFrame class in Netbeans?

JFrame.setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

Filtering Pandas DataFrames on dates

If date column is the index, then use .loc for label based indexing or .iloc for positional indexing.

For example:

df.loc['2014-01-01':'2014-02-01']

See details here http://pandas.pydata.org/pandas-docs/stable/dsintro.html#indexing-selection

If the column is not the index you have two choices:

  1. Make it the index (either temporarily or permanently if it's time-series data)
  2. df[(df['date'] > '2013-01-01') & (df['date'] < '2013-02-01')]

See here for the general explanation

Note: .ix is deprecated.

VB.net Need Text Box to Only Accept Numbers

If Not Char.IsNumber(e.KeyChar) AndAlso Not e.KeyChar = "." AndAlso Not Char.IsControl(e.KeyChar) Then
            e.KeyChar = ""
End If

This allow you to use delete key and set decimal points

NSDictionary to NSArray?

Leaving aside the technical issues with the code you posted, you asked this:

To use this Dictionary Items in a Table View i have to transfer it to a NSArray, am i right?

The answer to which is: not necessarily. There's nothing intrinsic to the machinery of UITableView, UITableViewDataSource, or UITableViewDelegate that means that your data has to be in an array. You will need to implement various methods to tell the system how many rows are in your table, and what data appears in each row. Many people find it much more natural and efficient to answer those questions with an ordered data structure like an array. But there's no requirement that you do so. If you can write the code to implement those methods with the dictionary you started with, feel free!

Responsive web design is working on desktop but not on mobile device

Though it is answered above and it is right to use

<meta name="viewport" content="width=device-width, initial-scale=1">

but if you are using React and webpack then don't forget to close the element tag

<meta name="viewport" content="width=device-width, initial-scale=1" />

Iterating over dictionaries using 'for' loops

Iterating over dictionaries using 'for' loops

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    ...

How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?

It's not just for loops. The important word here is "iterating".

A dictionary is a mapping of keys to values:

d = {'x': 1, 'y': 2, 'z': 3} 

Any time we iterate over it, we iterate over the keys. The variable name key is only intended to be descriptive - and it is quite apt for the purpose.

This happens in a list comprehension:

>>> [k for k in d]
['x', 'y', 'z']

It happens when we pass the dictionary to list (or any other collection type object):

>>> list(d)
['x', 'y', 'z']

The way Python iterates is, in a context where it needs to, it calls the __iter__ method of the object (in this case the dictionary) which returns an iterator (in this case, a keyiterator object):

>>> d.__iter__()
<dict_keyiterator object at 0x7fb1747bee08>

We shouldn't use these special methods ourselves, instead, use the respective builtin function to call it, iter:

>>> key_iterator = iter(d)
>>> key_iterator
<dict_keyiterator object at 0x7fb172fa9188>

Iterators have a __next__ method - but we call it with the builtin function, next:

>>> next(key_iterator)
'x'
>>> next(key_iterator)
'y'
>>> next(key_iterator)
'z'
>>> next(key_iterator)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

When an iterator is exhausted, it raises StopIteration. This is how Python knows to exit a for loop, or a list comprehension, or a generator expression, or any other iterative context. Once an iterator raises StopIteration it will always raise it - if you want to iterate again, you need a new one.

>>> list(key_iterator)
[]
>>> new_key_iterator = iter(d)
>>> list(new_key_iterator)
['x', 'y', 'z']

Returning to dicts

We've seen dicts iterating in many contexts. What we've seen is that any time we iterate over a dict, we get the keys. Back to the original example:

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:

If we change the variable name, we still get the keys. Let's try it:

>>> for each_key in d:
...     print(each_key, '=>', d[each_key])
... 
x => 1
y => 2
z => 3

If we want to iterate over the values, we need to use the .values method of dicts, or for both together, .items:

>>> list(d.values())
[1, 2, 3]
>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]

In the example given, it would be more efficient to iterate over the items like this:

for a_key, corresponding_value in d.items():
    print(a_key, corresponding_value)

But for academic purposes, the question's example is just fine.

How to find index of list item in Swift?

Just use firstIndex method.

array.firstIndex(where: { $0 == searchedItem })

No visible cause for "Unexpected token ILLEGAL"

I got this error in chrome when I had an unterminated string after the line that the error pointed to. After closing the string the error went away.

Example with error:

var file = files[i]; // SyntaxError: Unexpected token ILLEGAL

jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
    + "<a href=\"javascript: something('"+file.id+');\">Error is here</a>";

Example without error:

var file = files[i]; // No error

jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
    + "<a href=\"javascript: something('"+file.id+"');\">Error was here</a>";

How do you check what version of SQL Server for a database using TSQL?

CREATE FUNCTION dbo.UFN_GET_SQL_SEVER_VERSION 
(
)
RETURNS sysname
AS
BEGIN
    DECLARE @ServerVersion sysname, @ProductVersion sysname, @ProductLevel sysname, @Edition sysname;

    SELECT @ProductVersion = CONVERT(sysname, SERVERPROPERTY('ProductVersion')), 
           @ProductLevel = CONVERT(sysname, SERVERPROPERTY('ProductLevel')),
           @Edition = CONVERT(sysname, SERVERPROPERTY ('Edition'));
    --see: http://support2.microsoft.com/kb/321185
    SELECT @ServerVersion = 
        CASE 
            WHEN @ProductVersion LIKE '8.00.%' THEN 'Microsoft SQL Server 2000'
            WHEN @ProductVersion LIKE '9.00.%' THEN 'Microsoft SQL Server 2005'
            WHEN @ProductVersion LIKE '10.00.%' THEN 'Microsoft SQL Server 2008'
            WHEN @ProductVersion LIKE '10.50.%' THEN 'Microsoft SQL Server 2008 R2'
            WHEN @ProductVersion LIKE '11.0%' THEN 'Microsoft SQL Server 2012'
            WHEN @ProductVersion LIKE '12.0%' THEN 'Microsoft SQL Server 2014'
        END

    RETURN @ServerVersion + N' ('+@ProductLevel + N'), ' + @Edition + ' - ' + @ProductVersion;

END
GO

How to make an executable JAR file?

Here it is in one line:

jar cvfe myjar.jar package.MainClass *.class

where MainClass is the class with your main method, and package is MainClass's package.

Note you have to compile your .java files to .class files before doing this.

c  create new archive
v  generate verbose output on standard output
f  specify archive file name
e  specify application entry point for stand-alone application bundled into an executable jar file

This answer inspired by Powerslave's comment on another answer.

PHP multiline string with PHP

The internal set of single quotes in your code is killing the string. Whenever you hit a single quote it ends the string and continues processing. You'll want something like:

$thisstring = 'this string is long \' in needs escaped single quotes or nothing will run';

Display tooltip on Label's hover?

You don't have to use hidden field. Use "title" property. It will show browser default tooltip. You can then use jQuery plugin (like before mentioned bootstrap tooltip) to show custom formatted tooltip.

<label for="male" title="Hello This Will Have Some Value">Hello ...</label>

Hint: you can also use css to trim text, that does not fit into the box (text-overflow property). See http://jsfiddle.net/8eeHs/

Declaring static constants in ES6 classes?

You can make the "constants" read-only (immutable) by freezing the class. e.g.

class Foo {
    static BAR = "bat"; //public static read-only
}

Object.freeze(Foo); 

/*
Uncaught TypeError: Cannot assign to read only property 'BAR' of function 'class Foo {
    static BAR = "bat"; //public static read-only
}'
*/
Foo.BAR = "wut";

Javascript - sort array based on another array

this is probably too late but, you could also use some modified version of the code below in ES6 style. This code is for arrays like:

var arrayToBeSorted = [1,2,3,4,5];
var arrayWithReferenceOrder = [3,5,8,9];

The actual operation :

arrayToBeSorted = arrayWithReferenceOrder.filter(v => arrayToBeSorted.includes(v));

The actual operation in ES5 :

arrayToBeSorted = arrayWithReferenceOrder.filter(function(v) {
    return arrayToBeSorted.includes(v);
});

Should result in arrayToBeSorted = [3,5]

Does not destroy the reference array.

Python list sort in descending order

You can simply do this:

timestamps.sort(reverse=True)

Scikit-learn train_test_split with indices

You can use pandas dataframes or series as Julien said but if you want to restrict your-self to numpy you can pass an additional array of indices:

from sklearn.model_selection import train_test_split
import numpy as np
n_samples, n_features, n_classes = 10, 2, 2
data = np.random.randn(n_samples, n_features)  # 10 training examples
labels = np.random.randint(n_classes, size=n_samples)  # 10 labels
indices = np.arange(n_samples)
x1, x2, y1, y2, idx1, idx2 = train_test_split(
    data, labels, indices, test_size=0.2)

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

how to delete files from amazon s3 bucket?

if you are trying to delete file using your own local host console then you can try running this python script assuming that you have have already assigned your access id and secret key in the system

import boto3

#my custom sesssion
aws_m=boto3.session.Session(profile_name="your-profile-name-on-local-host")
client=aws_m.client('s3')

#list bucket objects before deleting 
response = client.list_objects(
    Bucket='your-bucket-name'
)
for x in response.get("Contents", None):
    print(x.get("Key",None));

#delete bucket objects
response = client.delete_object(
    Bucket='your-bucket-name',
    Key='mydocs.txt'
)

#list bucket objects after deleting
response = client.list_objects(
    Bucket='your-bucket-name'
)
for x in response.get("Contents", None):
    print(x.get("Key",None));

How to convert a boolean array to an int array

The 1*y method works in Numpy too:

>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)
>>> 1*y                      # Method 1
array([0, 0, 1, 1])
>>> y.astype(int)            # Method 2
array([0, 0, 1, 1]) 

If you are asking for a way to convert Python lists from Boolean to int, you can use map to do it:

>>> testList = [False, False,  True,  True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]

Or using list comprehensions:

>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]

Does Android support near real time push notification?

Google is depreciating C2DM, but in its place their introducing GCM (Google Cloud Messaging) I dont think theirs any quota and its free! It does require Android 2.2+ though! http://developer.android.com/guide/google/gcm/index.html

How do I convert a IPython Notebook into a Python file via commandline?

If you want to convert all *.ipynb files from current directory to python script, you can run the command like this:

jupyter nbconvert --to script *.ipynb

.prop() vs .attr()

I think Tim said it quite well, but let's step back:

A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initial values from attributes with the same or similar names (value gets its initial value from the "value" attribute; href gets its initial value from the "href" attribute, but it's not exactly the same value; className from the "class" attribute). Other properties get their initial values in other ways: For instance, the parentNode property gets its value based on what its parent element is; an element always has a style property, whether it has a "style" attribute or not.

Let's consider this anchor in a page at http://example.com/testing.html:

<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>

Some gratuitous ASCII art (and leaving out a lot of stuff):

+-------------------------------------------+
|             HTMLAnchorElement             |
+-------------------------------------------+
| href:       "http://example.com/foo.html" |
| name:       "fooAnchor"                   |
| id:         "fooAnchor"                   |
| className:  "test one"                    |
| attributes:                               |
|    href:  "foo.html"                      |
|    name:  "fooAnchor"                     |
|    id:    "fooAnchor"                     |
|    class: "test one"                      |
+-------------------------------------------+

Note that the properties and attributes are distinct.

Now, although they are distinct, because all of this evolved rather than being designed from the ground up, a number of properties write back to the attribute they derived from if you set them. But not all do, and as you can see from href above, the mapping is not always a straight "pass the value on", sometimes there's interpretation involved.

When I talk about properties being properties of an object, I'm not speaking in the abstract. Here's some non-jQuery code:

var link = document.getElementById('fooAnchor');
alert(link.href);                 // alerts "http://example.com/foo.html"
alert(link.getAttribute("href")); // alerts "foo.html"

(Those values are as per most browsers; there's some variation.)

The link object is a real thing, and you can see there's a real distinction between accessing a property on it, and accessing an attribute.

As Tim said, the vast majority of the time, we want to be working with properties. Partially that's because their values (even their names) tend to be more consistent across browsers. We mostly only want to work with attributes when there is no property related to it (custom attributes), or when we know that for that particular attribute, the attribute and the property are not 1:1 (as with href and "href" above).

The standard properties are laid out in the various DOM specs:

These specs have excellent indexes and I recommend keeping links to them handy; I use them all the time.

Custom attributes would include, for instance, any data-xyz attributes you might put on elements to provide meta-data to your code (now that that's valid as of HTML5, as long as you stick to the data- prefix). (Recent versions of jQuery give you access to data-xyz elements via the data function, but that function is not just an accessor for data-xyz attributes [it does both more and less than that]; unless you actually need its features, I'd use the attr function to interact with data-xyz attribute.)

The attr function used to have some convoluted logic around getting what they thought you wanted, rather than literally getting the attribute. It conflated the concepts. Moving to prop and attr was meant to de-conflate them. Briefly in v1.6.0 jQuery went too far in that regard, but functionality was quickly added back to attr to handle the common situations where people use attr when technically they should use prop.

SQL Query to concatenate column values from multiple rows in Oracle

For those who must solve this problem using Oracle 9i (or earlier), you will probably need to use SYS_CONNECT_BY_PATH, since LISTAGG is not available.

To answer the OP, the following query will display the PID from Table A and concatenate all the DESC columns from Table B:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT a.pid, seq, description
              FROM table_a a, table_b b
              WHERE a.pid = b.pid(+)
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

There may also be instances where keys and values are all contained in one table. The following query can be used where there is no Table A, and only Table B exists:

SELECT pid, SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY pid ORDER BY pid, seq) rnum, pid, description
       FROM (
              SELECT pid, seq, description
              FROM table_b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1 AND PRIOR pid = pid
GROUP BY pid
ORDER BY pid;

All values can be reordered as desired. Individual concatenated descriptions can be reordered in the PARTITION BY clause, and the list of PIDs can be reordered in the final ORDER BY clause.


Alternately: there may be times when you want to concatenate all the values from an entire table into one row.

The key idea here is using an artificial value for the group of descriptions to be concatenated.

In the following query, the constant string '1' is used, but any value will work:

SELECT SUBSTR (MAX (SYS_CONNECT_BY_PATH (description, ', ')), 3) all_descriptions
FROM (
       SELECT ROW_NUMBER () OVER (PARTITION BY unique_id ORDER BY pid, seq) rnum, description
       FROM (
              SELECT '1' unique_id, b.pid, b.seq, b.description
              FROM table_b b
             )
      )
START WITH rnum = 1
CONNECT BY PRIOR rnum = rnum - 1;

Individual concatenated descriptions can be reordered in the PARTITION BY clause.

Several other answers on this page have also mentioned this extremely helpful reference: https://oracle-base.com/articles/misc/string-aggregation-techniques

How to add Certificate Authority file in CentOS 7

Find *.pem file and place it to the anchors sub-directory or just simply link the *.pem file to there.

yum install -y ca-certificates
update-ca-trust force-enable
sudo ln -s /etc/ssl/your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem
update-ca-trust

How do you add a timer to a C# console application

Use the System.Threading.Timer class.

System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.

There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.

It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically. This will avoid possibly premature garbage collection of your timer object.

Here's an example of a timer in a console application:

using System; 
using System.Threading; 
public static class Program 
{ 
    public static void Main() 
    { 
       Console.WriteLine("Main thread: starting a timer"); 
       Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); 
       Console.WriteLine("Main thread: Doing other work here...");
       Thread.Sleep(10000); // Simulating other work (10 seconds)
       t.Dispose(); // Cancel the timer now
    }
    // This method's signature must match the TimerCallback delegate
    private static void ComputeBoundOp(Object state) 
    { 
       // This method is executed by a thread pool thread 
       Console.WriteLine("In ComputeBoundOp: state={0}", state); 
       Thread.Sleep(1000); // Simulates other work (1 second)
       // When this method returns, the thread goes back 
       // to the pool and waits for another task 
    }
}

From the book CLR Via C# by Jeff Richter. By the way this book describes the rationale behind the 3 types of timers in Chapter 23, highly recommended.

How can I make my custom objects Parcelable?

I have found simplest way to create Parcelable class

enter image description here

Change the content of a div based on selection from dropdown menu

Meh too slow. Here's my example anyway :)
http://jsfiddle.net/cqDES/

$(function() {
    $('select').change(function() {
        var val = $(this).val();
        if (val) {
            $('div:not(#div' + val + ')').slideUp();
            $('#div' + val).slideDown();
        } else {
            $('div').slideDown();
        }
    });
});

Remove Duplicates from range of cells in excel vba

To remove duplicates from a single column

 Sub removeDuplicate()
 'removeDuplicate Macro
 Columns("A:A").Select
 ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _ 
 Header:=xlNo 
 Range("A1").Select
 End Sub

if you have header then use Header:=xlYes

Increase your range as per your requirement.
you can make it to 1000 like this :

ActiveSheet.Range("$A$1:$A$1000")

More info here here

Is it possible to run a .NET 4.5 app on XP?

Try mono:

http://www.go-mono.com/mono-downloads/download.html

This download works on all versions of Windows XP, 2003, Vista and Windows 7.

ascending/descending in LINQ - can one change the order via parameter?

In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...

var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()

if(sortAscending) {
    qry = qry.OrderBy(x=>x.Property);
} else {
    qry = qry.OrderByDescending(x=>x.Property);
}

Any use? You can create the entire "order" dynamically, but it is more involved...

Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.

How to group by week in MySQL?

Just ad this in the select :

DATE_FORMAT($yourDate, \'%X %V\') as week

And

group_by(week);

Choice between vector::resize() and vector::reserve()

The two functions do vastly different things!

The resize() method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size(), iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[].

The reserve() method only allocates memory, but leaves it uninitialized. It only affects capacity(), but size() will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.

So it depends on what you want. If you want an array of 1000 default items, use resize(). If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use reserve().

EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where reserve() makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.

EDIT2: Ad question edit: If you have initial estimate, then reserve() that estimate. If it turns out to be not enough, just let the vector do it's thing.

How to execute a stored procedure inside a select query

"Not Possible". You can use a function instead of the stored procedure.

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

create function dbo.RemoveNonNumericChar(@str varchar(500))  
returns varchar(500)  
begin  
declare @startingIndex int  
set @startingIndex=0  
while 1=1  
begin  
    set @startingIndex= patindex('%[^0-9]%',@str)  
    if @startingIndex <> 0  
    begin  
        set @str = replace(@str,substring(@str,@startingIndex,1),'')  
    end  
    else    break;   
end  
return @str  
end

go  

select dbo.RemoveNonNumericChar('aisdfhoiqwei352345234@#$%^$@345345%^@#$^')  

Age from birthdate in python

Extend to Danny W. Adair Answer, to get month also

def calculate_age(b):
    t = date.today()
    c = ((t.month, t.day) < (b.month, b.day))
    c2 = (t.day< b.day)
    return t.year - b.year - c,c*12+t.month-b.month-c2

AngularJS toggle class using ng-class

autoscroll will be defined and modified in the controller:

<span ng-class= "autoscroll?'class_if_true':'class_if_false'"></span>

Add multiple classes based on condition by:

<span ng-class= "autoscroll?'first second third':'classes_if_false'"></span>

QUERY syntax using cell reference

Copied from Web Applications:

=QUERY(Responses!B1:I, "Select B where G contains '"&$B1&"'")

Spool Command: Do not output SQL statement to file

Exec the query in TOAD or SQL DEVELOPER

---select /*csv*/ username, user_id, created from all_users;

Save in .SQL format in "C" drive

--- x.sql

execute command

---- set serveroutput on
     spool y.csv
     @c:\x.sql
     spool off;

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

Shorter syntax

select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
  DELETE TOP (10000) LargeTable 
  WHERE readTime < dateadd(MONTH,-7,GETDATE())
END

NoClassDefFoundError - Eclipse and Android

This happens quite very often to me.

Last time that happened I can remembered was caused by switching the Eclipse ADT (Google special edition) to Android Studio, and switching back. I basically tried all methods that I can found on stackoverflow which didn't work for me.

Eventually, I got the app working again (no more NoCalssDeffoundError) by switching my IDE to original Eclipse (Kepler) with ADT.

Java SimpleDateFormat for time zone with a colon separator?

if you used the java 7, you could have used the following Date Time Pattern. Seems like this pattern is not supported in the Earlier version of java.

String dateTimeString  = "2010-03-01T00:00:00-08:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date date = df.parse(dateTimeString);

For More information refer to the SimpleDateFormat documentation.

Initialising an array of fixed size in python

>>> n = 5                     #length of list
>>> list = [None] * n         #populate list, length n with n entries "None"
>>> print(list)
[None, None, None, None, None]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, None, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, 1, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, 1, 1, 1]

or with really nothing in the list to begin with:

>>> n = 5                     #length of list
>>> list = []                 # create list
>>> print(list)
[]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1]

on the 4th iteration of append:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1]

5 and all subsequent:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1,1]

Error: No module named psycopg2.extensions

first install apt-get install python-setuptools

then try easy_install psycopg2

android TextView: setting the background color dynamically doesn't work

here is in little detail,

if you are in activity use this

textview.setBackground(ContextCompat.getColor(this,R.color.yourcolor));

if you are in fragment use below code

textview.setBackground(ContextCompat.getColor(getActivity(),R.color.yourcolor));

if you are in recyclerview adapter use below code

textview.setBackground(ContextCompat.getColor(context,R.color.yourcolor));

// use holder.textview if you are in onBindviewholder
//here context is passed from fragment

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

ASP.NET - How to write some html in the page? With Response.Write?

You can go with the literal control of ASP.net or you can use panels or the purpose.

How to make use of ng-if , ng-else in angularJS

You can write as:

<div class="case" ng-if="mydata.id === '5' ">
    <p> this will execute </p>
</div>
<div class="case" ng-if="mydata.id !== '5' ">
    <p> this will execute </p>
</div> 

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

Set Jackson Timezone for Date deserialization

Your date object is probably ok, since you sent your date encoded in ISO format with GMT timezone and you are in EST when you print your date.

Note that Date objects perform timezone translation at the moment they are printed. You can check if your date object is correct with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
System.out.println (cal);

What are Keycloak's OAuth2 / OpenID Connect endpoints?

After much digging around we were able to scrape the info more or less (mainly from Keycloak's own JS client lib):

  • Authorization Endpoint: /auth/realms/{realm}/tokens/login
  • Token Endpoint: /auth/realms/{realm}/tokens/access/codes

As for OpenID Connect UserInfo, right now (1.1.0.Final) Keycloak doesn't implement this endpoint, so it is not fully OpenID Connect compliant. However, there is already a patch that adds that as of this writing should be included in 1.2.x.

But - Ironically Keycloak does send back an id_token in together with the access token. Both the id_token and the access_token are signed JWTs, and the keys of the token are OpenID Connect's keys, i.e:

"iss":  "{realm}"
"sub":  "5bf30443-0cf7-4d31-b204-efd11a432659"
"name": "Amir Abiri"
"email: "..."

So while Keycloak 1.1.x is not fully OpenID Connect compliant, it does "speak" in OpenID Connect language.

How to convert WebResponse.GetResponseStream return into a string?

You can use StreamReader.ReadToEnd(),

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

How can I rename a project folder from within Visual Studio?

See item 3 in the linked article.


  1. Close the solution and the IDE.
  2. In Windows Explorer: Change the directory name to the new name.
  3. In Windows Explorer: Open the .sln file with a text editor.
  4. Change the directory name to the new name and save.
  5. Restart the IDE and open the solution from menu FileRecent Files menu if it doesn't start automatically.
  6. Click on the project folder in Solution Explorer and check the path property in the properties at the bottom. It will now be referencing to the new project folder.

It worked for me.

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Reverse a changelist submission

You cannot undo a successful changelist submission, but you can reverse previously submitted changes in two ways:

Rollback restores a file or set of files back to a specified changelist, date or revision. Any changes made after that point in time are not retained. Back out removes specific changes made at a given changelist, date or revision but allows a user to keep changes made in subsequent revisions.

For details please refer to https://www.perforce.com/perforce/r13.1/manuals/p4v/Working_with_changelists.html

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

How to concatenate columns in a Postgres SELECT?

it is better to use CONCAT function in PostgreSQL for concatenation

eg : select CONCAT(first_name,last_name) from person where pid = 136

if you are using column_a || ' ' || column_b for concatenation for 2 column , if any of the value in column_a or column_b is null query will return null value. which may not be preferred in all cases.. so instead of this

||

use

CONCAT

it will return relevant value if either of them have value

Javascript Get Values from Multiple Select Option Box

Also, change this:

    SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;

to

    SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;

The reason is that for the first time the variable SelBranchVal will be empty

Rename a column in MySQL

https://dev.mysql.com/doc/refman/8.0/en/alter-table.html

For MySQL 8

alter table creditReportXml_temp change column applicationID applicantID int(11);

What's the difference between SoftReference and WeakReference in Java?

In Java; order from strongest to weakest, there are: Strong, Soft, Weak and Phantom

A Strong reference is a normal reference that protects the referred object from collection by GC. i.e. Never garbage collects.

A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError.

A Weak reference is a reference that does not protect a referenced object from collection by GC. i.e. garbage collects when no Strong or Soft refs.

A Phantom reference is a reference to an object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed.

Source

Analogy: Assume a JVM is a kingdom, Object is a king of the kingdom, and GC is an attacker of the kingdom who tries to kill the king(object).

  • When King is Strong, GC can not kill him.
  • When King is Soft, GC attacks him but King rule the kingdom with protection until resource are available.
  • When King is Weak, GC attacks him but rule the kingdom without protection.
  • When king is Phantom, GC already killed him but king is available via his soul.

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

A simple plugin in Android will help you Step 1. Go to Settings Step 2. Click on Plugin Step 3. Search for Android Drawable Importer Step 4. Install plugin and restart

How to use?

Go to File>New>Batch Drawable Import

Enjoy

How to draw a filled circle in Java?

/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
    g.setColor(Color.RED);
    g.fillOval(50,50,20,20);
}

g.fillOval(x-axis,y-axis,width,height);

How to decode a Base64 string?

Isn't encoding taking the text TO base64 and decoding taking base64 BACK to text? You seem be mixing them up here. When I decode using this online decoder I get:

BASE64: blahblah
UTF8: nVnV

not the other way around. I can't reproduce it completely in PS though. See sample below:

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("blahblah"))
nV?nV?

PS > [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nVnV"))
blZuVg==

EDIT I believe you're using the wrong encoder for your text. The encoded base64 string is encoded from UTF8(or ASCII) string.

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

PS > [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
????

PS > [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

SQL Server remove milliseconds from datetime

select * from table
     where DATEADD(ms, DATEDIFF(ms, '20000101', date), '20000101') > '2010-07-20 03:21:52'

You'll have to trim milliseconds before comparison, which will be slow over many rows

Do one of these to fix this:

  • created a computed column with the expressions above to compare against
  • remove milliseconds on insert/update to avoid the read overhead
  • If SQL Server 2008, use datetime2(0)

How to Check byte array empty or not?

You must swap the order of your test:

From:

if (Attachment.Length > 0 && Attachment != null)

To:

if (Attachment != null && Attachment.Length > 0 )

The first version attempts to dereference Attachment first and therefore throws if it's null. The second version will check for nullness first and only go on to check the length if it's not null (due to "boolean short-circuiting").


[EDIT] I come from the future to tell you that with later versions of C# you can use a "null conditional operator" to simplify the code above to:

if (Attachment?.Length > 0)
        

IOException: The process cannot access the file 'file path' because it is being used by another process

As other answers in this thread have pointed out, to resolve this error you need to carefully inspect the code, to understand where the file is getting locked.

In my case, I was sending out the file as an email attachment before performing the move operation.

So the file got locked for couple of seconds until SMTP client finished sending the email.

The solution I adopted was to move the file first, and then send the email. This solved the problem for me.

Another possible solution, as pointed out earlier by Hudson, would've been to dispose the object after use.

public static SendEmail()
{
           MailMessage mMailMessage = new MailMessage();
           //setup other email stuff

            if (File.Exists(attachmentPath))
            {
                Attachment attachment = new Attachment(attachmentPath);
                mMailMessage.Attachments.Add(attachment);
                attachment.Dispose(); //disposing the Attachment object
            }
} 

How do I create a branch?

Create a new branch using the svn copy command as follows:

$ svn copy svn+ssh://host.example.com/repos/project/trunk \
           svn+ssh://host.example.com/repos/project/branches/NAME_OF_BRANCH \
      -m "Creating a branch of project"

Converting DateTime format using razor

Try:

@item.Date.ToString("dd MMM yyyy")

or you could use the [DisplayFormat] attribute on your view model:

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime Date { get; set }

and in your view simply:

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

Display html text in uitextview

You can have a look the OHAttributedLabel classes, I used these to overcome this kind of problem with my textField. In this they have overridden the drawRect method to obtain the required style.

https://github.com/AliSoftware/OHAttributedLabel

Extension methods must be defined in a non-generic static class

if you do not intend to have static functions just get rid of the "this" keyword in the arguments.

How do I disable orientation change on Android?

Add

android:configChanges="keyboardHidden|orientation|screenSize" 

to your manifest.

Getting path of captured image in Android using camera intent

Try this method to get path of original image captured by camera.

public String getOriginalImagePath() {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToLast();

        return cursor.getString(column_index_data);
    }

This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

Android studio, gradle and NDK

With the update of Android Studio to 1.0, the NDK toolchain support improved immensely (note: please read my updates at the bottom of this post to see usage with the new experimental Gradle plugin and Android Studio 1.5).

Android Studio and the NDK are integrated well enough so that you just need to create an ndk{} block in your module's build.gradle, and set your source files into the (module)/src/main/jni directory - and you're done!

No more ndk-build from the command line.

I've written all about it in my blog post here: http://www.sureshjoshi.com/mobile/android-ndk-in-android-studio-with-swig/

The salient points are:

There are two things you need to know here. By default, if you have external libs that you want loaded into the Android application, they are looked for in the (module)/src/main/jniLibs by default. You can change this by using setting sourceSets.main.jniLibs.srcDirs in your module’s build.gradle. You’ll need a subdirectory with libraries for each architecture you’re targeting (e.g. x86, arm, mips, arm64-v8a, etc…)

The code you want to be compiled by default by the NDK toolchain will be located in (module)/src/main/jni and similarly to above, you can change it by setting sourceSets.main.jni.srcDirs in your module’s build.gradle

and put this into your module's build.gradle:

ndk {
  moduleName "SeePlusPlus" // Name of C++ module (i.e. libSeePlusPlus)
  cFlags "-std=c++11 -fexceptions" // Add provisions to allow C++11 functionality
  stl "gnustl_shared" // Which STL library to use: gnustl or stlport
}

That's the process of compiling your C++ code, from there you need to load it, and create wrappers - but judging from your question, you already know how to do all that, so I won't re-hash.

Also, I've placed a Github repo of this example here: http://github.com/sureshjoshi/android-ndk-swig-example

UPDATE: June 14, 2015

When Android Studio 1.3 comes out, there should be better support for C++ through the JetBrains CLion plugin. I'm currently under the assumption that this will allow Java and C++ development from within Android Studio; however I think we'll still need to use the Gradle NDK section as I've stated above. Additionally, I think there will still be the need to write Java<->C++ wrapper files, unless CLion will do those automatically.

UPDATE: January 5, 2016

I have updated my blog and Github repo (in the develop branch) to use Android Studio 1.5 with the latest experimental Gradle plugin (0.6.0-alpha3).

http://www.sureshjoshi.com/mobile/android-ndk-in-android-studio-with-swig/ http://github.com/sureshjoshi/android-ndk-swig-example

The Gradle build for the NDK section now looks like this:

android.ndk {
    moduleName = "SeePlusPlus" // Name of C++ module (i.e. libSeePlusPlus)
    cppFlags.add("-std=c++11") // Add provisions to allow C++11 functionality
    cppFlags.add("-fexceptions")
    stl = "gnustl_shared" // Which STL library to use: gnustl or stlport
}

Also, quite awesomely, Android Studio has auto-complete for C++-Java generated wrappers using the 'native' keyword:

Example of auto-complete of C++-Java wrapper

However, it's not completely rosy... If you're using SWIG to wrap a library to auto-generate code, and then try to use the native keyword auto-generation, it will put the code in the wrong place in your Swig _wrap.cxx file... So you need to move it into the "extern C" block:

C++-Java wrapper moved to correct location

UPDATE: October 15, 2017

I'd be remiss if I didn't mention that Android Studio 2.2 onwards has essentially 'native' (no pun) support for the NDK toolchain via Gradle and CMake. Now, when you create a new project, just select C++ support and you're good to go.

You'll still need to generate your own JNI layer code, or use the SWIG technique I've mentioned above, but the scaffolding of a C++ in Android project is trivial now.

Changes in the CMakeLists file (which is where you place your C++ source files) will be picked up by Android Studio, and it'll automatically re-compile any associated libraries.

How to pass dictionary items as function arguments in python?

*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.

data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}


def my_function(**data):
    schoolname  = data['school']
    cityname = data['city']
    standard = data['class']
    studentname = data['name']

You can call the function like this:

my_function(**data)

How to rename a directory/folder on GitHub website?

You could use a workflow for this.

# ./.github/workflows/rename.yaml
name: Rename Directory

on:
  push:

jobs:
  rename:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: git mv old_name new_name
      - uses: EndBug/[email protected]

Then just delete the workflow file, which you can do in the UI

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How to access host port from docker container

For docker-compose using bridge networking to create a private network between containers, the accepted solution using docker0 doesn't work because the egress interface from the containers is not docker0, but instead, it's a randomly generated interface id, such as:

$ ifconfig

br-02d7f5ba5a51: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.32.1  netmask 255.255.240.0  broadcast 192.168.47.255

Unfortunately that random id is not predictable and will change each time compose has to recreate the network (e.g. on a host reboot). My solution to this is to create the private network in a known subnet and configure iptables to accept that range:

Compose file snippet:

version: "3.7"

services:
  mongodb:
    image: mongo:4.2.2
    networks:
    - mynet
    # rest of service config and other services removed for clarity

networks:
  mynet:
    name: mynet
    ipam:
      driver: default
      config:
      - subnet: "192.168.32.0/20"

You can change the subnet if your environment requires it. I arbitrarily selected 192.168.32.0/20 by using docker network inspect to see what was being created by default.

Configure iptables on the host to permit the private subnet as a source:

$ iptables -I INPUT 1 -s 192.168.32.0/20 -j ACCEPT

This is the simplest possible iptables rule. You may wish to add other restrictions, for example by destination port. Don't forget to persist your iptables rules when you're happy they're working.

This approach has the advantage of being repeatable and therefore automatable. I use ansible's template module to deploy my compose file with variable substitution and then use the iptables and shell modules to configure and persist the firewall rules, respectively.

How to return first 5 objects of Array in Swift?

Swift 4 with saving array types

extension Array {
    func take(_ elementsCount: Int) -> [Element] {
        let min = Swift.min(elementsCount, count)
        return Array(self[0..<min])
    }
}

How can I make a CSS table fit the screen width?

CSS:

table { 
    table-layout:fixed;
}

Update with CSS from the comments:

td { 
    overflow: hidden; 
    text-overflow: ellipsis; 
    word-wrap: break-word;
}

For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):

@media only screen and (max-width: 480px) {
    /* horizontal scrollbar for tables if mobile screen */
    .tablemobile {
        overflow-x: auto;
        display: block;
    }
}

Sufficient enough.

cannot import name patterns

Seems you are using outdated version of django.. Simply update django and try again.. Following command will update your django version..

pip install --upgrade django

How to compile C program on command line using MinGW?

I had the same problem with .c files that contained functions (not main() of my program). For example, my header files were "fact.h" and "fact.c", and my main program was "main.c" so my commands were like this:

E:\proj> gcc -c fact.c

Now I had an object file of fact.c (fact.o). after that:

E:\proj>gcc -o prog.exe fact.o main.c

Then my program (prog.exe) was ready to use and worked properly. I think that -c after gcc was important, because it makes object files that can attach to make the program we need. Without using -c, gcc ties to find main in your program and when it doesn't find it, it gives you this error.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Thanks to @HBP for paving the way here!

I found this to add a little flexibility to the solution.

The RegEx has been updated to accommodate times before noon.

This solution allows you to pass any string to it. As long as a valid time (in this format 18:00 || 18:00:00 || 3:00 || 3:00:00) is somewhere in that string, you're good to go.

Note: you can use just the militaryToTweleveHourConverter or take the guts out of the parseTime variable. However, I'm formatting a date from a database with date-fns then passing that formatted date to the converter.

Totally works. Hope this helps.

import dateFns from 'date-fns';



//* +---------------------------+
//* Format ex. Sat 1/1/18 1:00pm
//* +---------------------------+
const formatMonthDayYearTime = date =>
  militaryToTweleveHourConverter(
    dateFns.format(new Date(date), 'ddd M/DD/YY H:mm')
  );

//* +-------------------------------+
//* Convert MILITARY TIME to 12 hour
//* +-------------------------------+
const militaryToTweleveHourConverter = time => {
  const getTime = time.split(' ');

  const parseTime = getTime.map(res => {
    // Check for correct time format and split into components or return non-time units unaltered
    let timeUnit = res
      .toString()
      .match(/^([\d]|[0-1]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [res];

    console.log('timeUnit', timeUnit);
    // If the time format is matched, it will break the components into an array
    // ie. ["19:00", "19", ":", "00", undefined]
    if (timeUnit.length > 1) {
      // Remove full string match value
      timeUnit = timeUnit.slice(1);
      // Set am/pm and assign it to the last index in the array
      timeUnit[5] = timeUnit[0] < 12 ? 'am' : 'pm';
      // Adjust hours by subtracting 12 from anything greater than 12 and replace the value in the hours index
      timeUnit[0] = timeUnit[0] % 12 || 12;
    }
    // return adjusted time or original string
    return timeUnit.join('');
  });
  // Re-assemble the array pieces into a string
  return parseTime.join(' ');
};


console.log(formatMonthDayYearTime('Sat 9/17/18 18:30'));
// console log returns the following
// Mon 9/17/18 6:30pm

console.log(militaryToTweleveHourConverter('18:30'));
// console log returns the following
// 6:30pm

console.log(militaryToTweleveHourConverter('18:30:09'));
// console log returns the following
// 6:30:09pm

console.log(militaryToTweleveHourConverter('8:30:09'));
// console log returns the following
// 8:30:09am

Get the data received in a Flask request

If you post JSON with content type application/json, use request.get_json() to get it in Flask. If the content type is not correct, None is returned. If the data is not JSON, an error is raised.

@app.route("/something", methods=["POST"])
def do_something():
    data = request.get_json()

How do I get the HTTP status code with jQuery?

I think you should also implement the error function of the $.ajax method.

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
        alert(xhr.status); 
    },
    error: function(xhr, statusText, err){
        alert("Error:" + xhr.status); 
    }
});

How to get the Development/Staging/production Hosting Environment in ConfigureServices

TL;DR

Set an environment variable called ASPNETCORE_ENVIRONMENT with the name of the environment (e.g. Production). Then do one of two things:

  • Inject IHostingEnvironment into Startup.cs, then use that (env here) to check: env.IsEnvironment("Production"). Do not check using env.EnvironmentName == "Production"!
  • Use either separate Startup classes or individual Configure/ConfigureServices functions. If a class or the functions match these formats, they will be used instead of the standard options on that environment.
    • Startup{EnvironmentName}() (entire class) || example: StartupProduction()
    • Configure{EnvironmentName}() || example: ConfigureProduction()
    • Configure{EnvironmentName}Services() || example: ConfigureProductionServices()

Full explanation

The .NET Core docs describe how to accomplish this. Use an environment variable called ASPNETCORE_ENVIRONMENT that's set to the environment you want, then you have two choices.

Check environment name

From the docs:

The IHostingEnvironment service provides the core abstraction for working with environments. This service is provided by the ASP.NET hosting layer, and can be injected into your startup logic via Dependency Injection. The ASP.NET Core web site template in Visual Studio uses this approach to load environment-specific configuration files (if present) and to customize the app’s error handling settings. In both cases, this behavior is achieved by referring to the currently specified environment by calling EnvironmentName or IsEnvironment on the instance of IHostingEnvironment passed into the appropriate method.

NOTE: Checking the actual value of env.EnvironmentName is not recommended!

If you need to check whether the application is running in a particular environment, use env.IsEnvironment("environmentname") since it will correctly ignore case (instead of checking if env.EnvironmentName == "Development" for example).

Use separate classes

From the docs:

When an ASP.NET Core application starts, the Startup class is used to bootstrap the application, load its configuration settings, etc. (learn more about ASP.NET startup). However, if a class exists named Startup{EnvironmentName} (for example StartupDevelopment), and the ASPNETCORE_ENVIRONMENT environment variable matches that name, then that Startup class is used instead. Thus, you could configure Startup for development, but have a separate StartupProduction that would be used when the app is run in production. Or vice versa.

In addition to using an entirely separate Startup class based on the current environment, you can also make adjustments to how the application is configured within a Startup class. The Configure() and ConfigureServices() methods support environment-specific versions similar to the Startup class itself, of the form Configure{EnvironmentName}() and Configure{EnvironmentName}Services(). If you define a method ConfigureDevelopment() it will be called instead of Configure() when the environment is set to development. Likewise, ConfigureDevelopmentServices() would be called instead of ConfigureServices() in the same environment.

jquery/javascript convert date string to date

I would grab date.js or else you will need to roll your own formatting function.

How to emulate GPS location in the Android Emulator?

In eclipse:

You may have to drag the DDMS window down. 'Location Controls' is located under 'Telephony Actions' and may be hidden by a normally sized console view ( the bar with console, LogCat etc may be covering it!)

~

How to display length of filtered ng-repeat data

For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.

Assuming your list of people is in data variable and you filter people using query model, the following code will work for you:

<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
  • {{data.length}} - prints total number of people
  • {{(data|filter:query).length}} - prints filtered number of people

Note that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.

New Feature in Angular 1.3

AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.

<div ng-repeat="person in data | filter:query as results">
    <!-- template ... -->
</div>

<p>Number of visible people: {{results.length}}</p>

The alias expression will prevent multiple filter execution issue.

I hope that will help.

No Activity found to handle Intent : android.intent.action.VIEW

Answer by Maragues made me check out logcat output. Appears that the path you pass to Uri needs to be prefixed with
file:/

Since it is a local path to your storage.

You may want too look at the path itself too.

`05-04 16:37:37.597: WARN/System.err(4065): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=/mnt/sdcard/mnt/sdcard/audio-android.3gp typ=audio/mp3 }`

Mount point seems to appear twice in the full path.

Converting from hex to string

string str = "47-61-74-65-77-61-79-53-65-72-76-65-72";
string[] parts = str.Split('-');

foreach (string val in parts)
{ 
    int x;
    if (int.TryParse(val, out x))
    {
         Console.Write(string.Format("{0:x2} ", x);
    }
}
Console.WriteLine();

You can split the string at the -
Convert the text to ints (int.TryParse)
Output the int as a hex string {0:x2}

jQuery: selecting each td in a tr

You can simply do the following inside your TR loop:

$(this).find('td').each (function() {
  // do your cool stuff
});                          

ng-repeat: access key and value for each object in array of objects

A repeater inside a repeater

<div ng-repeat="step in steps">
    <div ng-repeat="(key, value) in step">
        {{key}} : {{value}}
    </div>
</div>

Get user input from textarea

I think you should not use spaces between the [(ngModel)] the = and the str. Then you should use a button or something like this with a click function and in this function you can use the values of your inputfields.

<input id="str" [(ngModel)]="str"/>
<button (click)="sendValues()">Send</button>

and in your component file

str: string;
sendValues(): void {
//do sth with the str e.g. console.log(this.str);
}

Hope I can help you.

add to array if it isn't there already

You should use the PHP function in_array (see http://php.net/manual/en/function.in-array.php).

if (!in_array($value, $array))
{
    $array[] = $value; 
}

This is what the documentation says about in_array:

Returns TRUE if needle is found in the array, FALSE otherwise.