Programs & Examples On #Pre packaged

Format date with Moment.js

You Probably Don't Need Moment.js Anymore

Moment is great time manipulation library but it's considered as a legacy project, and the team is recommending to use other libraries.

date-fns is one of the best lightweight libraries, it's modular, so you can pick the functions you need and reduce bundle size (issue & statement).

Another common argument against using Moment in modern applications is its size. Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles.

import { format } from 'date-fns' // 21K (gzipped: 5.8K)
import moment from 'moment' // 292.3K (gzipped: 71.6K)

Format date with date-fns:

// moment.js
moment().format('MM/DD/YYYY');
// => "12/18/2020"

// date-fns
import { format } from 'date-fns'
format(new Date(), 'MM/dd/yyyy');
// => "12/18/2020"

More on cheat sheet with the list of functions which you can use to replace moment.js: You-Dont-Need-Momentjs

Is it good practice to use the xor operator for boolean checks?

I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.

My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.

As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.

download file using an ajax request

Update April 27, 2015

Up and coming to the HTML5 scene is the download attribute. It's supported in Firefox and Chrome, and soon to come to IE11. Depending on your needs, you could use it instead of an AJAX request (or using window.location) so long as the file you want to download is on the same origin as your site.

You could always make the AJAX request/window.location a fallback by using some JavaScript to test if download is supported and if not, switching it to call window.location.

Original answer

You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download. Instead, you could use a success function to navigate to download.php. This will open the download prompt but won't change the current page.

$.ajax({
    url: 'download.php',
    type: 'POST',
    success: function() {
        window.location = 'download.php';
    }
});

Even though this answers the question, it's better to just use window.location and avoid the AJAX request entirely.

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

What is the easiest way to push an element to the beginning of the array?

What about using the unshift method?

ary.unshift(obj, ...) ? ary
Prepends objects to the front of self, moving other elements upwards.

And in use:

irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"

How to embed a .mov file in HTML?

<object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320" height="256" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
    <param name="src" value="sample.mov">
    <param name="qtsrc" value="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov">
    <param name="autoplay" value="true">
    <param name="loop" value="false">
    <param name="controller" value="true">
    <embed src="sample.mov" qtsrc="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov" width="320" height="256" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>
</object>

source is the first search result of the Google

How to Add Date Picker To VBA UserForm

You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.

I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.

How to add content to html body using JS?

Working demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
onload = function(){
var divg = document.createElement("div");
divg.appendChild(document.createTextNode("New DIV"));
document.body.appendChild(divg);
};
</script>
</head>
<body>

</body>
</html>

jQuery: value.attr is not a function

The second parameter of the callback function passed to each() will contain the actual DOM element and not a jQuery wrapper object. You can call the getAttribute() method of the element:

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function(key, value) {
        console.info(key, ": ", value);
        console.info("cat_id: ", value.getAttribute('cat_id'));
    });
});

Or wrap the element in a jQuery object yourself:

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function(key, value) {
        console.info(key, ": ", value);
        console.info("cat_id: ", $(value).attr('cat_id'));
    });
});

Or simply use $(this):

$('#category_sorting_form_save').click(function() {
    var elements = $("#category_sorting_elements > div");
    $.each(elements, function() {
        console.info("cat_id: ", $(this).attr('cat_id'));
    });
});

Python Web Crawlers and "getting" html source code

Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).

I recommend you using the stdlib module urllib2, it will allow you to comfortably get web resources. Example:

import urllib2

response = urllib2.urlopen("http://google.de")
page_source = response.read()

For parsing the code, have a look at BeautifulSoup.

BTW: what exactly do you want to do:

Just for background, I need to download a page and replace any img with ones I have

Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests is a very nice high-level library which is easier to use than urllib2.

Best way to parseDouble with comma as decimal separator?

Double.parseDouble(p.replace(',','.'))

...is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.

Basically replace(char,char) is about 10 times quicker and since you'll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out... Certainly doesn't on my system.

How to differ sessions in browser-tabs?

Note: The solution here needs to be done at application design stage. It would be difficult to engineer this in later.

Use a hidden field to pass around the session identifier.

For this to work each page must include a form:

<form method="post" action="/handler">

  <input type="hidden" name="sessionId" value="123456890123456890ABCDEF01" />
  <input type="hidden" name="action" value="" />

</form>

Every action on your side, including navigation, POSTs the form back (setting the action as appropriate). For "unsafe" requests, you could include another parameter, say containing a JSON value of the data to be submitted:

<input type="hidden" name="action" value="completeCheckout" />
<input type="hidden" name="data" value='{ "cardNumber" : "4111111111111111", ... ' />

As there are no cookies, each tab will be independent and will have no knowledge of other sessions in the same browser.

Lots of advantages, particularly when it comes to security:

  • No reliance on JavaScript or HTML5.
  • Inherently protects against CSRF.
  • No reliance on cookies, so protects against POODLE.
  • Not vulnerable to session fixation.
  • Can prevent back button use, which is desirable when you want users to follow a set path through your site (which means logic bugs that can sometimes be attacked by out-of-order requests, can be prevented).

Some disadvantages:

  • Back button functionality may be desired.
  • Not very effective with caching as every action is a POST.

Further information here.

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

cat /proc/meminfo | grep MemTotal or free gives you the exact amount of RAM your server has. This is not "available memory".

I guess your issue comes up when you have a VM and you would like to calculate the full amount of memory hosted by the hypervisor but you will have to log into the hypervisor in that case.

cat /proc/meminfo | grep MemTotal

is equivalent to

 getconf -a | grep PAGES | awk 'BEGIN {total = 1} {if (NR == 1 || NR == 3) total *=$NF} END {print total / 1024" kB"}'

simple Jquery hover enlarge

If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:

$(document).ready(function() {
    $("[id^=content]").hover(function() {
        $(this).addClass('transition');
    }, function() {
        $(this).removeClass('transition');
    });
});

Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.

Converting PHP result array to JSON

json_encode is available in php > 5.2.0:

echojson_encode($row);

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.

for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE

Like this:

declare @Source table
(
name varchar(30),
age decimal(23,0)
)

insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);


MERGE beautiful  AS Tg
using  @source as Sc
on tg.namet=sc.name 

when matched then update 
set tg.age=sc.age

when not matched then 
insert (name, age) VALUES
(SC.name, sc.age);

How do I declare an array with a custom class?

To default-initialize an array of Ts, T must be default constructible. Normally the compiler gives you a default constructor for free. However, since you declared a constructor yourself, the compiler does not generate a default constructor.

Your options:

  • add a default constructor to name, if that makes sense (I don't think so, but I don't know the problem domain);
  • initialize all the elements of the array upon declaration (you can do this because name is an aggregate);

      name someName[4] = { { "Arthur", "Dent" },
                           { "Ford", "Prefect" },
                           { "Tricia", "McMillan" },
                           { "Zaphod", "Beeblebrox" }
                         };
    
  • use a std::vector instead, and only add element when you have them constructed.

vertical-align image in div

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to the <div> this css:

display:flex;
align-items:center;
justify-content:center;

JSFiddle demo

Live Example:

_x000D_
_x000D_
.img_thumb {_x000D_
    float: left;_x000D_
    height: 120px;_x000D_
    margin-bottom: 5px;_x000D_
    margin-left: 9px;_x000D_
    position: relative;_x000D_
    width: 147px;_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    border-radius: 3px;_x000D_
    display:flex;_x000D_
    align-items:center;_x000D_
    justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
    <a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
       <img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to apply a patch generated with git format-patch?

Note: You can first preview what your patch will do:

First the stats:

git apply --stat a_file.patch

Then a dry run to detect errors:

git apply --check a_file.patch

Finally, you can use git am to apply your patch as a commit. This also allows you to sign off an applied patch.
This can be useful for later reference.

git am --signoff < a_file.patch 

See an example in this article:

In your git log, you’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.

Example

How to test multiple variables against a value?

You can try the method shown below. In this method, you will have the freedom to specify/input the number of variables that you wish to enter.

mydict = {0:"c", 1:"d", 2:"e", 3:"f"}
mylist= []

num_var = int(raw_input("How many variables? ")) #Enter 3 when asked for input.

for i in range(num_var): 
    ''' Enter 0 as first input, 1 as second input and 3 as third input.'''
    globals()['var'+str('i').zfill(3)] = int(raw_input("Enter an integer between 0 and 3 "))
    mylist += mydict[globals()['var'+str('i').zfill(3)]]

print mylist
>>> ['c', 'd', 'f']

UILabel with text of two different colors

//NSString *myString = @"I have to replace text 'Dr Andrew Murphy, John Smith' ";
NSString *myString = @"Not a member?signin";

//Create mutable string from original one
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:myString];

//Fing range of the string you want to change colour
//If you need to change colour in more that one place just repeat it
NSRange range = [myString rangeOfString:@"signin"];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:(63/255.0) green:(163/255.0) blue:(158/255.0) alpha:1.0] range:range];

//Add it to the label - notice its not text property but it's attributeText
_label.attributedText = attString;

When should I use nil and NULL in Objective-C?

They both are just typecast zero's. Functionally, there's no difference between them. ie.,

#define NULL ((void*)0)
#define nil ((id)0)

There is a difference, but only to yourself and other humans that read the code, the compiler doesn't care.

One more thing nil is an object value while NULL is a generic pointer value.

How to get names of classes inside a jar file?

You can try:

jar tvf jarfile.jar 

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

How to determine whether a Pandas Column contains a particular value

Use

df[df['id']==x].index.tolist()

If x is present in id then it'll return the list of indices where it is present, else it gives an empty list.

CSS background image to fit height, width should auto-scale in proportion

body.bg {
    background-size: cover;
    background-repeat: no-repeat;
    min-height: 100vh;
    background: white url(../images/bg-404.jpg) center center no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
}   
Try This
_x000D_
_x000D_
    body.bg {_x000D_
     background-size: cover;_x000D_
     background-repeat: no-repeat;_x000D_
     min-height: 100vh;_x000D_
     background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;_x000D_
     -webkit-background-size: cover;_x000D_
     -moz-background-size: cover;_x000D_
     -o-background-size: cover;_x000D_
    } 
_x000D_
    <body class="bg">_x000D_
_x000D_
_x000D_
     _x000D_
    </body>
_x000D_
_x000D_
_x000D_

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.

import java.text.SimpleDateFormat;
import java.util.Date;

public class test {
    public static void main(String argv[]){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date now = new Date();
        String strDate = sdf.format(now);
        System.out.println(strDate);
    }
}

Git: Remove committed file after push

  1. Get the hash code of last commit.

    • git log
  2. Revert the commit
    • git revert <hash_code_from_git_log>
  3. Push the changes
    • git push

check out in the GHR. you might get what ever you need, hope you this is useful

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

Depending on where you are in the kestrel pipeline - if you have access to IConfiguration (Startup.cs constructor) or IWebHostEnvironment (formerly IHostingEnvironment) you can either inject the IWebHostEnvironment into your constructor or just request the key from the configuration.

Inject IWebHostEnvironment in Startup.cs Constructor

public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
     var contentRoot = env.ContentRootPath;
}

Using IConfiguration in Startup.cs Constructor

public Startup(IConfiguration configuration)
{
     var contentRoot = configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
}

TypeLoadException says 'no implementation', but it is implemented

I keep coming back to this... Many of the answers here do a great job of explaining what the problem is but not how to fix it.

The solution to this is to manually delete the bin files in your projects published directory. It will clean up all the references and force the project to use the latest DLLs.

I don't suggest using the publish tools Delete function because this tends to throw off IIS.

SyntaxError: Unexpected token o in JSON at position 1

The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary.

You can test this yourself, e.g. in Chrome's console:

new Object().toString()
// "[object Object]"

JSON.parse(new Object())
// Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse("[object Object]")
// Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse() converts the input into a string. The toString() method of JavaScript objects by default returns [object Object], resulting in the observed behavior.

Try the following instead:

var newData = userData.data.userList;

z-index issue with twitter bootstrap dropdown menu

Just realized what's going on.

I had the navbar inside a header which was position: fixed;

Changed the z-index on the header and it's working now - guess I didn't look high enough up the containers to set the z-index initially !#@!?

Thanks.

Django - makemigrations - No changes detected

Another possibility is you squashed some migrations and applied the resulting one, but forgot to remove the replaces attribute from it.

Unknown version of Tomcat was specified in Eclipse

Go to "Window -> preferences -> Server -> Runtime Environments"

Remove the existing servers they might not have downloaded completely.

Add new Server

Change event on select with knockout binding, how can I know if it is a real change?

Here is a solution that may help with this strange behaviour. I couldn't find a better solution than place a button to manually trigger the change event.

EDIT: Maybe a custom binding like this could help:

ko.bindingHandlers.changeSelectValue = {

   init: function(element,valueAccessor){

        $(element).change(function(){

            var value = $(element).val();

            if($(element).is(":focus")){

                  //Do whatever you want with the new value
            }

        });

    }
  };

And in your select data-bind attribute add:

changeSelectValue: yourSelectValue

How to limit google autocomplete results to City and Country only

Basically same as the accepted answer, but updated with new type and multiple country restrictions:

function initialize() {

 var options = {
  types: ['(regions)'],
  componentRestrictions: {country: ["us", "de"]}
 };

 var input = document.getElementById('searchTextField');
 var autocomplete = new google.maps.places.Autocomplete(input, options);
}

Using '(regions)' instead of '(cities)' allows to search by postal code as well as city name.

See official documentation, Table 3: https://developers.google.com/places/supported_types

Location of the android sdk has not been setup in the preferences in mac os?

Hope this helps:

Step 1.) Go to https://www.eclipse.org/downloads/index-developer.php?release=kepler and download appropriate Eclipse version.

Step 2.) Extract downloaded zip file in appropriate location. In this tutorial, I have downloaded and installed it under program files.

Step 3.) Right click on eclipse.exe file and send shortcut to desktop.

Step 4.) Double click on eclipse shortcut from desktop and select appropriate location to create your workspace.

Step 5.) Navigate to Window > Preferences. This should open Preferences window.

Step 6.) On the left hand side page expend “Java” and click on “Installed JREs”

Step 7.) Click Add. It will open “Add JRE” dialog. Select “Standard VM” and click Next.

Step 8.) For “JRE home” select “Direcotry…”. This will open “Browse for folder” dialog. Select the location where your JDK is installed. NOTE: MAKE SURE THAT ITS x64 AS WELL, AS WE ARE USING 64-BIT VERSION OF ECLIPSE.

Step 9.) If you have selected proper location, it will show JDK version in JRE name and it will display “JRE system libraries”.

Step 10.) Click finish. Now your JDK is properly pointed as “Installed JREs”.

Step 11.) Select checkbox unchecked before name of your JDK name.

Click ok and you’re done. You are now using JDK as “Installed JREs”

Read complete procedure at below location.

https://softwaretestingboard.com/qna/4/how-do-i-map-android-sdk-after-eclipse-plugin-is-installed#axzz4wM3UEZtq

Seaborn Barplot - Displaying Values

A simple way to do so is to add the below code (for Seaborn):

for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points') 

Example :

splot = sns.barplot(df['X'], df['Y'])
# Annotate the bars in plot
for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points')    
plt.show()

anaconda - graphviz - can't import after installation

Graphviz is evidently included in Anaconda so as to be used with pydot or pydot-ng (both of which are included in Anaconda). You may want to consider using one of those instead of the 'graphviz' Python module.

filters on ng-model in an input

Use a directive which adds to both the $formatters and $parsers collections to ensure that the transformation is performed in both directions.

See this other answer for more details including a link to jsfiddle.

How do I set default value of select box in angularjs

  <select ng-model="selectedCar" ><option ng-repeat="car in cars "  value="{{car.model}}">{{car.model}}</option></select>
<script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.cars = [{model : "Ford Mustang", color : "red"}, {model : "Fiat 500", color : "white"},{model : "Volvo XC90", color : "black"}];
$scope.selectedCar=$scope.cars[0].model ;});

How to write UTF-8 in a CSV file

A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:

    fd = codecs.open(tempfilename, 'wb', 'utf-8')  
    for c in whatever :
        fd.write( json.dumps(c) [1:-1] )   # json dumps writes ["a",..]
        fd.write('\n')
    fd.close()

Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*

How to check if ZooKeeper is running or up from command prompt?

One other way would be to use 4 letter commands to validate if zookeeper service is healthy or not

echo stat | nc <zookeeper ip> 2181
echo mntr | nc <zookeeper ip> 2181
echo isro  | nc <zookeeper ip> 2181

More details on the documentation link below https://zookeeper.apache.org/doc/r3.1.2/zookeeperAdmin.html#sc_zkCommands

How do you find all subclasses of a given class in Java?

Scanning for classes is not easy with pure Java.

The spring framework offers a class called ClassPathScanningCandidateComponentProvider that can do what you need. The following example would find all subclasses of MyClass in the package org.example.package

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(MyClass.class));

// scan in org.example.package
Set<BeanDefinition> components = provider.findCandidateComponents("org/example/package");
for (BeanDefinition component : components)
{
    Class cls = Class.forName(component.getBeanClassName());
    // use class cls found
}

This method has the additional benefit of using a bytecode analyzer to find the candidates which means it will not load all classes it scans.

Xcode - Warning: Implicit declaration of function is invalid in C99

should call the function properly; like- Fibonacci:input

Error: free(): invalid next size (fast):

It means that you have a memory error. You may be trying to free a pointer that wasn't allocated by malloc (or delete an object that wasn't created by new) or you may be trying to free/delete such an object more than once. You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.

Any number of programming errors can cause this problem. You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs. If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).

Forcing a postback

A postback is triggered after a form submission, so it's related to a client action... take a look here for an explanation: ASP.NET - Is it possible to trigger a postback from server code?

and here for a solution: http://forums.asp.net/t/928411.aspx/1

Difference between innerText, innerHTML and value?

The only difference between innerText and innerHTML is that innerText insert string as it is into the element, while innerHTML run it as html content.

_x000D_
_x000D_
const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';_x000D_
document.getElementById('innertext').innerText = ourstring;_x000D_
document.getElementById('innerhtml').innerHTML = ourstring;
_x000D_
.name{_x000D_
color:red;_x000D_
}
_x000D_
<h3>Inner text below. It inject string as it is into the element.</h3>_x000D_
<div id="innertext"></div>_x000D_
<br />_x000D_
<h3>Inner html below. It renders the string into the element and treat as part of html document.</h3>_x000D_
<div id="innerhtml"></div>
_x000D_
_x000D_
_x000D_

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

How can I hide an HTML table row <tr> so that it takes up no space?

HTML:

<input type="checkbox" id="attraction" checked="checked" onchange="updateMap()">poi.attraction</input>

JavaScript:

function updateMap() {
     map.setOptions({'styles': getStyles() });
} 

function getStyles() {
    var styles = [];
    for (var i=0; i < types.length; i++) {
      var style = {};
      var type = types[i];
      var enabled = document.getElementById(type).checked;
      style['featureType'] = 'poi.' + type;
      style['elementType'] = 'labels';
      style['stylers'] = [{'visibility' : (enabled ? 'on' : 'off') }];
      styles.push(style);
    }
    return styles;
}

How to force Selenium WebDriver to click on element which is not currently visible?

To add my grain of sand here: if an element resides behind a fixed div it will be considered as not visible and you won't be able to click it; this happened to me recently and i solved it executing a script as recommended above, which does:

document.evaluate("<xpath locator for element to be clicked>", document, null, XPathResult.ANY_TYPE, null).iterateNext().click()", locator);

Graph visualization library in JavaScript

I've just put together what you may be looking for: http://www.graphdracula.net

It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:

var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");

I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!


You may want to have a look at other projects, too! Below are two meta-comparisons:

  • SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.

  • DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":Selection DataVisualization.ch

Here's a list of similar projects (some have been already mentioned here):

Pure JavaScript Libraries

  • vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.

  • Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.

  • The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.

  • D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.

  • Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.

  • sigma.js Lightweight but powerful library for drawing graphs

  • jsPlumb jQuery plug-in for creating interactive connected graphs

  • Springy - a force-directed graph layout algorithm

  • Processing.js Javascript port of the Processing library by John Resig

  • JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.

  • RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.

  • JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package

  • mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.

Commercial libraries

Abandoned libraries

  • Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)

  • Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.

  • arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.

  • jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.

  • jsdot Client side graph drawing application. Abandoned in 2011.

  • Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.

  • Moo Wheel Interactive JS representation for connections and relations (2008)

  • JSViz 2007-era graph visualization script

  • dagre Graph layout for JavaScript

Non-Javascript Libraries

How to configure CORS in a Spring Boot + Spring Security application?

Cors can be a pain in the ass, but with this simple code you are Cors ONLY!!!! to to specified method

@CrossOrigin(origins="*")// in this line add your url and thats is all for spring boot side
    @GetMapping("/some")
    public String index() {
        return "pawned cors!!!!";
    }

Like a charm in spring boot 2.0.2

ImportError: No module named PyQt4

It is likely that you are running the python executable from /usr/bin (Apple version) instead of /usr/loca/bin (Brew version)

You can either

a) check your PATH variable

or

b) run brew doctor

or

c) run which python

to check if it is the case.

Can I update a JSF component from a JSF backing bean method?

I also tried to update a component from a jsf backing bean/class

You need to do the following after manipulating the UI component:

FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())

It is important to use the clientId instead of the (server-side) componentId!!

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

http://en.wikipedia.org/wiki/Email_address

Add image to layout in ruby on rails

It's working for me:

<%= image_tag( root_url + "images/rss.jpg", size: "50x50", :alt => "rss feed") -%>

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

Something like gunzip using the -r flag?....

Travel the directory structure recursively. If any of the file names specified on the command line are directories, gzip will descend into the directory and compress all the files it finds there (or decompress them in the case of gunzip ).

http://www.computerhope.com/unix/gzip.htm

How to get error message when ifstream open fails

You can also throw a std::system_error as shown in the test code below. This method seems to produce more readable output than f.exception(...).

#include <exception> // <-- requires this
#include <fstream>
#include <iostream>

void process(const std::string& fileName) {
    std::ifstream f;
    f.open(fileName);

    // after open, check f and throw std::system_error with the errno
    if (!f)
        throw std::system_error(errno, std::system_category(), "failed to open "+fileName);

    std::clog << "opened " << fileName << std::endl;
}

int main(int argc, char* argv[]) {
    try {
        process(argv[1]);
    } catch (const std::system_error& e) {
        std::clog << e.what() << " (" << e.code() << ")" << std::endl;
    }
    return 0;
}

Example output (Ubuntu w/clang):

$ ./test /root/.profile
failed to open /root/.profile: Permission denied (system:13)
$ ./test missing.txt
failed to open missing.txt: No such file or directory (system:2)
$ ./test ./test
opened ./test
$ ./test $(printf '%0999x')
failed to open 000...000: File name too long (system:36)

How can I query for null values in entity framework?

There is a slightly simpler workaround that works with LINQ to Entities:

var result = from entry in table
         where entry.something == value || (value == null && entry.something == null)
         select entry;

This works becasuse, as AZ noticed, LINQ to Entities special cases x == null (i.e. an equality comparison against the null constant) and translates it to x IS NULL.

We are currently considering changing this behavior to introduce the compensating comparisons automatically if both sides of the equality are nullable. There are a couple of challenges though:

  1. This could potentially break code that already depends on the existing behavior.
  2. The new translation could affect the performance of existing queries even when a null parameter is seldom used.

In any case, whether we get to work on this is going to depend greatly on the relative priority our customers assign to it. If you care about the issue, I encourage you to vote for it in our new Feature Suggestion site: https://data.uservoice.com.

Lookup City and State by Zip Google Geocode Api

function getCityState($zip, $blnUSA = true) {
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";

    $address_info = file_get_contents($url);
    $json = json_decode($address_info);
    $city = "";
    $state = "";
    $country = "";
    if (count($json->results) > 0) {
        //break up the components
        $arrComponents = $json->results[0]->address_components;

        foreach($arrComponents as $index=>$component) {
            $type = $component->types[0];

            if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                $city = trim($component->short_name);
            }
            if ($state == "" && $type=="administrative_area_level_1") {
                $state = trim($component->short_name);
            }
            if ($country == "" && $type=="country") {
                $country = trim($component->short_name);

                if ($blnUSA && $country!="US") {
                    $city = "";
                    $state = "";
                    break;
                }
            }
            if ($city != "" && $state != "" && $country != "") {
                //we're done
                break;
            }
        }
    }
    $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);

    die(json_encode($arrReturn));
}

How to list the tables in a SQLite database file that was opened with ATTACH?

To list the tables you can also do:

SELECT name FROM sqlite_master
WHERE type='table';

How do I tell Maven to use the latest version of a dependency?

The dependencies syntax is located at the Dependency Version Requirement Specification documentation. Here it is is for completeness:

Dependencies' version element define version requirements, used to compute effective dependency version. Version requirements have the following syntax:

  • 1.0: "Soft" requirement on 1.0 (just a recommendation, if it matches all other ranges for the dependency)
  • [1.0]: "Hard" requirement on 1.0
  • (,1.0]: x <= 1.0
  • [1.2,1.3]: 1.2 <= x <= 1.3
  • [1.0,2.0): 1.0 <= x < 2.0
  • [1.5,): x >= 1.5
  • (,1.0],[1.2,): x <= 1.0 or x >= 1.2; multiple sets are comma-separated
  • (,1.1),(1.1,): this excludes 1.1 (for example if it is known not to work in combination with this library)

In your case, you could do something like <version>[1.2.3,)</version>

How to change the integrated terminal in visual studio code or VSCode

For OP's terminal Cmder there is an integration guide, also hinted in the VS Code docs.

If you want to use VS Code tasks and encounter problems after switch to Cmder, there is an update to @khernand's answer. Copy this into your settings.json file:

"terminal.integrated.shell.windows": "cmd.exe",

"terminal.integrated.env.windows": {
  "CMDER_ROOT": "[cmder_root]" // replace [cmder_root] with your cmder path
},
"terminal.integrated.shellArgs.windows": [
  "/k",
  "%CMDER_ROOT%\\vendor\\bin\\vscode_init.cmd" // <-- this is the relevant change
  // OLD: "%CMDER_ROOT%\\vendor\\init.bat"
],

The invoked file will open Cmder as integrated terminal and switch to cmd for tasks - have a look at the source here. So you can omit configuring a separate terminal in tasks.json to make tasks work.

Starting with VS Code 1.38, there is also "terminal.integrated.automationShell.windows" setting, which lets you set your terminal for tasks globally and avoids issues with Cmder.

"terminal.integrated.automationShell.windows": "cmd.exe"

Return multiple values from a function, sub or type?

you could connect all the data you need from the file to a single string, and in the excel sheet seperate it with text to column. here is an example i did for same issue, enjoy:

Sub CP()
Dim ToolFile As String

Cells(3, 2).Select

For i = 0 To 5
    r = ActiveCell.Row
    ToolFile = Cells(r, 7).Value
    On Error Resume Next
    ActiveCell.Value = CP_getdatta(ToolFile)

    'seperate data by "-"
    Selection.TextToColumns Destination:=Range("C3"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
        :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True

Cells(r + 1, 2).Select
Next


End Sub

Function CP_getdatta(ToolFile As String) As String
    Workbooks.Open Filename:=ToolFile, UpdateLinks:=False, ReadOnly:=True

    Range("A56000").Select
    Selection.End(xlUp).Select
    x = CStr(ActiveCell.Value)
    ActiveCell.Offset(0, 20).Select
    Selection.End(xlToLeft).Select
    While IsNumeric(ActiveCell.Value) = False
        ActiveCell.Offset(0, -1).Select
    Wend
    ' combine data to 1 string
    CP_getdatta = CStr(x & "-" & ActiveCell.Value)
    ActiveWindow.Close False

End Function

php pdo: get the columns name of a table

Just Put your Database name,username,password (Where i marked ?) and table name.& Yuuppiii!.... you get all data from your main database (with column name)

<?php 

function qry($q){

    global $qry;
    try {   
    $host = "?";
    $dbname = "?";
    $username = "?";
    $password = "?";
    $dbcon = new PDO("mysql:host=$host; 
    dbname=$dbname","$username","$password");
}
catch (Exception $e) {

    echo "ERROR ".$e->getMEssage();

}

    $qry = $dbcon->query($q);
    $qry->setFetchMode(PDO:: FETCH_OBJ);

    return $qry;

}


echo "<table>";

/*Get Colums Names in table row */
$columns = array();

$qry1= qry("SHOW COLUMNS FROM Your_table_name");

while (@$column = $qry1->fetch()->Field) {
    echo "<td>".$column."</td>";
    $columns[] = $column;

}

echo "<tr>";

/* Fetch all data into a html table * /

$qry2 = qry("SELECT * FROM Your_table_name");

while ( $details = $qry2->fetch()) {

    echo "<tr>";
    foreach ($columns as $c_name) {
    echo "<td>".$details->$c_name."</td>";

}

}

echo "</table>";

?>

Have border wrap around text

Try this and see if you get what you are aiming for:

_x000D_
_x000D_
<div id='page' style='width: 600px'>_x000D_
  <h1 style='border:2px black solid; font-size:42px; width:fit-content; width:-webkit-fit-content; width:-moz-fit-content;'>Title</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Exercises to improve my Java programming skills

If you wanted to learn some GUI, may be tic tac toe is good. Even for console, I still find that is a fun problem. Not challenging but a little bit fun. Later you can advance some other games or port that game to GUI, client server or java applet for the web. I think if you want to learn something and get fun as well, game is a good choice:)

.ps1 cannot be loaded because the execution of scripts is disabled on this system

Your script is blocked from executing due to the execution policy.

You need to run PowerShell as administrator and set it on the client PC to Unrestricted. You can do that by calling Invoke with:

Set-ExecutionPolicy Unrestricted

Changing user agent on urllib2.urlopen

there are two properties of urllib.URLopener() namely:
addheaders = [('User-Agent', 'Python-urllib/1.17'), ('Accept', '*/*')] and
version = 'Python-urllib/1.17'.
To fool the website you need to changes both of these values to an accepted User-Agent. for e.g.
Chrome browser : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36'
Google bot : 'Googlebot/2.1'
like this

import urllib
page_extractor=urllib.URLopener()  
page_extractor.addheaders = [('User-Agent', 'Googlebot/2.1'), ('Accept', '*/*')]  
page_extractor.version = 'Googlebot/2.1'
page_extractor.retrieve(<url>, <file_path>)

changing just one property does not work because the website marks it as a suspicious request.

Adding files to java classpath at runtime

Yes I believe it's possible but you might have to implement your own classloader. I have never done it but that is the path I would probably look at.

Is it bad to have my virtualenv directory inside my git repository?

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...

error C2220: warning treated as error - no 'object' file generated

As a side-note, you can enable/disable individual warnings using #pragma. You can have a look at the documentation here

From the documentation:

// pragma_warning.cpp
// compile with: /W1
#pragma warning(disable:4700)
void Test() {
   int x;
   int y = x;   // no C4700 here
   #pragma warning(default:4700)   // C4700 enabled after Test ends
}

int main() {
   int x;
   int y = x;   // C4700
}

Tesseract OCR simple example

Try updating the line to:

ocr.Init(@"C:\", "eng", false); // the path here should be the parent folder of tessdata

How to execute command stored in a variable?

Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the bash manpage):

  • initial word splitting
  • brace expansion
  • tilde expansion
  • parameter, variable and arithmetic expansion
  • command substitution
  • secondary word splitting
  • path expansion (aka globbing)
  • quote removal

Using $cmd directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.

Using eval "$cmd" does nothing until the quote removal phase, where $cmd is returned as is, and passed as a parameter to eval, whose function is to run the whole chain again before executing.

So basically, they're the same in most cases, and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:

$ cmd="echo foo{bar,baz}"
$ $cmd
foo{bar,baz}
$ eval "$cmd"
foobar foobaz

How to pass arguments and redirect stdin from a file to program run in gdb?

If you want to have bare run command in gdb to execute your program with redirections and arguments, you can use set args:

% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run

I was unable to achieve the same behaviour with --args parameter, gdb fiercely escapes the redirections, i.e.

% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...

This one actually redirects the input of gdb itself, not what we really want here

% gdb --args echo 1 2 <file
zsh: no such file or directory: file

How to increase time in web.config for executing sql query

You can do one thing.

  1. In the AppSettings.config (create one if doesn't exist), create a key value pair.
  2. In the Code pull the value and convert it to Int32 and assign it to command.TimeOut.

like:- In appsettings.config ->

<appSettings>    
   <add key="SqlCommandTimeOut" value="240"/>
</appSettings>

In Code ->

command.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);

That should do it.

Note:- I faced most of the timeout issues when I used SqlHelper class from microsoft application blocks. If you have it in your code and are facing timeout problems its better you use sqlcommand and set its timeout as described above. For all other scenarios sqlhelper should do fine. If your client is ok with waiting a little longer than what sqlhelper class offers you can go ahead and use the above technique.

example:- Use this -

 SqlCommand cmd = new SqlCommand(completequery);

 cmd.CommandTimeout =  Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);

 SqlConnection con = new SqlConnection(sqlConnectionString);
 SqlDataAdapter adapter = new SqlDataAdapter();
 con.Open();
 adapter.SelectCommand = new SqlCommand(completequery, con);
 adapter.Fill(ds);
 con.Close();

Instead of

DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(sqlConnectionString, CommandType.Text, completequery);

Update: Also refer to @Triynko answer below. It is important to check that too.

Finding second occurrence of a substring in a string in Java

You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy

public static ArrayList<Integer> occurrencesPos(String str, String substr) {
    final boolean ignoreCase = true;
    int substrLength = substr.length();
    int strLength = str.length();

    ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();

    for(int i = 0; i < strLength - substrLength + 1; i++) {
        if(str.regionMatches(ignoreCase, i, substr, 0, substrLength))  {
            occurrenceArr.add(i);
        }
    }
    return occurrenceArr;
}

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

"Least Astonishment" and the Mutable Default Argument

I used to think that creating the objects at runtime would be the better approach. I'm less certain now, since you do lose some useful features, though it may be worth it regardless simply to prevent newbie confusion. The disadvantages of doing so are:

1. Performance

def foo(arg=something_expensive_to_compute())):
    ...

If call-time evaluation is used, then the expensive function is called every time your function is used without an argument. You'd either pay an expensive price on each call, or need to manually cache the value externally, polluting your namespace and adding verbosity.

2. Forcing bound parameters

A useful trick is to bind parameters of a lambda to the current binding of a variable when the lambda is created. For example:

funcs = [ lambda i=i: i for i in range(10)]

This returns a list of functions that return 0,1,2,3... respectively. If the behaviour is changed, they will instead bind i to the call-time value of i, so you would get a list of functions that all returned 9.

The only way to implement this otherwise would be to create a further closure with the i bound, ie:

def make_func(i): return lambda: i
funcs = [make_func(i) for i in range(10)]

3. Introspection

Consider the code:

def foo(a='test', b=100, c=[]):
   print a,b,c

We can get information about the arguments and defaults using the inspect module, which

>>> inspect.getargspec(foo)
(['a', 'b', 'c'], None, None, ('test', 100, []))

This information is very useful for things like document generation, metaprogramming, decorators etc.

Now, suppose the behaviour of defaults could be changed so that this is the equivalent of:

_undefined = object()  # sentinel value

def foo(a=_undefined, b=_undefined, c=_undefined)
    if a is _undefined: a='test'
    if b is _undefined: b=100
    if c is _undefined: c=[]

However, we've lost the ability to introspect, and see what the default arguments are. Because the objects haven't been constructed, we can't ever get hold of them without actually calling the function. The best we could do is to store off the source code and return that as a string.

If else embedding inside html

<?php if ($foo) { ?>
    <div class="mydiv">Condition is true</div>
<?php } else { ?>
    <div class="myotherdiv">Condition is false</div>
<?php } ?>

How much does it cost to develop an iPhone application?

There are ways of paying less to get an application, developed than paying the going rate, but very often you get what you pay for - inexperienced developers who leave you with a mess of spaghetti code that's impossible to maintain, or experienced developers with whom you have to communicate across a cultural and language gap.

Developing an app like Twitterific is not easy. It's an extraordinarily polished app with a lot of attention to detail that most people - indeed many developers - would fail to notice or realize the effort behind. You may be able to get a Twitter iPhone client written for $3500 or $5000 by going offshore or by being willing to "work with inexperienced developers", but you're not going to get Twitterific for that, and it's doubtful you'd get even a halfway decent application for that amount.

And you likely will end up spending a lot of time managing the process, going back and forth on requirements, and fighting to get what you really want instead of what they want to give you.

There's also a risk with "cut-rate" development, whether it's offshore or just using inexperienced developers - you may very well end up with something you can't use, or something that gets 1 star ratings because it crashes or behaves erratically. You might find the occasional underpriced gem of a developer, but they won't stay underpriced for long given the sheer demand in this market right now.

By virtue of my books and blog, people often reach out to me when they need help with their iPhone applications. I get, on average, 4 or 5 inquiries a month from people asking for help fixing applications they had developed either over-seas or by inexperienced developers here in the States. In most cases, I end up having to tell them they'd be better off throwing their code out and starting over with a developer who knows what they're doing rather than trying to fix the code they bought on the cheap. If they insist on trying to "fix" what they have, I decline the work.

Angular 2 How to redirect to 404 or other path if the path does not exist

As Angular moved on with the release, I faced this same issue. As per version 2.1.0 the Route interface looks like:

export interface Route {
    path?: string;
    pathMatch?: string;
    component?: Type<any>;
    redirectTo?: string;
    outlet?: string;
    canActivate?: any[];
    canActivateChild?: any[];
    canDeactivate?: any[];
    canLoad?: any[];
    data?: Data;
    resolve?: ResolveData;
    children?: Route[];
    loadChildren?: LoadChildren;
} 

So my solutions was the following:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '404', component: NotFoundComponent },
    { path: '**', redirectTo: '404' }
];

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

How can I read the client's machine/computer name from the browser?

You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:

function GetComputerName() {
    try {
        var network = new ActiveXObject('WScript.Network');
        // Show a pop up if it works
        alert(network.computerName);
    }
    catch (e) { }
}

It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.

Here is a link to some more info on WScript: More Information

Get list of databases from SQL Server

Don't Get confused, Use the below simple query to get all the databases,

select * from sys.databases

If u need only the User defined databases;

select * from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb'); 

Some of the System database names are (resource,distribution,reportservice,reportservicetempdb) just insert it into the query. If u have the above db's in your machine as default.

How to examine processes in OS X's Terminal?

You can just use top It will display everything running on your OSX

What does it mean to "program to an interface"?

Programming to an interface is saying, "I need this functionality and I don't care where it comes from."

Consider (in Java), the List interface versus the ArrayList and LinkedList concrete classes. If all I care about is that I have a data structure containing multiple data items that I should access via iteration, I'd pick a List (and that's 99% of the time). If I know that I need constant-time insert/delete from either end of the list, I might pick the LinkedList concrete implementation (or more likely, use the Queue interface). If I know I need random access by index, I'd pick the ArrayList concrete class.

Can you get the column names from a SqlDataReader?

If you want the column names only, you can do:

List<string> columns = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
    DataTable dt = reader.GetSchemaTable();
    foreach (DataRow row in dt.Rows)
    {
        columns.Add(row.Field<String>("ColumnName"));
    }
}

But if you only need one row, I like my AdoHelper addition. This addition is great if you have a single line query and you don't want to deal with data table in you code. It's returning a case insensitive dictionary of column names and values.

public static Dictionary<string, string> ExecuteCaseInsensitiveDictionary(string query, string connectionString, Dictionary<string, string> queryParams = null)
{
    Dictionary<string, string> CaseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;

                // Add the parameters for the SelectCommand.
                if (queryParams != null)
                    foreach (var param in queryParams)
                        cmd.Parameters.AddWithValue(param.Key, param.Value);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            CaseInsensitiveDictionary.Add(column.ColumnName, row[column].ToString());
                        }
                    }
                }
            }
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return CaseInsensitiveDictionary;
}

Sleep for milliseconds

In Unix you can use usleep.

In Windows there is Sleep.

How to set the value for Radio Buttons When edit?

just add 'checked="checked"' in the correct radio button that you would like it to be default on. As example you could use php quick if notation to add that in:

<input type="radio" name="sex" value="Male" size="17" <?php echo($isMale?'checked="checked"':''); ?>>Male
<input type="radio" name="sex" value="Female" size="17" <?php echo($isFemale?'checked="checked"':''); ?>>Female

in this example $isMale & $isFemale is boolean values that you assign based on the value from your database.

Printing a char with printf

In C char gets promoted to int in expressions. That pretty much explains every question, if you think about it.

Source: The C Programming Language by Brian W.Kernighan and Dennis M.Ritchie

A must read if you want to learn C.

Also see this stack overflow page, where people much more experienced then me can explain it much better then I ever can.

MAX function in where clause mysql

The syntax you have used is incorrect. The query should be something like:

SELECT column_name(s) FROM tablename WHERE id = (SELECT MAX(id) FROM tablename)

Sound effects in JavaScript / HTML5

You may also want to use this to detect HTML 5 audio in some cases:

http://diveintohtml5.ep.io/everything.html

HTML 5 JS Detect function

function supportsAudio()
{
    var a = document.createElement('audio'); 
    return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
}

Whether a variable is undefined

http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html

Depends on how specific you want the test to be. You could maybe get away with

if(page_name){ string += "&page_name=" + page_name; }

CSS background-image not working

I have tried your code and found that if we put background-image: url(image.png); in btn-pToolName and change color:#000000. it displays the image at background.

my test css:

           .btn-pTool {
                margin: 0;
                padding: 0;
            }

            .btn-pToolName {
                text-align: center;
                width: 26px;
                height: 190px;
                display: block;
                color: #000000;
                text-decoration: none;
                font-family: Arial, Helvetica, sans-serif;
                font-weight: bold;
                font-size: 1em;
                line-height: 32px;
                background-image: url(defalut.png);
                background-repeat: no-repeat;
            }

and test html:

        <div class="pToolContainer">
            <span class="btn-pTool"><a class="btn-pToolName" href="#">adad</a></span>
            <div class="pToolSlidePanel"></div>
        </div>

Hope this helps.

How to use not contains() in xpath?

You can use not(expression) function

not() is a function in xpath (as opposed to an operator)

Example:

//a[not(contains(@id, 'xx'))]

OR

expression != true()

How to setup Main class in manifest file in jar produced by NetBeans project

In 7.3 just enable Properties/Build/Package/Copy Dependent Libraries and main class will be added to manifest when building depending on selected target.

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

Try to install Integrated Native Developer Experience
" Is a cross-architecture productivity suite that provides developers with tools, support, and IDE integration to create high-performance C++/Java* applications for Windows* on Intel® architecture, OS X on Intel® architecture and Android* on ARM* and Intel® architecture."

Integrated Native Developer Experience

How to check if the key pressed was an arrow key in Java KeyListener?

If you mean that you wanna attach this to your panel (Window that you are working with).

then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.

Then, attach that class to you panel by: this.addKeyListener(new subclass());

how to write javascript code inside php

Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.

<?php
$script = <<< JS

$(function() {
   // js code goes here
});

JS;
?>

After closing the heredoc construction the $script variable contains your JS code that can be used like this:

<script><?= $script ?></script>

The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.

Numpy matrix to array

np.array(M).ravel()

If you care for speed; But if you care for memory:

np.asarray(M).ravel()

Bootstrap DatePicker, how to set the start date for tomorrow?

this.$('#datepicker').datepicker({minDate: 1});

minDate:0 - Enable dates in the calender from the current date. MinDate:1 enable dates in the calender currentDate+1

To Restrict date between from tomorrow and the same day next month u need to give something like

$( "#datepicker" ).datepicker({ minDate: 1, maxDate: "+1M" });

In C#, how to check whether a string contains an integer?

You can check if string contains numbers only:

Regex.IsMatch(myStringVariable, @"^-?\d+$")

But number can be bigger than Int32.MaxValue or less than Int32.MinValue - you should keep that in mind.

Another option - create extension method and move ugly code there:

public static bool IsInteger(this string s)
{
   if (String.IsNullOrEmpty(s))
       return false;

   int i;
   return Int32.TryParse(s, out i);
}

That will make your code more clean:

if (myStringVariable.IsInteger())
    // ...

Changing CSS for last <li>

I usually do this by creating a htc file (ex. last-child.htc):

<attach event="ondocumentready" handler="initializeBehaviours" />
<script type="text/javascript">
function initializeBehaviours() {
  this.lastChild.className += ' last-child';
}
</script>

And call it from my IE conditional css file with:

ul { behavior: url("/javascripts/htc/last-child.htc"); }

Whereas in my main css file I got:

ul li:last-child,
ul li.last-child {
  /* some code */
}

Another solution (albeit slower) that uses your existent css markup without defining any .last-child class would be Dean Edwards ie7.js library.

How can I check for an empty/undefined/null string in JavaScript?

Trimming whitespace with the null-coalescing operator:

if (!str?.trim()) {
  // do something...
}

How can INSERT INTO a table 300 times within a loop in SQL?

Found some different answers that I combined to solve simulair problem:

CREATE TABLE nummer (ID INTEGER PRIMARY KEY, num, text, text2);
WITH RECURSIVE
  for(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM for WHERE i < 1000000)
INSERT INTO nummer SELECT i, i+1, "text" || i, "otherText" || i FROM for;

Adds 1 miljon rows with

  • id increased by one every itteration
  • num one greater then id
  • text concatenated with id-number like: text1, text2 ... text1000000
  • text2 concatenated with id-number like: otherText1, otherText2 ... otherText1000000

Fastest method of screen capturing on Windows

DXGI Desktop Capture

Project that captures the desktop image with DXGI duplication. Saves the captured image to the file in different image formats (*.bmp; *.jpg; *.tif).

This sample is written in C++. You also need some experience with DirectX (D3D11, D2D1).

What the Application Can Do

  • If you have more than one desktop monitor, you can choose.
  • Resize the captured desktop image.
  • Choose different scaling modes.
  • You can show or hide the mouse icon in the output image.
  • You can rotate the image for the output picture, or leave it as default.

Passing an array of parameters to a stored procedure

What about using the XML data type instead of passing an array. I find that a better solution and works well in SQL 2005

How to change the hosts file on android

You have root, but you still need to remount /system to be read/write

$ adb shell
$ su
$ mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

Go here for more information: Mount a filesystem read-write.

What is Cache-Control: private?

The Expires entity-header field gives the date/time after which the response is considered stale.The Cache-control:maxage field gives the age value (in seconds) bigger than which response is consider stale.

Althought above header field give a mechanism to client to decide whether to send request to the server. In some condition, the client send a request to sever and the age value of response is bigger then the maxage value ,dose it means server needs to send the resource to client? Maybe the resource never changed.

In order to resolve this problem, HTTP1.1 gives last-modifided head. The server gives the last modified date of the response to client. When the client need this resource, it will send If-Modified-Since head field to server. If this date is before the modified date of the resouce, the server will sends the resource to client and gives 200 code.Otherwise,it will returns 304 code to client and this means client can use the resource it cached.

Does a "Find in project..." feature exist in Eclipse IDE?

There is no way to do pure text search in whole work workspace/project via a shortcut that I know of (and it is a PITA), but this will find references in the workspace:

  1. Put your cursor on what you want to lookup
  2. Press Ctrl + Shift + g

How to get Real IP from Visitor?

This is my approach:

 function getRealUserIp(){
    switch(true){
      case (!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP'];
      case (!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP'];
      case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR'];
      default : return $_SERVER['REMOTE_ADDR'];
    }
 }

How to use:

$ip = getRealUserIp();

ImportError: numpy.core.multiarray failed to import

I used Anaconda environment and had the same issue. I tried all the aforementioned approaches and, alas, it didn't help me. Accumulated the suggestions, here the way which helped me:

  1. Delete all NumPy folders in the virtual environment or in the system if you don't use a virtual environment, for example in my case:

    ~/home/anaconda3/envs//lib/python/site-packages/numpy

    ~/home/anaconda3/envs//lib/python/site-packages/numpy.libs

    ~/home/anaconda3/envs//lib/python/site-packages/numpy-.dist-info

  2. Install new Numpy with:

    pip install numpy -U

Hope, it could help in the same case

Change key pair for ec2 instance

  • Create new key e.g. using PuTTY Key Generator
  • Stop instance
  • Set instance user data to push public key to server
  • Start instance

Warning: Don't forget to clear the user data again. Otherwise this key will be pushed on every instance start. Step-by-step instructions.

#cloud-config
bootcmd:
 - echo 'ssh-rsa AAAAB3Nz...' > /root/.ssh/authorized_keys

enter image description here

how can I Update top 100 records in sql server

this piece of code can do its job

UPDATE TOP (100) table_name set column_name = value;

If you want to show the last 100 records, you can use this if you need.

With OrnekWith
as
(
Select Top(100) * from table_name Order By ID desc
)
Update table_name Set column_name = value;

PG::ConnectionBad - could not connect to server: Connection refused

As described by @Magne, the error PG::ConnectionBad - could not connect to server: Connection refused can be presented following a major/minor version upgrade (e.g. 9.5 -> 9.6 or 9 -> 10) of PostgreSQL.

I got this error after having run brew upgrade postgresql after the release of PostgreSQL version 9.6. The problem is that major/minor version upgrades require additional steps to migrate old date to the new version.

How to check if this is your problem

You can check if this is the problem by checking the latest brew formula PostgreSQL version installed with homebrew...

$ brew info postgresql

/usr/local/Cellar/postgresql/9.5.4_1 (3,147 files, 35M)
Poured from bottle on 2016-10-14 at 13:33:28
/usr/local/Cellar/postgresql/9.6.1 (3,242 files, 36.4M) *
Poured from bottle on 2017-02-06 at 12:41:00

...and then comparing it to the current PG_VERSION

$ cat /usr/local/var/postgres/PG_VERSION
9.5

If the PG_VERSION is less than the latest brew formula and the difference is a major/minor version change, then this is probably your problem.

How to fix (i.e. how to upgrade the data)

Instructions below are for an upgrade from 9.5 to 9.6. Change the version numbers as appropriate for your own upgrade

Step 1. Make sure PostgreSQL is switched off:

$ launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
# or, with Homebrew...
$ brew services stop postgresql

Step 2. Make a new pristine database:

$ initdb /usr/local/var/postgres9.6 -E utf8

Step 3. Check what the old and new binary versions are:

$ ls /usr/local/Cellar/postgresql/
9.5.3   9.5.4   9.6.1

Note that in this example I am upgrading from 9.5.4 binary to 9.6.1 binary

Step 4. Migrate the current data to the new database using the pg_upgrade utility.

$ pg_upgrade \
  -d /usr/local/var/postgres \
  -D /usr/local/var/postgres9.6 \
  -b /usr/local/Cellar/postgresql/9.5.4/bin/ \
  -B /usr/local/Cellar/postgresql/9.6.1/bin/ \
  -v
  • -d flag specifies the current data directory
  • -D flag specifies the new data directory to be created
  • -b specifies the old binary
  • -B specifies the new binary we're upgrading to

Step 5. Move the old data directory out of the way

$ mv /usr/local/var/postgres /usr/local/var/postgres9.5

Step 6. Move newly created data directory to where PostgreSQL expects it to be

$ mv /usr/local/var/postgres9.6 /usr/local/var/postgres

Step 7. Start PostgreSQL again

$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
# or, if you're running a current version of Homebrew
$ brew services start postgresql

Step 8. If you’re using the pg gem for Rails, you should recompile by uninstalling and reinstalling the gem (skip this step if you're not using the pg gem)

$ gem uninstall pg
$ gem install pg

Step 9.(optional) After you've reassured yourself that everything is working OK, you can run regain some disk space with the following command:

brew cleanup postgresql

...and if you're feeling really brave you can delete the old PostgreSQL data directory with the following command

rm -rf /usr/local/var/postgres9.5/

(This answer is based on an excellent blog post https://keita.blog/2016/01/09/homebrew-and-postgresql-9-5/ with some additions)

Autocompletion of @author in Intellij

You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).

In the "Abbreviation" field, enter the string that should activate the template (e.g. @a), and in the "Template Text" area enter the string to complete (e.g. @author - My Name). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).

I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.

To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding

-Duser.name=Your name

to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.

enter image description here

Restart IntelliJ

Return Boolean Value on SQL Select Statement

Given that commonly 1 = true and 0 = false, all you need to do is count the number of rows, and cast to a boolean.

Hence, your posted code only needs a COUNT() function added:

SELECT CAST(COUNT(1) AS BIT) AS Expr1
FROM [User]
WHERE (UserID = 20070022)

cleanest way to skip a foreach if array is empty

foreach((array)$items as $item) {}

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

tl;dr

The answer is NEVER! (unless you really know what you're doing)

9/10 times the solution can be resolved with a proper understanding of encoding/decoding.

1/10 people have an incorrectly defined locale or environment and need to set:

PYTHONIOENCODING="UTF-8"  

in their environment to fix console printing problems.

What does it do?

sys.setdefaultencoding("utf-8") (struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:

str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC") 

In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

(My console is configured as UTF-8, so "€" = '\xe2\x82\xac', hence exception on \xe2)

or

UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)

sys.setdefaultencoding("utf-8") will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into code

Console

sys.setdefaultencoding("utf-8") also has a side effect of appearing to fix sys.stdout.encoding, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING to fix the console encoding.

Example:

$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()

$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€

What's so bad with sys.setdefaultencoding("utf-8")?

People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.

From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/

def welcome_message(byte_string):
    try:
        return u"%s runs your business" % byte_string
    except UnicodeError:
        return u"%s runs your business" % unicode(byte_string,
            encoding=detect_encoding(byte_string))

print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))

Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.

Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.

Example problem

While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte

How to Convert a Text File into a List in Python

This looks like a CSV file, so you could use the python csv module to read it. For example:

import csv

crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]

Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.

How to disable manual input for JQuery UI Datepicker field?

I think you should add style="background:white;" to make looks like it is writable

<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly"   style="background:white;"/>

Decompile .smali files on an APK

I second that.

Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.

However, JDGUI generates .java files which have ,more often than not, errors.

It has got something to do with code obfuscation I guess.

Differences between socket.io and websockets

Its advantages are that it simplifies the usage of WebSockets as you described in #2, and probably more importantly it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. I would avoid using WebSockets directly unless you are very familiar with what environments they don't work and you are capable of working around those limitations.

This is a good read on both WebSockets and Socket.IO.

http://davidwalsh.name/websocket

Select arrow style change

There are a few examples here

It's based off this answer, but I added one to the list to make a design that is even more minimal

select.moreMinimal {

    background-color: inherit;
    display: inline-block;
    font: inherit;
    padding: 0 2.2em 0 1em;    
    margin: 0;      
    cursor: pointer;

    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-appearance: none;
    -moz-appearance: none;
  }

select.moreMinimal {
    background-image:
      linear-gradient(45deg, transparent 50%, gray 50%),
      linear-gradient(135deg, gray 50%, transparent 50%);
    background-position:
      calc(100% - 20px), 
      calc(100% - 15px);
    background-size:
      5px 5px,
      5px 5px;
    background-repeat: no-repeat;
}
  
//TODO: Probably shouldn't be focus, cause when you click it again it's still green
select.moreMinimal:focus {
    background-image:
        linear-gradient(45deg, green 50%, transparent 50%),
        linear-gradient(135deg, transparent 50%, green 50%);
    background-position:
        calc(100% - 15px),
        calc(100% - 20px);
    background-size:
        5px 5px,
        5px 5px;
    background-repeat: no-repeat;
    border-color: green;
    outline: 0;
}

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

I had the same problem, Of course there was a little difference. The story was that when I was removing the below line:

<mvc:resources mapping="/resources/**" location="classpath:/resources/" />

Everything was OK but in presence of that line the same error raise.

After some trial and error I found I have to add the below line to my spring application context file:

<mvc:annotation-driven />

Hope it helps!

How to round the corners of a button

For iOS SWift 4

button.layer.cornerRadius = 25;
button.layer.masksToBounds = true;

Inserting the iframe into react component

If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution

var Iframe = React.createClass({     
  render: function() {
    return(         
      <div>          
        <iframe src={this.props.src} height={this.props.height} width={this.props.width}/>         
      </div>
    )
  }
});

ReactDOM.render(
  <Iframe src="http://plnkr.co/" height="500" width="500"/>,
  document.getElementById('example')
);

here live demo is available Demo

Trigger an action after selection select2

There was made some changes to the select2 events names (I think on v. 4 and later) so the '-' is changed into this ':'.
See the next examples:

$('#select').on("select2:select", function(e) { 
    //Do stuff
});

You can check all the events at the 'select2' plugin site: select2 Events

Send request to curl with post data sourced from a file

I had to use a HTTP connection, because on HTTPS there is default file size limit.

https://techcommunity.microsoft.com/t5/IIS-Support-Blog/Solution-for-Request-Entity-Too-Large-error/ba-p/501134

    curl -i -X 'POST' -F 'file=@/home/testeincremental.xlsx' 'http://example.com/upload.aspx?user=example&password=example123&type=XLSX'

How to find all combinations of coins when given some dollar value

Here's a C# function:

    public static void change(int money, List<int> coins, List<int> combination)
    {
        if(money < 0 || coins.Count == 0) return;
        if (money == 0)
        {
            Console.WriteLine((String.Join("; ", combination)));
            return;
        }

        List<int> copy = new List<int>(coins);
        copy.RemoveAt(0);
        change(money, copy, combination);

        combination = new List<int>(combination) { coins[0] };
        change(money - coins[0], coins, new List<int>(combination));
    }

Use it like this:

change(100, new List<int>() {5, 10, 25}, new List<int>());

It prints:

25; 25; 25; 25
10; 10; 10; 10; 10; 25; 25
10; 10; 10; 10; 10; 10; 10; 10; 10; 10
5; 10; 10; 25; 25; 25
5; 10; 10; 10; 10; 10; 10; 10; 25
5; 5; 10; 10; 10; 10; 25; 25
5; 5; 10; 10; 10; 10; 10; 10; 10; 10; 10
5; 5; 5; 10; 25; 25; 25
5; 5; 5; 10; 10; 10; 10; 10; 10; 25
5; 5; 5; 5; 10; 10; 10; 25; 25
5; 5; 5; 5; 10; 10; 10; 10; 10; 10; 10; 10
5; 5; 5; 5; 5; 25; 25; 25
5; 5; 5; 5; 5; 10; 10; 10; 10; 10; 25
5; 5; 5; 5; 5; 5; 10; 10; 25; 25
5; 5; 5; 5; 5; 5; 10; 10; 10; 10; 10; 10; 10
5; 5; 5; 5; 5; 5; 5; 10; 10; 10; 10; 25
5; 5; 5; 5; 5; 5; 5; 5; 10; 25; 25
5; 5; 5; 5; 5; 5; 5; 5; 10; 10; 10; 10; 10; 10
5; 5; 5; 5; 5; 5; 5; 5; 5; 10; 10; 10; 25
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 25; 25
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 10; 10; 10; 10; 10
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 10; 10; 25
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 10; 10; 10; 10
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 10; 25
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 10; 10; 10
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 25
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 10; 10
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 10
5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5; 5

Code for download video from Youtube on Java, Android

Ref : Youtube Video Download (Android/Java)

private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();

initTypeMap(); call first

class Meta {
    public String num;
    public String type;
    public String ext;

    Meta(String num, String ext, String type) {
        this.num = num;
        this.ext = ext;
        this.type = type;
    }
}

class Video {
    public String ext = "";
    public String type = "";
    public String url = "";

    Video(String ext, String type, String url) {
        this.ext = ext;
        this.type = type;
        this.url = url;
    }
}

public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
        throws IOException {
    if (ytUrl == null) {
        return null;
    }

    // Remove any query params in query string after the watch?v=<vid> in
    // e.g.
    // http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
    int andIdx = ytUrl.indexOf('&');
    if (andIdx >= 0) {
        ytUrl = ytUrl.substring(0, andIdx);
    }

    // Get the HTML response
    /* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
   /* HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            userAgent);
    HttpGet request = new HttpGet(ytUrl);
    HttpResponse response = client.execute(request);*/
    String html = "";
    HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    InputStream in = c.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        str.append(line.replace("\\u0026", "&"));
    }
    in.close();
    html = str.toString();

    // Parse the HTML response and extract the streaming URIs
    if (html.contains("verify-age-thumb")) {
        Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
        return null;
    }

    if (html.contains("das_captcha")) {
        Log.e("Downloader", "Captcha found, please try with different IP address.");
        return null;
    }

    Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
    // Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
    Matcher m = p.matcher(html);
    List<String> matches = new ArrayList<String>();
    while (m.find()) {
        matches.add(m.group());
    }

    if (matches.size() != 1) {
        Log.e("Downloader", "Found zero or too many stream maps.");
        return null;
    }

    String urls[] = matches.get(0).split(",");
    HashMap<String, String> foundArray = new HashMap<String, String>();
    for (String ppUrl : urls) {
        String url = URLDecoder.decode(ppUrl, "UTF-8");
        Log.e("URL","URL : "+url);

        Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
        Matcher m1 = p1.matcher(url);
        String itag = null;
        if (m1.find()) {
            itag = m1.group(1);
        }

        Pattern p2 = Pattern.compile("signature=(.*?)[&]");
        Matcher m2 = p2.matcher(url);
        String sig = null;
        if (m2.find()) {
            sig = m2.group(1);
        } else {
            Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
            Matcher m23 = p23.matcher(url);
            if (m23.find()) {
                sig = m23.group(1);
            }
        }

        Pattern p3 = Pattern.compile("url=(.*?)[&]");
        Matcher m3 = p3.matcher(ppUrl);
        String um = null;
        if (m3.find()) {
            um = m3.group(1);
        }

        if (itag != null && sig != null && um != null) {
            Log.e("foundArray","Adding Value");
            foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
                    + "signature=" + sig);
        }
    }
    Log.e("foundArray","Size : "+foundArray.size());
    if (foundArray.size() == 0) {
        Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
        return null;
    }


    ArrayList<Video> videos = new ArrayList<Video>();

    for (String format : typeMap.keySet()) {
        Meta meta = typeMap.get(format);

        if (foundArray.containsKey(format)) {
            Video newVideo = new Video(meta.ext, meta.type,
                    foundArray.get(format));
            videos.add(newVideo);
            Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
                    + ", type:" + newVideo.type + ", url:" + newVideo.url);
        }
    }

    return videos;
}

private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(webViewActivity.this, "",
                "Connecting to YouTube...", true);
    }

    @Override
    protected ArrayList<Video> doInBackground(String... params) {
        ArrayList<Video> fVideos = new ArrayList<>();
        String url = params[0];
        try {
            ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
            /*                Log.e("Downloader","Size of Video : "+videos.size());*/
            if (videos != null && !videos.isEmpty()) {
                for (Video video : videos)
                {
                    Log.e("Downloader", "ext : " + video.ext);
                    if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
                        ext = video.ext.toLowerCase();
                        fVideos.add(new Video(video.ext,video.type,video.url));
                    }
                }


                return fVideos;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
        }
        Log.e("Downloader", "Couldn't get stream URI for " + url);
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<Video> streamingUrl) {
        super.onPostExecute(streamingUrl);
        progressDialog.dismiss();
        if (streamingUrl != null) {
            if (!streamingUrl.isEmpty()) {
                //Log.e("Steaming Url", "Value : " + streamingUrl);

                for (int i = 0; i < streamingUrl.size(); i++) {
                    Video fX = streamingUrl.get(i);
                    Log.e("Founded Video", "URL : " + fX.url);
                    Log.e("Founded Video", "TYPE : " + fX.type);
                    Log.e("Founded Video", "EXT : " + fX.ext);
                }
                //new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
            }
        }
    }
}
public void initTypeMap()
{
    typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
    typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
    typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
    typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
    typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
    typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
    typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
    typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
    typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
    typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
    typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
    typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
    typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
    typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}

Edit 2:

Some time This Code Not worked proper

Same-origin policy

https://en.wikipedia.org/wiki/Same-origin_policy

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1]. 

Ref : https://superuser.com/questions/773719/how-do-all-of-these-save-video-from-youtube-services-work/773998#773998

url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts              // DASH: contains video or audio stream

Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this

url  // direct HTTP link to a video
itag // code specifying the quality
s    // signature, security measure to counter downloading

Each URL will be encoded so you will need to decode them. Now the tricky part.

YouTube has at least 3 security levels for their videos

unsecured // as expected, you can download these with just the unencoded URL
s         // see below
RTMPE     // uses "rtmpe://" protocol, no known method for these

The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.

The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as

AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this

function mo(a) {
  a = a.split("");
  a = lo.rw(a, 1);
  a = lo.rw(a, 32);
  a = lo.IC(a, 1);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 44);
  return a.join("")
}

This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as

http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js

this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header

Access-Control-Allow-Origin: http://www.youtube.com

and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests

Access-Control-Allow-Origin: *

So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.

How do you configure HttpOnly cookies in tomcat / java webapps?

If your web server supports Serlvet 3.0 spec, like tomcat 7.0+, you can use below in web.xml as:

<session-config>
  <cookie-config>
     <http-only>true</http-only>        
     <secure>true</secure>        
  </cookie-config>
</session-config>

As mentioned in docs:

HttpOnly: Specifies whether any session tracking cookies created by this web application will be marked as HttpOnly

Secure: Specifies whether any session tracking cookies created by this web application will be marked as secure even if the request that initiated the corresponding session is using plain HTTP instead of HTTPS

Please refer to how to set httponly and session cookie for java web application

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

How to write a CSS hack for IE 11?

You can use the following code inside the style tag:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
/* IE10+ specific styles go here */  
}

Below is an example that worked for me:

<style type="text/css">

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
   #flashvideo {
        width:320px;
        height:240;
        margin:-240px 0 0 350px;
        float:left;
    }

    #googleMap {
        width:320px;
        height:240;
        margin:-515px 0 0 350px;
        float:left;
        border-color:#000000;
    }
}

#nav li {
    list-style:none;
    width:240px;
    height:25px;
    }

#nav a {
    display:block;
    text-indent:-5000px;
    height:25px;
    width:240px;
    }
</style>

Please note that since (#nav li) and (#nav a) are outside of the @media screen ..., they are general styles.

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

jquery to change style attribute of a div class

$('.handle').css('left', '300px');

$('.handle').css({
    left : '300px'
});

$('.handle').attr('style', 'left : 300px');

or use OrnaJS

How to set default font family in React Native?

That works for me: Add Custom Font in React Native

download your fonts and place them in assets/fonts folder, add this line in package.json

 "rnpm": {
"assets": ["assets/fonts/Sarpanch"]}

then open terminal and run this command: react-native link

Now your are good to go. For more detailed step. visit the link above mentioned

Make selected block of text uppercase

I think you can use Step 1: Select text Step 2: Ctrl + Shift + P Step 3: Enter Uppercae

Update statement with inner join on Oracle

UPDATE IP_ADMISSION_REQUEST ip1
SET IP1.WRIST_BAND_PRINT_STATUS=0
WHERE IP1.IP_ADM_REQ_ID        =
  (SELECT IP.IP_ADM_REQ_ID
  FROM IP_ADMISSION_REQUEST ip
  INNER JOIN VISIT v
  ON ip.ip_visit_id=v.visit_id
  AND v.pat_id     =3702
  ); `enter code here`

how to use the Box-Cox power transformation in R

Box and Cox (1964) suggested a family of transformations designed to reduce nonnormality of the errors in a linear model. In turns out that in doing this, it often reduces non-linearity as well.

Here is a nice summary of the original work and all the work that's been done since: http://www.ime.usp.br/~abe/lista/pdfm9cJKUmFZp.pdf

You will notice, however, that the log-likelihood function governing the selection of the lambda power transform is dependent on the residual sum of squares of an underlying model (no LaTeX on SO -- see the reference), so no transformation can be applied without a model.

A typical application is as follows:

library(MASS)

# generate some data
set.seed(1)
n <- 100
x <- runif(n, 1, 5)
y <- x^3 + rnorm(n)

# run a linear model
m <- lm(y ~ x)

# run the box-cox transformation
bc <- boxcox(y ~ x)

enter image description here

(lambda <- bc$x[which.max(bc$y)])
[1] 0.4242424

powerTransform <- function(y, lambda1, lambda2 = NULL, method = "boxcox") {

  boxcoxTrans <- function(x, lam1, lam2 = NULL) {

    # if we set lambda2 to zero, it becomes the one parameter transformation
    lam2 <- ifelse(is.null(lam2), 0, lam2)

    if (lam1 == 0L) {
      log(y + lam2)
    } else {
      (((y + lam2)^lam1) - 1) / lam1
    }
  }

  switch(method
         , boxcox = boxcoxTrans(y, lambda1, lambda2)
         , tukey = y^lambda1
  )
}


# re-run with transformation
mnew <- lm(powerTransform(y, lambda) ~ x)

# QQ-plot
op <- par(pty = "s", mfrow = c(1, 2))
qqnorm(m$residuals); qqline(m$residuals)
qqnorm(mnew$residuals); qqline(mnew$residuals)
par(op)

enter image description here

As you can see this is no magic bullet -- only some data can be effectively transformed (usually a lambda less than -2 or greater than 2 is a sign you should not be using the method). As with any statistical method, use with caution before implementing.

To use the two parameter Box-Cox transformation, use the geoR package to find the lambdas:

library("geoR")
bc2 <- boxcoxfit(x, y, lambda2 = TRUE)

lambda1 <- bc2$lambda[1]
lambda2 <- bc2$lambda[2]

EDITS: Conflation of Tukey and Box-Cox implementation as pointed out by @Yui-Shiuan fixed.

What is a classpath and how do I set it?

Setting the CLASSPATH System Variable

To display the current CLASSPATH variable, use these commands in Windows and UNIX (Bourne shell): In Windows: C:\> set CLASSPATH In UNIX: % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use these commands: In Windows: C:\> set CLASSPATH= In UNIX: % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable, use these commands (for example): In Windows: C:\> set CLASSPATH=C:\users\george\java\classes In UNIX: % CLASSPATH=/home/george/java/classes; export CLASSPATH

HTML radio buttons allowing multiple selections

Try this way of formation, it is rather fancy ...

Have a look at this jsfiddle

Button-Radio

The idea is to choose a the radio as a button instead of the normal circle image.

Run a Python script from another Python script, passing in arguments

This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:

import script1

In an ideal world, you will be able to call a function inside script1 directly:

for i in range(whatever):
    script1.some_function(i)

If necessary, you can hack sys.argv. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.

import contextlib
@contextlib.contextmanager
def redirect_argv(num):
    sys._argv = sys.argv[:]
    sys.argv=[str(num)]
    yield
    sys.argv = sys._argv

with redirect_argv(1):
    print(sys.argv)

I think this is preferable to passing all your data to the OS and back; that's just silly.

Do Java arrays have a maximum size?

There are actually two limits. One, the maximum element indexable for the array and, two, the amount of memory available to your application. Depending on the amount of memory available and the amount used by other data structures, you may hit the memory limit before you reach the maximum addressable array element.

How do you build a Singleton in Dart?

Modified @Seth Ladd answer for who's prefer Swift style of singleton like .shared:

class Auth {
  // singleton
  static final Auth _singleton = Auth._internal();
  factory Auth() => _singleton;
  Auth._internal();
  static Auth get shared => _singleton;

  // variables
  String username;
  String password;
}

Sample:

Auth.shared.username = 'abc';

How can you tell when a layout has been drawn?

You can add a tree observer to the layout. This should return the correct width and height. onCreate() is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width, put this on the onCreate() method:

    final LinearLayout layout = (LinearLayout) findViewById(R.id.YOUR_VIEW_ID);
    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    layout.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
            int width  = layout.getMeasuredWidth();
            int height = layout.getMeasuredHeight(); 

        } 
    });

An error occurred while signing: SignTool.exe not found

I did have similar problem. For some reason under project properties -> Signing -> Sign ClickOnce manifests was enabled.

I unchecked it and the problem went away.

How do you write a migration to rename an ActiveRecord model and its table in Rails?

You can do execute this command : rails g migration rename_{old_table_name}to{new_table_name}

after you edit the file and add this code in the method change

rename_table :{old_table_name}, :{new_table_name}

MySQL JOIN ON vs USING?

For those experimenting with this in phpMyAdmin, just a word:

phpMyAdmin appears to have a few problems with USING. For the record this is phpMyAdmin run on Linux Mint, version: "4.5.4.1deb2ubuntu2", Database server: "10.2.14-MariaDB-10.2.14+maria~xenial - mariadb.org binary distribution".

I have run SELECT commands using JOIN and USING in both phpMyAdmin and in Terminal (command line), and the ones in phpMyAdmin produce some baffling responses:

1) a LIMIT clause at the end appears to be ignored.
2) the supposed number of rows as reported at the top of the page with the results is sometimes wrong: for example 4 are returned, but at the top it says "Showing rows 0 - 24 (2503 total, Query took 0.0018 seconds.)"

Logging on to mysql normally and running the same queries does not produce these errors. Nor do these errors occur when running the same query in phpMyAdmin using JOIN ... ON .... Presumably a phpMyAdmin bug.

how to run two commands in sudo?

I usually do:

sudo bash -c 'whoami; whoami'

git push rejected: error: failed to push some refs

for me following worked, just ran these command one by one

git pull -r origin master

git push -f origin your_branch

Url.Action parameters?

you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :

var qs = HttpUtility.ParseQueryString(""); 
qs.Add("name", "John")
qs.Add("contact", "calgary");
qs.Add("contact", "vancouver")

<a href="<%: Url.Action("GetByList", "Listing")%>?<%:qs%>">
    <span>People</span>
</a>

How to run ssh-add on windows?

Original answer using git's start-ssh-agent

Make sure you have Git installed and have git's cmd folder in your PATH. For example, on my computer the path to git's cmd folder is C:\Program Files\Git\cmd

Make sure your id_rsa file is in the folder c:\users\yourusername\.ssh

Restart your command prompt if you haven't already, and then run start-ssh-agent. It will find your id_rsa and prompt you for the passphrase

Update 2019 - A better solution if you're using Windows 10: OpenSSH is available as part of Windows 10 which makes using SSH from cmd/powershell much easier in my opinion. It also doesn't rely on having git installed, unlike my previous solution.

  1. Open Manage optional features from the start menu and make sure you have Open SSH Client in the list. If not, you should be able to add it.

  2. Open Services from the start Menu

  3. Scroll down to OpenSSH Authentication Agent > right click > properties

  4. Change the Startup type from Disabled to any of the other 3 options. I have mine set to Automatic (Delayed Start)

  5. Open cmd and type where ssh to confirm that the top listed path is in System32. Mine is installed at C:\Windows\System32\OpenSSH\ssh.exe. If it's not in the list you may need to close and reopen cmd.

Once you've followed these steps, ssh-agent, ssh-add and all other ssh commands should now work from cmd. To start the agent you can simply type ssh-agent.

  1. Optional step/troubleshooting: If you use git, you should set the GIT_SSH environment variable to the output of where ssh which you ran before (e.g C:\Windows\System32\OpenSSH\ssh.exe). This is to stop inconsistencies between the version of ssh you're using (and your keys are added/generated with) and the version that git uses internally. This should prevent issues that are similar to this

Some nice things about this solution:

  • You won't need to start the ssh-agent every time you restart your computer
  • Identities that you've added (using ssh-add) will get automatically added after restarts. (It works for me, but you might possibly need a config file in your c:\Users\User\.ssh folder)
  • You don't need git!
  • You can register any rsa private key to the agent. The other solution will only pick up a key named id_rsa

Hope this helps

What is an API key?

What "exactly" an API key is used for depends very much on who issues it, and what services it's being used for. By and large, however, an API key is the name given to some form of secret token which is submitted alongside web service (or similar) requests in order to identify the origin of the request. The key may be included in some digest of the request content to further verify the origin and to prevent tampering with the values.

Typically, if you can identify the source of a request positively, it acts as a form of authentication, which can lead to access control. For example, you can restrict access to certain API actions based on who's performing the request. For companies which make money from selling such services, it's also a way of tracking who's using the thing for billing purposes. Further still, by blocking a key, you can partially prevent abuse in the case of too-high request volumes.

In general, if you have both a public and a private API key, then it suggests that the keys are themselves a traditional public/private key pair used in some form of asymmetric cryptography, or related, digital signing. These are more secure techniques for positively identifying the source of a request, and additionally, for protecting the request's content from snooping (in addition to tampering).

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

If behind a proxy, you can navigate to Ruby downloads, click on Download, which will download the specified update ( or Gem ) to a desired location.

Next, via Ruby command line, navigate to the downloaded location by using : pushd [directory]

eg : pushd D:\Setups

then run the following command: gem install [update name] --local

eg: gem install rubygems-update --local.

Tested on Windows 7 with Ruby update version 2.4.1.

To check use following command : ruby -v

How to check if a json key exists?

you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also

use optString instead of getString:

Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists

HTTPS connection Python

I had some code that was failing with an HTTPConnection (MOVED_PERMANENTLY error), but as soon as I switched to HTTPS it worked perfectly again with no other changes needed. That's a very simple fix!

oracle sql: update if exists else insert

The way I always do it (assuming the data is never to be deleted, only inserted) is to

  • Firstly do an insert, if this fails with a unique constraint violation then you know the row is there,
  • Then do an update

Unfortunately many frameworks such as Hibernate treat all database errors (e.g. unique constraint violation) as unrecoverable conditions, so it isn't always easy. (In Hibernate the solution is to open a new session/transaction just to execute this one insert command.)

You can't just do a select count(*) .. where .. as even if that returns zero, and therefore you choose to do an insert, between the time you do the select and the insert someone else might have inserted the row and therefore your insert will fail.

JDBC connection to MSSQL server in windows authentication mode

Using windows authentication:

String url ="jdbc:sqlserver://PC01\inst01;databaseName=DB01;integratedSecurity=true";

Using SQL authentication:

String url ="jdbc:sqlserver://PC01\inst01;databaseName=DB01";

Error 5 : Access Denied when starting windows service

In may case system run out of free space on local disk.

Set transparent background of an imageview on Android

There is already a transparent built into Android: R.color.transparent. http://developer.android.com/reference/android/R.color.html#transparent

But I think you may want to make the background of the image that you are placing into the WebView transparent, for example, with a transparent PNG, rather than the ImageView background. If the actual image is not at all see-through then the ImageView background can't be seen through it.

Converting from byte to int in java

Primitive data types (such as byte) don't have methods in java, but you can directly do:

int i=rno[0];

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

This worked for me

Use the installation of the Visual Studio

On the tab "Workloads" check ".Net Core cross-platform development" and click on "Modify"

enter image description here

Don't forget to check ".NET Core 2.0 development tools" on the left menu.

Source

Note

I installed the Asp Net Core before, however not appeared on my Visual Studio, just after I installed using the installation of Visual Studio appeared for me.

How to fix the session_register() deprecated issue?

Don't use it. The description says:

Register one or more global variables with the current session.

Two things that came to my mind:

  1. Using global variables is not good anyway, find a way to avoid them.
  2. You can still set variables with $_SESSION['var'] = "value".

See also the warnings from the manual:

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

This is pretty important, because the register_globals directive is set to False by default!

Further:

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

and

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister().

How to make a local variable (inside a function) global

You could use module scope. Say you have a module called utils:

f_value = 'foo'

def f():
    return f_value

f_value is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils from one module will be accessible to all other modules that have it imported:

>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'

Note that you can import the function by name:

>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'

But not the attribute:

>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'

This is because you're labeling the object referenced by the module attribute as f_value in the local scope, but then rebinding it to the string bar, while the function f is still referring to the module attribute.

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

Extract values in Pandas value_counts()

#!/usr/bin/env python

import pandas as pd

# Make example dataframe
df = pd.DataFrame([(1, 'Germany'),
                   (2, 'France'),
                   (3, 'Indonesia'),
                   (4, 'France'),
                   (5, 'France'),
                   (6, 'Germany'),
                   (7, 'UK'),
                   ],
                  columns=['groupid', 'country'],
                  index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# What you're looking for
values = df['country'].value_counts().keys().tolist()
counts = df['country'].value_counts().tolist()

Now, print(df['country'].value_counts()) gives:

France       3
Germany      2
UK           1
Indonesia    1

and print(values) gives:

['France', 'Germany', 'UK', 'Indonesia']

and print(counts) gives:

[3, 2, 1, 1]

Convert Text to Date?

I had a very similar issue earlier. Unfortunately I looked at this thread and didn't find an answer which I was happy with. Hopefully this will help others.

Using VBA.DateSerial(year,month,day) you can overcome Excel's intrinsic bias to US date format. It also means you have full control over the data, which is something I personally prefer:

function convDate(str as string) as Date
  Dim day, month, year as integer
  year  = int(mid(str,1,4))
  month = int(mid(str,6,2))
  day   = int(mid(str,9,2))
  convDate = VBA.DateSerial(year,month,day)
end function

Skipping every other element after the first

Using the for-loop like you have, one way is this:

def altElement(a):
    b = []
    j = False
    for i in a:
        j = not j
        if j:
            b.append(i)

    print b

j just keeps switching between 0 and 1 to keep track of when to append an element to b.

String replace a Backslash

This will replace backslashes with forward slashes in the string:

source = source.replace('\\','/');

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

Get characters after last / in url

Here's a beautiful dynamic function I wrote to remove last part of url or path.

/**
 * remove the last directories
 *
 * @param $path the path
 * @param $level number of directories to remove
 *
 * @return string
 */
private function removeLastDir($path, $level)
{
    if(is_int($level) && $level > 0){
        $path = preg_replace('#\/[^/]*$#', '', $path);
        return $this->removeLastDir($path, (int) $level - 1);
    }
    return $path;
}

Error C1083: Cannot open include file: 'stdafx.h'

Add #include "afxwin.h" in your source file. It will solve your issue.

ASP.Net 2012 Unobtrusive Validation with jQuery

<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />

this line was not in my WebConfig so : I simple solved this by downgrading targetting .Net version to 4.0 :)

List of macOS text editors and code editors

I have to say that i love Coda, it can do almost anything you need in 'plain' text WebDevelopent, i use it daily to develop simple and complex projects using XHTML,PHP,Javascript,CSS...

Ok, it's not free but compare it with many other development suits and you'll find that that 100$ are really affordable (i bought many months ago when it was at about 60$) In the last version they included a lot of new nice features and whoa... just look at the panic WebSite

Before using coda i was a hardcore ZendStudio User, i used that in Windows,Linux and Mac (i have been user for a long time for all that platforms) as it was developed in Java it was really slow even in a modern MacBookPro.. so i also tested a lots of diferent IDEs for developing but at this moment any of these are as powerful and simple as Coda is

How do you get the file size in C#?

FileInfo.Length will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.

@AspectJ pointcut for all methods of a class with specific annotation

The simplest way seems to be :

@Around("execution(@MyHandling * com.exemple.YourService.*(..))")
public Object aroundServiceMethodAdvice(final ProceedingJoinPoint pjp)
   throws Throwable {
   // perform actions before

   return pjp.proceed();

   // perform actions after
}

It will intercept execution of all methods specifically annotated with '@MyHandling' in 'YourService' class. To intercept all methods without exception, just put the annotation directly on the class.

No matter of the private / public scope here, but keep in mind that spring-aop cannot use aspect for method calls in same instance (typically private ones), because it doesn't use the proxy class in this case.

We use @Around advice here, but it's basically the same syntax with @Before, @After or any advice.

By the way, @MyHandling annotation must be configured like this :

@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface MyHandling {

}

How do I set response headers in Flask?

This was how added my headers in my flask application and it worked perfectly

@app.after_request
def add_header(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    return response

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

I know this post is old but here is what I found. It doesn't work when I link it this way(with / before css/style.csson the href attribute.

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

However, when I removed / I'm able to link properly with the css file It should be like this(without /).

<link rel="stylesheet" media="all" href="CSS/Style.css" type="text/css" />

This was giving me trouble on my project. Hope it will help somebody else.

Split files using tar, gz, zip, or bzip2

use tar to split into multiple archives

there are plenty of programs that will work with tar files on windows, including cygwin.

Fatal error: Namespace declaration statement has to be the very first statement in the script in

Make sure there is no whitespace before your php tag

// whitespace
<?php
    namespace HelloWorld
?>

Remove the white space before your php tag starts

<?php
    namespace HelloWorld
?>

Simple 'if' or logic statement in Python

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

dereferencing pointer to incomplete type

I don't exactly understand what's the problem. Incomplete type is not the type that's "missing". Incompete type is a type that is declared but not defined (in case of struct types). To find the non-defining declaration is easy. As for the finding the missing definition... the compiler won't help you here, since that is what caused the error in the first place.

A major reason for incomplete type errors in C are typos in type names, which prevent the compiler from matching one name to the other (like in matching the declaration to the definition). But again, the compiler cannot help you here. Compiler don't make guesses about typos.

No Such Element Exception?

I Know this question was aked 3 years ago, but I just had the same problem, and what solved it was instead of putting:

 while (i.hasNext()) {
    // code goes here 
}

I did one iteration at the start, and then checked for condition using:

do {
   // code goes here
} while (i.hasNext());

I hope this will help some people at some stage.

How to add an object to an array

Using ES6 notation, you can do something like this:

For appending you can use the spread operator like this:

_x000D_
_x000D_
var arr1 = [1,2,3]_x000D_
var obj = 4_x000D_
var newData = [...arr1, obj] // [1,2,3,4]_x000D_
console.log(newData);
_x000D_
_x000D_
_x000D_

Add Header and Footer for PDF using iTextsharp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using DataLayer;

namespace DataMngt.MyCode
{
    public class HeaderFooter : PdfPageEventHelper
    {
        #region Startup_Stuff

        private string[] _headerLines;
        private string _footerLine;

        private DefineFont _boldFont;
        private DefineFont _normalFont;

        private iTextSharp.text.Font fontTxtBold;
        private iTextSharp.text.Font fontTxtRegular;

        private int _fontPointSize = 0;

        private bool hasFooter = false;
        private bool hasHeader = false;

        private int _headerWidth = 0;
        private int _headerHeight = 0;

        private int _footerWidth = 0;
        private int _footerHeight = 0;

        private int _leftMargin = 0;
        private int _rightMargin = 0;
        private int _topMargin = 0;
        private int _bottomMargin = 0;

        private PageNumbers NumberSettings;

        private DateTime runTime = DateTime.Now;             

        public enum PageNumbers
        {
            None,
            HeaderPlacement,
            FooterPlacement
        }

        // This is the contentbyte object of the writer
        PdfContentByte cb;

        PdfTemplate headerTemplate;
        PdfTemplate footerTemplate;

        public string[] headerLines
        {
            get
            {
                return _headerLines;
            }
            set
            {
                _headerLines = value;
                hasHeader = true;
            }
        }

        public string footerLine
        {
            get
            {
                return _footerLine;
            }
            set
            {
                _footerLine = value;
                hasFooter = true;
            }
        }

        public DefineFont boldFont
        {
            get
            {
                return _boldFont;
            }
            set
            {
                _boldFont = value;
            }
        }

        public DefineFont normalFont
        {
            get
            {
                return _normalFont;
            }
            set
            {
                _normalFont = value;
            }
        }

        public int fontPointSize
        {
            get
            {
                return _fontPointSize;
            }
            set
            {
                _fontPointSize = value;
            }
        }

        public int leftMargin
        {
            get
            {
                return _leftMargin;
            }
            set
            {
                _leftMargin = value;
            }
        }

        public int rightMargin
        {
            get
            {
                return _rightMargin;
            }
            set
            {
                _rightMargin = value;
            }
        }

        public int topMargin
        {
            get
            {
                return _topMargin;
            }
            set
            {
                _topMargin = value;
            }
        }

        public int bottomMargin
        {
            get
            {
                return _bottomMargin;
            }
            set
            {
                _bottomMargin = value;
            }
        }

        public int headerheight
        {
            get
            {
                return _headerHeight;
            }
        }

        public int footerHeight
        {
            get
            {
                return _footerHeight;
            }
        }

        public PageNumbers PageNumberSettings
        {
            get
            {
                return NumberSettings;
            }

            set
            {
                NumberSettings = value;
            }
        }

        #endregion

        #region Write_Headers_Footers

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            if (hasHeader)
            {
                // left side is the string array passed in
                // right side is a built in string array (0 = date, 1 = time, 2(optional) = page)
                float[] widths = new float[2] { 90f, 10f };

                PdfPTable hdrTable = new PdfPTable(2);
                hdrTable.TotalWidth = document.PageSize.Width - (_leftMargin + _rightMargin);
                hdrTable.WidthPercentage = 95;
                hdrTable.SetWidths(widths);
                hdrTable.LockedWidth = true;

                for (int hdrIdx = 0; hdrIdx < (_headerLines.Length < 2 ? 2 : _headerLines.Length); hdrIdx ++)
                {
                    string leftLine = (hdrIdx < _headerLines.Length ? _headerLines[hdrIdx] : string.Empty);

                    Paragraph leftPara = new Paragraph(5, leftLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular));

                    switch (hdrIdx)
                    {
                        case 0:
                            {
                                leftPara.Font.Size = _fontPointSize;

                                PdfPCell leftCell = new PdfPCell(leftPara);
                                leftCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                leftCell.Border = 0;

                                string rightLine = string.Format(SalesPlanResources.datePara, runTime.ToString(SalesPlanResources.datePrintMask));
                                Paragraph rightPara = new Paragraph(5, rightLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular));
                                rightPara.Font.Size = _fontPointSize;

                                PdfPCell rightCell = new PdfPCell(rightPara);
                                rightCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                rightCell.Border = 0;

                                hdrTable.AddCell(leftCell);
                                hdrTable.AddCell(rightCell);

                                break;
                            }

                        case 1:
                            {
                                leftPara.Font.Size = _fontPointSize;

                                PdfPCell leftCell = new PdfPCell(leftPara);
                                leftCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                leftCell.Border = 0;

                                string rightLine = string.Format(SalesPlanResources.timePara, runTime.ToString(SalesPlanResources.timePrintMask));
                                Paragraph rightPara = new Paragraph(5, rightLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular));
                                rightPara.Font.Size = _fontPointSize;

                                PdfPCell rightCell = new PdfPCell(rightPara);
                                rightCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                rightCell.Border = 0;

                                hdrTable.AddCell(leftCell);
                                hdrTable.AddCell(rightCell);

                                break;
                            }

                        case 2:
                            {
                                leftPara.Font.Size = _fontPointSize;

                                PdfPCell leftCell = new PdfPCell(leftPara);
                                leftCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                leftCell.Border = 0;

                                string rightLine;
                                if (NumberSettings == PageNumbers.HeaderPlacement)
                                {
                                    rightLine = string.Concat(SalesPlanResources.pagePara, writer.PageNumber.ToString());
                                }
                                else
                                {
                                    rightLine = string.Empty; 
                                }
                                Paragraph rightPara = new Paragraph(5, rightLine, fontTxtRegular);
                                rightPara.Font.Size = _fontPointSize;

                                PdfPCell rightCell = new PdfPCell(rightPara);
                                rightCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                rightCell.Border = 0;

                                hdrTable.AddCell(leftCell);
                                hdrTable.AddCell(rightCell);

                                break;
                            }

                        default:
                            {
                                leftPara.Font.Size = _fontPointSize;

                                PdfPCell leftCell = new PdfPCell(leftPara);
                                leftCell.HorizontalAlignment = Element.ALIGN_LEFT;
                                leftCell.Border = 0;
                                leftCell.Colspan = 2;                               

                                hdrTable.AddCell(leftCell);

                                break;
                            }
                    }
                }

                hdrTable.WriteSelectedRows(0, -1, _leftMargin, document.PageSize.Height - _topMargin, writer.DirectContent);

                //Move the pointer and draw line to separate header section from rest of page
                cb.MoveTo(_leftMargin, document.Top + 10);
                cb.LineTo(document.PageSize.Width - _leftMargin, document.Top + 10);
                cb.Stroke();
            }

            if (hasFooter)
            {
                // footer line is the width of the page so it is centered horizontally 
                PdfPTable ftrTable = new PdfPTable(1);
                float[] widths = new float[1] {100 };

                ftrTable.TotalWidth = document.PageSize.Width - 10;
                ftrTable.WidthPercentage = 95;
                ftrTable.SetWidths(widths);

                string OneLine;

                if (NumberSettings == PageNumbers.FooterPlacement)
                {
                    OneLine = string.Concat(_footerLine, writer.PageNumber.ToString());
                }
                else
                {
                    OneLine = _footerLine;
                }

                Paragraph onePara = new Paragraph(0, OneLine, fontTxtRegular);
                onePara.Font.Size = _fontPointSize;

                PdfPCell oneCell = new PdfPCell(onePara);
                oneCell.HorizontalAlignment = Element.ALIGN_CENTER; 
                oneCell.Border = 0;
                ftrTable.AddCell(oneCell);

                ftrTable.WriteSelectedRows(0, -1, _leftMargin, (_footerHeight), writer.DirectContent);

                //Move the pointer and draw line to separate footer section from rest of page
                cb.MoveTo(_leftMargin, document.PageSize.GetBottom(_footerHeight + 2));
                cb.LineTo(document.PageSize.Width - _leftMargin, document.PageSize.GetBottom(_footerHeight + 2));
                cb.Stroke();
            }
        }

        #endregion


        #region Setup_Headers_Footers_Happens_here

        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            // create the fonts that are to be used
            // first the hightlight or Bold font
            fontTxtBold = FontFactory.GetFont(_boldFont.fontFamily, _boldFont.fontSize, _boldFont.foreColor);
            if (_boldFont.isBold)
            {
                fontTxtBold.SetStyle(Font.BOLD);
            }
            if (_boldFont.isItalic)
            {
                fontTxtBold.SetStyle(Font.ITALIC);
            }
            if (_boldFont.isUnderlined)
            {
                fontTxtBold.SetStyle(Font.UNDERLINE);
            }

            // next the normal font
            fontTxtRegular = FontFactory.GetFont(_normalFont.fontFamily, _normalFont.fontSize, _normalFont.foreColor);
            if (_normalFont.isBold)
            {
                fontTxtRegular.SetStyle(Font.BOLD);
            }
            if (_normalFont.isItalic)
            {
                fontTxtRegular.SetStyle(Font.ITALIC);
            }
            if (_normalFont.isUnderlined)
            {
                fontTxtRegular.SetStyle(Font.UNDERLINE);
            }

            // now build the header and footer templates
            try
            {
                float pageHeight = document.PageSize.Height;
                float pageWidth = document.PageSize.Width;

                _headerWidth = (int)pageWidth - ((int)_rightMargin + (int)_leftMargin);
                _footerWidth = _headerWidth;

                if (hasHeader)
                {
                    // i basically dummy build the headers so i can trial fit them and see how much space they take.
                    float[] widths = new float[1] { 90f };

                    PdfPTable hdrTable = new PdfPTable(1);
                    hdrTable.TotalWidth = document.PageSize.Width - (_leftMargin + _rightMargin);
                    hdrTable.WidthPercentage = 95;
                    hdrTable.SetWidths(widths);
                    hdrTable.LockedWidth = true;

                    _headerHeight = 0;

                    for (int hdrIdx = 0; hdrIdx < (_headerLines.Length < 2 ? 2 : _headerLines.Length); hdrIdx++)
                    {
                        Paragraph hdrPara = new Paragraph(5, hdrIdx > _headerLines.Length - 1 ? string.Empty : _headerLines[hdrIdx], (hdrIdx > 0 ? fontTxtRegular : fontTxtBold));
                        PdfPCell hdrCell = new PdfPCell(hdrPara);
                        hdrCell.HorizontalAlignment = Element.ALIGN_LEFT;
                        hdrCell.Border = 0;
                        hdrTable.AddCell(hdrCell);
                        _headerHeight = _headerHeight + (int)hdrTable.GetRowHeight(hdrIdx);
                    }

                    // iTextSharp underestimates the size of each line so fudge it a little 
                    // this gives me 3 extra lines to play with on the spacing
                    _headerHeight = _headerHeight + (_fontPointSize * 3);

                }

                if (hasFooter)
                {
                    _footerHeight = (_fontPointSize * 2);
                }

                document.SetMargins(_leftMargin, _rightMargin, (_topMargin + _headerHeight), _footerHeight);

                cb = writer.DirectContent;

                if (hasHeader)
                {
                    headerTemplate = cb.CreateTemplate(_headerWidth, _headerHeight);
                }

                if (hasFooter)
                {
                    footerTemplate = cb.CreateTemplate(_footerWidth, _footerHeight);
                }
            }
            catch (DocumentException de)
            {

            }
            catch (System.IO.IOException ioe)
            {

            }
        }

        #endregion

        #region Cleanup_Doc_Processing

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);

            if (hasHeader)
            {
                headerTemplate.BeginText();
                headerTemplate.SetTextMatrix(0, 0);

                if (NumberSettings == PageNumbers.HeaderPlacement)
                {
                }

                headerTemplate.EndText();
            }

            if (hasFooter)
            {
                footerTemplate.BeginText();
                footerTemplate.SetTextMatrix(0, 0);

                if (NumberSettings == PageNumbers.FooterPlacement)
                {
                }

                footerTemplate.EndText();
            }
        }

        #endregion

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace DataMngt.MyCode
{

    // used to define the fonts passed into the header and footer class
    public struct DefineFont
    {
        public string fontFamily { get; set; }
        public int fontSize { get; set; }
        public bool isBold { get; set; }
        public bool isItalic { get; set; }
        public bool isUnderlined { get; set; }
        public BaseColor foreColor { get; set; }
    }
}

To Use:

 Document pdfDoc = new Document(PageSize.LEGAL.Rotate(), 10, 10, 25, 25);
 System.IO.MemoryStream mStream = new System.IO.MemoryStream();
 PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
 MyCode.HeaderFooter headers = new MyCode.HeaderFooter();
 writer.PageEvent = headers;

.. .. Build the string array for the headers ...

DefineFont passFont = new DefineFont();

    // always set this to the largest font used
    headers.fontPointSize = 8;

    // set up the highlight or bold font
    passFont.fontFamily = "Helvetica";
    passFont.fontSize = 8;
    passFont.isBold = true;
    passFont.isItalic = false;
    passFont.isUnderlined = false;
    passFont.foreColor = BaseColor.BLACK;

    headers.boldFont = passFont;

    // now setup the normal text font
    passFont.fontSize = 7;
    passFont.isBold = false;

    headers.normalFont = passFont;

    headers.leftMargin = 10;
    headers.bottomMargin = 25;
    headers.rightMargin = 10;
    headers.topMargin = 25;

    headers.PageNumberSettings = HeaderFooter.PageNumbers.FooterPlacement;

    headers.footerLine = "Page";
    headers.headerLines = parmLines.ToArray();

    pdfDoc.SetMargins(headers.leftMargin, headers.rightMargin, headers.topMargin + headers.headerheight, headers.bottomMargin + headers.footerHeight);
    pdfDoc.Open();

    // the new page is necessary due to a bug in in the current version of itextsharp
    pdfDoc.NewPage();

... now your headers and footer will be handled automatically

Creating an array from a text file in Bash

Use the mapfile command:

mapfile -t myArray < file.txt

The error is using for -- the idiomatic way to loop over lines of a file is:

while IFS= read -r line; do echo ">>$line<<"; done < file.txt

See BashFAQ/005 for more details.

Changing text color of menu item in navigation drawer

More options:

you can also change the group title by overriding "textColorSecondary"

In your styles.xml

<style name="AppTheme.NavigationView">
    <item name="android:textColorSecondary">#FFFFFF</item>
</style>

In your layout

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/activity_main_menu_drawer_drawer"
    android:theme="@style/AppTheme.NavigationView"
    app:itemIconTint="@color/colorPrimary"
    app:itemTextColor="@color/white"/>

incompatible character encodings: ASCII-8BIT and UTF-8

Try to find the exact line which causing this problem and then enforce UTF8 coding, this solution worked for me.

title.to_s.force_encoding("UTF-8")

Correct way to detach from a container without stopping it

You can use the --detach-keys option when you run docker attach to override the default CTRL+P, CTRL + Q sequence (that doesn't always work).

For example, when you run docker attach --detach-keys="ctrl-a" test and you press CTRL+A you will exit the container, without killing it.

Other examples:

  • docker attach --detach-keys="ctrl-a,x" test - press CTRL+A and then X to exit
  • docker attach --detach-keys="a,b,c" test - press A, then B, then C to exit

Extract from the official documentation:

If you want, you can configure an override the Docker key sequence for detach. This is useful if the Docker default sequence conflicts with key sequence you use for other applications. There are two ways to define your own detach key sequence, as a per-container override or as a configuration property on your entire configuration.

To override the sequence for an individual container, use the --detach-keys="<sequence>" flag with the docker attach command. The format of the <sequence> is either a letter [a-Z], or the ctrl- combined with any of the following:

  • a-z (a single lowercase alpha character )
  • @ (at sign)
  • [ (left bracket)
  • \ (two backward slashes)
  • _ (underscore)
  • ^ (caret)

These a, ctrl-a, X, or ctrl-\\ values are all examples of valid key sequences. To configure a different configuration default key sequence for all containers, see Configuration file section.

Note: This works since docker version 1.10+ (at the time of this answer, the current version is 18.03)

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

pull/push from multiple remote locations

Here is my example with bash script inside .gitconfig alias section

[alias]
        pushall = "!f(){ for i in `git remote`; do git push $i; done; };f"

How to pass arguments to Shell Script through docker run

There are a few things interacting here:

  1. docker run your_image arg1 arg2 will replace the value of CMD with arg1 arg2. That's a full replacement of the CMD, not appending more values to it. This is why you often see docker run some_image /bin/bash to run a bash shell in the container.

  2. When you have both an ENTRYPOINT and a CMD value defined, docker starts the container by concatenating the two and running that concatenated command. So if you define your entrypoint to be file.sh, you can now run the container with additional args that will be passed as args to file.sh.

  3. Entrypoints and Commands in docker have two syntaxes, a string syntax that will launch a shell, and a json syntax that will perform an exec. The shell is useful to handle things like IO redirection, chaining multiple commands together (with things like &&), variable substitution, etc. However, that shell gets in the way with signal handling (if you've ever seen a 10 second delay to stop a container, this is often the cause) and with concatenating an entrypoint and command together. If you define your entrypoint as a string, it would run /bin/sh -c "file.sh", which alone is fine. But if you have a command defined as a string too, you'll see something like /bin/sh -c "file.sh" /bin/sh -c "arg1 arg2" as the command being launched inside your container, not so good. See the table here for more on how these two options interact

  4. The shell -c option only takes a single argument. Everything after that would get passed as $1, $2, etc, to that single argument, but not into an embedded shell script unless you explicitly passed the args. I.e. /bin/sh -c "file.sh $1 $2" "arg1" "arg2" would work, but /bin/sh -c "file.sh" "arg1" "arg2" would not since file.sh would be called with no args.

Putting that all together, the common design is:

FROM ubuntu:14.04
COPY ./file.sh /
RUN chmod 755 /file.sh
# Note the json syntax on this next line is strict, double quotes, and any syntax
# error will result in a shell being used to run the line.
ENTRYPOINT ["file.sh"]

And you then run that with:

docker run your_image arg1 arg2

There's a fair bit more detail on this at:

Retrofit 2.0 how to get deserialised error response.body

It's actually very straight forward.

Kotlin:

val jsonObj = JSONObject(response.errorBody()!!.charStream().readText())
responseInterface.onFailure(jsonObj.getString("msg"))

Java:

    if(response.errorBody()!=null){
    JSONObject jsonObj = new JSONObject(TextStreamsKt.readText(response.errorBody().charStream()));
        responseInterface.onFailure(jsonObj.getString("msg"));
    }else{
        responseInterface.onFailure("you might want to return a generic error message.");
    }

Tested on retrofit:2.5.0. Read the text from the charStream which will give you a String, then parse to JSONObject.

Adios.

Run Command Prompt Commands

if you want to run the command in async mode - and print the results. you can you this class:

    public static class ExecuteCmd
{
    /// <summary>
    /// Executes a shell command synchronously.
    /// </summary>
    /// <param name="command">string command</param>
    /// <returns>string, as output of the command.</returns>
    public static void ExecuteCommandSync(object command)
    {
        try
        {
            // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
            // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
            // The following commands are needed to redirect the standard output. 
            //This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo.RedirectStandardOutput =  true;
            procStartInfo.UseShellExecute = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            // Get the output into a string
            string result = proc.StandardOutput.ReadToEnd();

            // Display the command output.
            Console.WriteLine(result);
        }
        catch (Exception objException)
        {
            // Log the exception
            Console.WriteLine("ExecuteCommandSync failed" + objException.Message);
        }
    }

    /// <summary>
    /// Execute the command Asynchronously.
    /// </summary>
    /// <param name="command">string command.</param>
    public static void ExecuteCommandAsync(string command)
    {
        try
        {
            //Asynchronously start the Thread to process the Execute command request.
            Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
            //Make the thread as background thread.
            objThread.IsBackground = true;
            //Set the Priority of the thread.
            objThread.Priority = ThreadPriority.AboveNormal;
            //Start the thread.
            objThread.Start(command);
        }
        catch (ThreadStartException )
        {
            // Log the exception
        }
        catch (ThreadAbortException )
        {
            // Log the exception
        }
        catch (Exception )
        {
            // Log the exception
        }
    }

}

Jenkins Git Plugin: How to build specific tag?

None of these answers were sufficient for me, using Jenkins CI v.1.555, Git Client plugin v.1.6.4, and Git plugin 2.0.4.

I wanted a job to build for one Git repository for one specific, fixed (i.e., non-parameterized) tag. I had to cobble together a solution from the various answers plus the "build a Git tag" blog post cited by Thilo.

  1. Make sure you push your tag to the remote repository with git push --tags
  2. In the "Git Repository" section of your job, under the "Source Code Management" heading, click "Advanced".
  3. In the field for Refspec, add the following text: +refs/tags/*:refs/remotes/origin/tags/*
  4. Under "Branches to build", "Branch specifier", put */tags/<TAG_TO_BUILD> (replacing <TAG_TO_BUILD> with your actual tag name).

Adding the Refspec for me turned out to be critical. Although it seemed the git repositories were fetching all the remote information by default when I left it blank, the Git plugin would nevertheless completely fail to find my tag. Only when I explicitly specified "get the remote tags" in the Refspec field was the Git plugin able to identify and build from my tag.

Update 2014-5-7: Unfortunately, this solution does come with an undesirable side-effect for Jenkins CI (v.1.555) and the Git repository push notification mechanism à la Stash Webhook to Jenkins: any time any branch on the repository is updated in a push, the tag build jobs will also fire again. This leads to a lot of unnecessary re-builds of the same tag jobs over and over again. I have tried configuring the jobs both with and without the "Force polling using workspace" option, and it seemed to have no effect. The only way I could prevent Jenkins from making the unnecessary builds for the tag jobs is to clear the Refspec field (i.e., delete the +refs/tags/*:refs/remotes/origin/tags/*).

If anyone finds a more elegant solution, please edit this answer with an update. I suspect, for example, that maybe this wouldn't happen if the refspec specifically was +refs/tags/<TAG TO BUILD>:refs/remotes/origin/tags/<TAG TO BUILD> rather than the asterisk catch-all. For now, however, this solution is working for us, we just remove the extra Refspec after the job succeeds.

MySQL: NOT LIKE

categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'

Is it possible to change a UIButtons background color?

Another possibility:

  1. Create a UIButton in Interface builder.
  2. Give it a type 'Custom'
  3. Now, in IB it is possible to change the background color

However, the button is square, and that is not what we want. Create an IBOutlet with a reference to this button and add the following to the viewDidLoad method:

[buttonOutlet.layer setCornerRadius:7.0f];
[buttonOutlet.layer setClipToBounds:YES];

Don't forget to import QuartzCore.h