Programs & Examples On #Macruby

MacRuby is an implementation of the Ruby 1.9 programming language in ObjC for Mac OSX

Laravel 5 route not defined, while it is?

One more cause for this:

If the routes are overridden with the same URI (Unknowingly), it causes this error:

Eg:

Route::get('dashboard', ['uses' => 'SomeController@index', 'as' => 'my.dashboard']);
Route::get('dashboard/', ['uses' => 'SomeController@dashboard', 'as' => 'my.home_dashboard']);

In this case route 'my.dashboard' is invalidate as the both routes has same URI ('dashboard', 'dashboard/')

Solution: You should change the URI for either one

Eg:

Route::get('dashboard', ['uses' => 'SomeController@index', 'as' => 'my.dashboard']);
Route::get('home-dashboard', ['uses' => 'SomeController@dashboard', 'as' => 'my.home_dashboard']); 

// See the URI changed for this 'home-dashboard'

Hope it helps some once.

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

You need some Administrator privilege to your account if your machine in local area network then you apply some administrator privilege to your User else you should start ide as Administrator...

How can I make a TextBox be a "password box" and display stars when using MVVM?

As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" />

Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf" link: https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf Then copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.

After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" > 
    <TextBox.InputBindings>
        <!--Disable CTRL+C -->
        <KeyBinding Command="ApplicationCommands.NotACommand"
            Key="C"
            Modifiers="Control" />
    </TextBox.InputBindings>
</TextBox>

How do I measure time elapsed in Java?

Java provides the static method System.currentTimeMillis(). And that's returning a long value, so it's a good reference. A lot of other classes accept a 'timeInMillis' parameter which is long as well.

And a lot of people find it easier to use the Joda Time library to do calculations on dates and times.

Getting Integer value from a String using javascript/jquery

For parseInt to work, your string should have only numerical data. Something like this:

 str1 = "123.00";
 str2 = "50.00";
 total = parseInt(str1)+parseInt(str2);
 alert(total);

Can you split the string before you start processing them for a total?

How to handle login pop up window using Selenium WebDriver?

I was getting windows security alert whenever my application was opening. to resolve this issue i used following procedure

import org.openqa.selenium.security.UserAndPassword;
UserAndPassword UP = new UserAndPassword("userName","Password");
driver.switchTo().alert().authenticateUsing(UP);

this resolved my issue of logging into application. I hope this might help who are all looking for authenticating windows security alert.

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

What is the best way to conditionally apply attributes in AngularJS?

Regarding the accepted solution, the one posted by Ashley Davis, the method described still prints the attribute in the DOM, regardless of the fact that the value it has been assigned is undefined.

For example, on an input field setup with both an ng-model and a value attribute:

<input type="text" name="myInput" data-ng-attr-value="{{myValue}}" data-ng-model="myModel" />

Regardless of what's behind myValue, the value attribute still gets printed in the DOM, thus, interpreted. Ng-model then, becomes overridden.

A bit unpleasant, but using ng-if does the trick:

<input type="text" name="myInput" data-ng-if="value" data-ng-attr-value="{{myValue}}" data-ng-model="myModel" />
<input type="text" name="myInput" data-ng-if="!value" data-ng-model="myModel" />

I would recommend using a more detailed check inside the ng-if directives :)

Sending JWT token in the headers with Postman

I did as how moplin mentioned .But in my case service send the JWT in response headers ,as a value under the key "Authorization".

Authorization ?Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpbWFsIiwiZXhwIjoxNDk4OTIwOTEyfQ.dYEbf4x5TGr_kTtwywKPI2S-xYhsp5RIIBdOa_wl9soqaFkUUKfy73kaMAv_c-6cxTAqBwtskOfr-Gm3QI0gpQ

What I did was ,make a Global variable in postman as

key->jwt
value->blahblah

in login request->Tests Tab, add

postman.clearGlobalVariable("jwt");
postman.setGlobalVariable("jwt", postman.getResponseHeader("Authorization"));

in other requests select the Headers tab and give

key->Authorization

value->{{jwt}}

Moment js get first and last day of current month

There would be another way to do this:

var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

How do you launch the JavaScript debugger in Google Chrome?

For Mac users, go to Google Chrome --> menu View --> Developer --> JavaScript Console.

Screenshot

Undo git pull, how to bring repos to old state

it works first use: git reflog

find your SHA of your previus state and make (HEAD@{1} is an example)

git reset --hard HEAD@{1}

ios Upload Image and Text using HTTP POST

Here's code from my app to post an image to our web server:

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]];
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]];
[_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]];
[_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
NSString* FileParamConstant = [NSString stringWithString:@"file"];

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@""]; 

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];                                    
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long) [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];

How do I insert non breaking space character &nbsp; in a JSF page?

The easiest way is:

<h:outputText value=" " />

Error including image in Latex

I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:

\includegraphics[height=60mm, width=100mm]{number2.png}

works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.

Incidentally, you can change this in TexShop from the "Typeset" menu.

Hope this helps.

Check if process returns 0 with batch file

To check whether a process/command returned 0 or not, use the operators && == 0 or not == 0 ||:

Just add operator to your script:

execute_command && (

       echo\Return 0, with no execution error
) || (
        echo\Return non 0, something went wrong
     )

command && echo\Return 0 || echo\Return non 0

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)

How to define custom configuration variables in rails

If you use Heroku or otherwise have need to keep your application settings as environment variables, the figaro gem is very helpful.

How can I get a uitableViewCell by indexPath?

[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]

will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)

ADD: Here is an alternate syntax that achieves the same thing without the cast.

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];

Regex match digits, comma and semicolon?

word.matches("^[0-9,;]+$"); you were almost there

Setting active profile and config location from command line in spring boot

If you use Gradle:

-Pspring.profiles.active=local

Git add and commit in one command

  1. type git add . && git commit -am and enter
  2. type historyand enter
  3. remember the number for the above command, say the number is 543
  4. From now on, for every commit type !543 "your comment here" i.e. exclamatory mark+number and a space and your comment.

Vuex - Computed property "name" was assigned to but it has no setter

If you're going to v-model a computed, it needs a setter. Whatever you want it to do with the updated value (probably write it to the $store, considering that's what your getter pulls it from) you do in the setter.

If writing it back to the store happens via form submission, you don't want to v-model, you just want to set :value.

If you want to have an intermediate state, where it's saved somewhere but doesn't overwrite the source in the $store until form submission, you'll need to create such a data item.

invalid use of incomplete type

The reason is that when instantiating a class template, all its declarations (not the definitions) of its member functions are instantiated too. The class template is instantiated precisely when the full definition of a specialization is required. That is the case when it is used as a base class for example, as in your case.

So what happens is that A<B> is instantiated at

class B : public A<B>

at which point B is not a complete type yet (it is after the closing brace of the class definition). However, A<B>::action's declaration requires B to be complete, because it is crawling in the scope of it:

Subclass::mytype

What you need to do is delaying the instantiation to some point at which B is complete. One way of doing this is to modify the declaration of action to make it a member template.

template<typename T>
void action(T var) {
    (static_cast<Subclass*>(this))->do_action(var);
}

It is still type-safe because if var is not of the right type, passing var to do_action will fail.

Saving excel worksheet to CSV files with filename+worksheet name using VB

Best way to find out is to record the macro and perform the exact steps and see what VBA code it generates. you can then go and replace the bits you want to make generic (i.e. file names and stuff)

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

How can I create a self-signed cert for localhost?

You can use PowerShell to generate a self-signed certificate with the new-selfsignedcertificate cmdlet:

New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My"

Note: makecert.exe is deprecated.

Cmdlet Reference: https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate

Change the maximum upload file size

the answers are a bit incomplete, 3 things you have to do

in php.ini of your php installation (note: depending if you want it for CLI, apache, or nginx, find the right php.ini to manipulate. For nginx it is usually located in /etc/php/7.1/fpm where 7.1 depends on your version. For apache usually /etc/php/7.1/apache2)

post_max_size=500M

upload_max_filesize=500M

memory_limit=900M

or set other values. Restart/reload apache if you have apache installed or php-fpm for nginx if you use nginx.

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

Extract a part of the filepath (a directory) in Python

You have to put the entire path as a parameter to os.path.split. See The docs. It doesn't work like string split.

How to acces external json file objects in vue.js app

Just assign the import to a data property

<script>
      import json from './json/data.json'
      export default{
          data(){
              return{
                  myJson: json
              }
          }
      }
</script>

then loop through the myJson property in your template using v-for

<template>
    <div>
        <div v-for="data in myJson">{{data}}</div>
    </div>
</template>

NOTE

If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.

Vue converts all the properties in the data option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.

So you can create a custom option as follows:

<script>
          import MY_JSON from './json/data.json'
          export default{
              //custom option named myJson
                 myJson: MY_JSON
          }
    </script>

then loop through the custom option in your template using $options:

<template>
        <div>
            <div v-for="data in $options.myJson">{{data}}</div>
        </div>
    </template>

node.js require all files in a folder?

I recommend using glob to accomplish that task.

var glob = require( 'glob' )
  , path = require( 'path' );

glob.sync( './routes/**/*.js' ).forEach( function( file ) {
  require( path.resolve( file ) );
});

Developing C# on Linux

You can also install it using conda (tested on Ubuntu):

conda create --name csharp
conda activate csharp
conda install -c conda-forge mono

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

I had this same problem, however mine was because I hadn't set the Server authentication to "SQL Server and Windows Authentication mode" (which you had) I just wanted to mention it here in case someone missed it in your question.

You can access this by

  • Right click on instance (IE SQLServer2008)
  • Select "Properties"
  • Select "Security" option
  • Change "Server authentication" to "SQL Server and Windows Authentication mode"
  • Restart the SQLServer service
    • Right click on instance
    • Click "Restart"

td widths, not working?

 <table style="table-layout:fixed;">

This will force the styled width <td>. If the text overfills it, it will overlap the other <td> text. So try using media queries.

Angular2 set value for formGroup

For set value when your control is FormGroup can use this example

this.clientForm.controls['location'].setValue({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude
    });

Android: Flush DNS

copied from: https://android.stackexchange.com/questions/12962/flush-clear-dns-cache

Addresses are cached for 600 seconds (10 minutes) by default. Failed lookups are cached for 10 seconds. From everything I've seen, there's nothing built in to flush the cache. This is apparently a reported bug http://code.google.com/p/android/issues/detail?id=7904 in Android because of the way it stores DNS cache. Clearing the browser cache doesn't touch the DNS, the "hard reset" clears it.

How can I install a previous version of Python 3 in macOS using homebrew?

I have tried everything but could not make it work. Finally I have used pyenv and it worked directly like a charm.

So having homebrew installed, juste do:

brew install pyenv
pyenv install 3.6.5

to manage virtualenvs:

brew install pyenv-virtualenv
pyenv virtualenv 3.6.5 env_name

See pyenv and pyenv-virtualenv for more info.

EDIT (2019/03/19)

I have found using the pyenv-installer easier than homebrew to install pyenv and pyenv-virtualenv direclty:

curl https://pyenv.run | bash

To manage python version, either globally:

pyenv global 3.6.5

or locally in a given directory:

pyenv local 3.6.5

How do I grep for all non-ASCII characters?

The following works for me:

grep -P "[\x80-\xFF]" file.xml

Non-ASCII characters start at 0x80 and go to 0xFF when looking at bytes. Grep (and family) don't do Unicode processing to merge multi-byte characters into a single entity for regex matching as you seem to want. The -P option in my grep allows the use of \xdd escapes in character classes to accomplish what you want.

RegExp in TypeScript

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

How to break lines in PowerShell?

If you are using just code like this below, you must put just a grave accent at the end of line `.

docker run -d --name rabbitmq `
           -p 5672:5672 `
           -p 15672:15672 `
           --restart=always `
           --hostname rabbitmq-master `
           -v c:\docker\rabbitmq\data:/var/lib/rabbitmq `
           rabbitmq:latest

Show/hide widgets in Flutter programmatically

Maybe you can use the Navigator function like this Navigator.of(context).pop();

Convert command line arguments into an array in Bash

Actually your command line arguments are practically like an array already. At least, you can treat the $@ variable much like an array. That said, you can convert it into an actual array like this:

myArray=( "$@" )

If you just want to type some arguments and feed them into the $@ value, use set:

$ set -- apple banana "kiwi fruit"
$ echo "$#"
3
$ echo "$@"
apple banana kiwi fruit

Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array.

Calling a JavaScript function returned from an Ajax response

If your AJAX script takes more than a couple milliseconds to run, eval() will always run ahead and evaluate the empty response element before AJAX populates it with the script you're trying to execute.

Rather than mucking around with timing and eval(), here is a pretty simple workaround that should work in most situations and is probably a bit more secure. Using eval() is generally frowned upon because the characters being evaluated as code can easily be manipulated client-side.

Concept

  1. Include your javascript function in the main page. Write it so that any dynamic elements can be accepted as arguments.
  2. In your AJAX file, call the function by using an official DOM event (onclick, onfocus, onblur, onload, etc.) Depending on what other elements are in your response, you can get pretty clever about making it feel seamless. Pass your dynamic elements in as arguments.
  3. When your response element gets populated and the event takes place, the function runs.

Example

In this example, I want to attach a dynamic autocomplete list from the jquery-ui library to an AJAX element AFTER the element has been added to the page. Easy, right?

start.php

<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<!-- these libraries are for the autocomplete() function -->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-lightness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
<!--
// this is the ajax call
function editDemoText(ElementID,initialValue) {
    try { ajaxRequest = new XMLHttpRequest();
    } catch (e) {
    try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
    return false;
    }}}
    ajaxRequest.onreadystatechange = function() {
        if ( ajaxRequest.readyState == 4 ) {
            var ajaxDisplay = document.getElementById('responseDiv');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }
    var queryString = "?ElementID="+ElementID+"&initialValue="+initialValue;
    ajaxRequest.open("GET", "ajaxRequest.php"+queryString, true);
    ajaxRequest.send(null);
    }

// this is the function we wanted to call in AJAX, 
// but we put it here instead with an argument (ElementID)
function AttachAutocomplete(ElementID) {
    // this list is static, but can easily be pulled in from 
    // a database using PHP. That would look something like this:
    /*
     * $list = "";
     * $r = mysqli_query($mysqli_link, "SELECT element FROM table");
     * while ( $row = mysqli_fetch_array($r) ) {
     *    $list .= "\".str_replace('"','\"',$row['element'])."\",";
     *    }
     * $list = rtrim($list,",");
     */
    var availableIDs = ["Demo1","Demo2","Demo3","Demo4"];
    $("#"+ElementID).autocomplete({ source: availableIDs });
    }
//-->
</script>
</head>
<body>
<!-- this is where the AJAX response sneaks in after DOM is loaded -->
<!-- we're using an onclick event to trigger the initial AJAX call -->
<div id="responseDiv"><a href="javascript:void(0);" onclick="editDemoText('EditableText','I am editable!');">I am editable!</a></div>
</body>
</html>

ajaxRequest.php

<?php
// for this application, onfocus works well because we wouldn't really 
// need the autocomplete populated until the user begins typing
echo "<input type=\"text\" id=\"".$_GET['ElementID']."\" onfocus=\"AttachAutocomplete('".$_GET['ElementID']."');\" value=\"".$_GET['initialValue']."\" />\n";
?>

Set transparent background of an imageview on Android

You could also use View.setAlpha(float) to change the visibility precisely.

0 would be transparent, 1 fully visible. ;)

Why is my Spring @Autowired field null?

Another solution would be putting call: SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
To MileageFeeCalculator constructor like this:

@Service
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService; // <--- will be autowired when constructor is called

    public MileageFeeCalculator() {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
    }

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile()); 
    }
}

Git Ignores and Maven targets

As already pointed out in comments by Abhijeet you can just add line like:

/target/**

to exclude file in \.git\info\ folder.

Then if you want to get rid of that target folder in your remote repo you will need to first manually delete this folder from your local repository, commit and then push it. Thats because git will show you content of a target folder as modified at first.

Java JTable setting Column Width

What happens if you call setMinWidth(400) on the last column instead of setPreferredWidth(400)?

In the JavaDoc for JTable, read the docs for doLayout() very carefully. Here are some choice bits:

When the method is called as a result of the resizing of an enclosing window, the resizingColumn is null. This means that resizing has taken place "outside" the JTable and the change - or "delta" - should be distributed to all of the columns regardless of this JTable's automatic resize mode.

This might be why AUTO_RESIZE_LAST_COLUMN didn't help you.

Note: When a JTable makes adjustments to the widths of the columns it respects their minimum and maximum values absolutely.

This says that you might want to set Min == Max for all but the last columns, then set Min = Preferred on the last column and either not set Max or set a very large value for Max.

Default value of 'boolean' and 'Boolean' in Java

The default value for a Boolean (object) is null.
The default value for a boolean (primitive) is false.

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

its because of Headerfiles define what the class contains (Members, data-structures) and cpp files implement it.

And of course, the main reason for this is that you could include one .h File multiple times in other .h files, but this would result in multiple definitions of a class, which is invalid.

Git Push ERROR: Repository not found

If you belong to a group in Github check that you have Write Access.

How to grab substring before a specified character jQuery or JavaScript

If you like it short simply use a RegExp:

var streetAddress = /[^,]*/.exec(addy)[0];

How can I change image tintColor in iOS and WatchKit

profileImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
profileImageView.tintColor = UIColor.green

OR

First select Particular image in image asset and then select reddened as Template instead of Default and after that write line. profileImageView.tintColor = UIColor.green

Jquery If radio button is checked

This will listen to the changed event. I have tried the answers from others but those did not work for me and finally, this one worked.

$('input:radio[name="postage"]').change(function(){
    if($(this).is(":checked")){
        alert("lksdahflk");
    }
});

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I've made a short code to do that and I want to share it with you.

Here the main code:

public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{

  MailMessage email = new MailMessage();
  email.From = new MailAddress(from);
  email.To.Add(to);
  email.Subject = subject;
  email.Body = Message;
  SmtpClient smtp = new SmtpClient(host, port);
  smtp.UseDefaultCredentials = false;
  NetworkCredential nc = new NetworkCredential(from, password);
  smtp.Credentials = nc;
  smtp.EnableSsl = true;
  email.IsBodyHtml = true;
  email.Priority = MailPriority.Normal;
  email.BodyEncoding = Encoding.UTF8;

  if (file.Length > 0)
  {
    Attachment attachment;
    attachment = new Attachment(file);
    email.Attachments.Add(attachment);
  }

  // smtp.Send(email);
  smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
  string userstate = "sending ...";
  smtp.SendAsync(email, userstate);
}

private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
  string result = "";
  if (e.Cancelled)
  {    
    MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
  }
  else if (e.Error != null)
  {
    MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }
  else {
    MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }

}

In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example

using (OpenFileDialog attachement = new OpenFileDialog()
{
  Filter = "Exel Client|*.png",
  ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
  Send("[email protected]", "gmail_password", 
       "[email protected]", "just smile ", "mail with attachement",
       "smtp.gmail.com", 587, attachement.FileName);

}
}

How to set a default value in react-select

I was having a similar error. Make sure your options have a value attribute.

<option key={index} value={item}> {item} </option>

Then match the selects element value initially to the options value.

<select 
    value={this.value} />

sql server #region

I've used a technique similar to McVitie's, and only in stored procedures or scripts that are pretty long. I will break down certain functional portions like this:

BEGIN /** delete queries **/

DELETE FROM blah_blah

END /** delete queries **/

BEGIN /** update queries **/

UPDATE sometable SET something = 1

END /** update queries **/

This method shows up fairly nice in management studio and is really helpful in reviewing code. The collapsed piece looks sort of like:

BEGIN /** delete queries **/ ... /** delete queries **/

I actually prefer it this way because I know that my BEGIN matches with the END this way.

phpMyAdmin allow remote users

Replace the contents of the first <directory> tag.

Remove:

<Directory /usr/share/phpMyAdmin/>
 <IfModule mod_authz_core.c>
  # Apache 2.4
  <RequireAny>
    Require ip 127.0.0.1
    Require ip ::1
  </RequireAny>
 </IfModule>
 <IfModule !mod_authz_core.c>
  # Apache 2.2
  Order Deny,Allow
  Deny from All
  Allow from 127.0.0.1
  Allow from ::1
 </IfModule>
</Directory>

And place this instead:

<Directory /usr/share/phpMyAdmin/>
 Order allow,deny
 Allow from all
</Directory>

Don't forget to restart Apache afterwards.

Easily measure elapsed time

They are they same because your doSomething function happens faster than the granularity of the timer. Try:

printf ("**MyProgram::before time= %ld\n", time(NULL));

for(i = 0; i < 1000; ++i) {
    doSomthing();
    doSomthingLong();
}

printf ("**MyProgram::after time= %ld\n", time(NULL));

How do I add a ToolTip to a control?

Here is your article for doing it with code

private void Form1_Load(object sender, System.EventArgs e)
{
     // Create the ToolTip and associate with the Form container.
     ToolTip toolTip1 = new ToolTip();

     // Set up the delays for the ToolTip.
     toolTip1.AutoPopDelay = 5000;
     toolTip1.InitialDelay = 1000;
     toolTip1.ReshowDelay = 500;
     // Force the ToolTip text to be displayed whether or not the form is active.
     toolTip1.ShowAlways = true;

     // Set up the ToolTip text for the Button and Checkbox.
     toolTip1.SetToolTip(this.button1, "My button1");
     toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}

How do I address unchecked cast warnings?

In Android Studio if you want to disable inspection you can use:

//noinspection unchecked
Map<String, String> myMap = (Map<String, String>) deserializeMap();

Format XML string to print friendly XML string

The simple solution that is working for me:

        XmlDocument xmlDoc = new XmlDocument();
        StringWriter sw = new StringWriter();
        xmlDoc.LoadXml(rawStringXML);
        xmlDoc.Save(sw);
        String formattedXml = sw.ToString();

How do I convert a dictionary to a JSON String in C#?

Here's how to do it using only standard .Net libraries from Microsoft …

using System.IO;
using System.Runtime.Serialization.Json;

private static string DataToJson<T>(T data)
{
    MemoryStream stream = new MemoryStream();

    DataContractJsonSerializer serialiser = new DataContractJsonSerializer(
        data.GetType(),
        new DataContractJsonSerializerSettings()
        {
            UseSimpleDictionaryFormat = true
        });

    serialiser.WriteObject(stream, data);

    return Encoding.UTF8.GetString(stream.ToArray());
}

TypeError: can't use a string pattern on a bytes-like object in re.findall()

The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

See the urlopen documentation for more details.

Facebook Javascript SDK Problem: "FB is not defined"

Facebook prefers that you load their SDK asynchronously so that it doesn't block any other scripts that you need for your page but due to the iframe there's a chance that the console tries to call a method on the FB object before the FB object is completely created even though FB is only called in the fbAsyncInit function.
Try loading the javascript synchronously and you shouldn't get the error anymore. To do this you can copy and paste the code that Facebook provides and place it in an external .js file and then include that .js file in a <script> tag in the <head> of your page. If you must load their SDK asynchronously then check for FB to be created first before calling the init function.

How to add parameters to a HTTP GET request in Android?

The method

setParams() 

like

httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));

only adds HttpProtocol parameters.

To execute the httpGet you should append your parameters to the url manually

HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar");

or use the post request the difference between get and post requests are explained here, if you are interested

Remove specific characters from a string in Python

I was surprised that no one had yet recommended using the builtin filter function.

    import operator
    import string # only for the example you could use a custom string

    s = "1212edjaq"

Say we want to filter out everything that isn't a number. Using the filter builtin method "...is equivalent to the generator expression (item for item in iterable if function(item))" [Python 3 Builtins: Filter]

    sList = list(s)
    intsList = list(string.digits)
    obj = filter(lambda x: operator.contains(intsList, x), sList)))

In Python 3 this returns

    >>  <filter object @ hex>

To get a printed string,

    nums = "".join(list(obj))
    print(nums)
    >> "1212"

I am not sure how filter ranks in terms of efficiency but it is a good thing to know how to use when doing list comprehensions and such.

UPDATE

Logically, since filter works you could also use list comprehension and from what I have read it is supposed to be more efficient because lambdas are the wall street hedge fund managers of the programming function world. Another plus is that it is a one-liner that doesnt require any imports. For example, using the same string 's' defined above,

      num = "".join([i for i in s if i.isdigit()])

That's it. The return will be a string of all the characters that are digits in the original string.

If you have a specific list of acceptable/unacceptable characters you need only adjust the 'if' part of the list comprehension.

      target_chars = "".join([i for i in s if i in some_list]) 

or alternatively,

      target_chars = "".join([i for i in s if i not in some_list])

How to replace a character by a newline in Vim

Here's the answer that worked for me. From this guy:

----quoting Use the vi editor to insert a newline char in replace


Something else I have to do and cannot remember and then have to look up.

In vi, to insert a newline character in a search and replace, do the following:

:%s/look_for/replace_with^M/g

The command above would replace all instances of “look_for” with “replace_with\n” (with \n meaning newline).

To get the “^M”, enter the key combination Ctrl + V, and then after that (release all keys) press the Enter key.


"405 method not allowed" in IIS7.5 for "PUT" method

Taken from here and it worked for me :

1.Go to IIS Manager.

2.Click on your app.

3.Go to "Handler Mappings".

4.In the feature list, double click on "WebDAV".

5.Click on "Request Restrictions".

6.In the tab "Verbs" select "All verbs" .

7.Press OK.

How to make android listview scrollable?

Practically its not good to do. But if you want to do like this, just make listview's height fixed to wrap_content.

android:layout_height="wrap_content"

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

How to install php-curl in Ubuntu 16.04

To Install cURL 7.49.0 on Ubuntu 16.04 and Derivatives

wget http://curl.haxx.se/download/curl-7.49.0.tar.gz
tar -xvf curl-7.49.0.tar.gz
cd curl-7.49.0/
./configure
make
sudo make install

Way to ng-repeat defined number of times instead of repeating over array?

I wanted to keep my html very minimal, so defined a small filter that creates the array [0,1,2,...] as others have done:

angular.module('awesomeApp')
  .filter('range', function(){
    return function(n) {
      var res = [];
      for (var i = 0; i < n; i++) {
        res.push(i);
      }
      return res;
    };
  });

After that, on the view is possible to use like this:

<ul>
  <li ng-repeat="i in 5 | range">
    {{i+1}} <!-- the array will range from 0 to 4 -->
  </li>
</ul>

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

For me it was picking the default JVM v6 set in env vars.

Needed to explicitly add below in eclipse.ini to use v8 which is req by photon.

-vm
C:\Program Files\Java\jdk1.8.0_75\bin\javaw.exe
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8

NOTE : Add the entry of vm above the vm args else it will not work!

How to iterate object keys using *ngFor

1.Create a custom pipe to get keys.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'keys'
})
export class KeysPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return Object.keys(value);
  }
}
  1. In angular template file, you can use *ngFor and iterate over your object object
<div class ="test" *ngFor="let key of Obj | keys">
    {{key}}
    {{Obj[key].property}
<div>

How to detect my browser version and operating system using JavaScript?

PPK's script is THE authority for this kind of things, as @Jalpesh said, this might point you in the right way

var wn = window.navigator,
        platform = wn.platform.toString().toLowerCase(),
        userAgent = wn.userAgent.toLowerCase(),
        storedName;

// ie
    if (userAgent.indexOf('msie',0) !== -1) {
        browserName = 'ie';
        os = 'win';
        storedName = userAgent.match(/msie[ ]\d{1}/).toString();
        version = storedName.replace(/msie[ ]/,'');

        browserOsVersion = browserName + version;
    }

Taken from https://github.com/leopic/jquery.detectBrowser.js/blob/sans-jquery/jquery.detectBrowser.sansjQuery.js

How to close form

You can also close the application:

Application.Exit();

It will end the processes.

How to pass object with NSNotificationCenter

Swift 5.1 Custom Object/Type

// MARK: - NotificationName
// Extending notification name to avoid string errors.
extension Notification.Name {
    static let yourNotificationName = Notification.Name("yourNotificationName")
}


// MARK: - CustomObject
class YourCustomObject {
    // Any stuffs you would like to set in your custom object as always.
    init() {}
}

// MARK: - Notification Sender Class
class NotificatioSenderClass {

     // Just grab the content of this function and put it to your function responsible for triggering a notification.
    func postNotification(){
        // Note: - This is the important part pass your object instance as object parameter.
        let yourObjectInstance = YourCustomObject()
        NotificationCenter.default.post(name: .yourNotificationName, object: yourObjectInstance)
    }
}

// MARK: -Notification  Receiver class
class NotificationReceiverClass: UIViewController {
    // MARK: - ViewController Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        // Register your notification listener
        NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotificationWithCustomObject), name: .yourNotificationName, object: nil)
    }

    // MARK: - Helpers
    @objc private func didReceiveNotificationWithCustomObject(notification: Notification){
        // Important: - Grab your custom object here by casting the notification object.
        guard let yourPassedObject = notification.object as? YourCustomObject else {return}
        // That's it now you can use your custom object
        //
        //

    }
      // MARK: - Deinit
  deinit {
      // Save your memory by releasing notification listener
      NotificationCenter.default.removeObserver(self, name: .yourNotificationName, object: nil)
    }




}

How to exit a 'git status' list in a terminal?

My preferred combo is Gq, which prints all diffs and then exits.

You can type h to show the help commands for interacting with less, which prints this to console:

                   SUMMARY OF LESS COMMANDS

      Commands marked with * may be preceded by a number, N.
      Notes in parentheses indicate the behavior if N is given.

  h  H                 Display this help.
  q  :q  Q  :Q  ZZ     Exit.
 ---------------------------------------------------------------------------

                           MOVING

  e  ^E  j  ^N  CR  *  Forward  one line   (or N lines).
  y  ^Y  k  ^K  ^P  *  Backward one line   (or N lines).
  f  ^F  ^V  SPACE  *  Forward  one window (or N lines).
  b  ^B  ESC-v      *  Backward one window (or N lines).
  z                 *  Forward  one window (and set window to N).
  w                 *  Backward one window (and set window to N).
  ESC-SPACE         *  Forward  one window, but don't stop at end-of-file.
  d  ^D             *  Forward  one half-window (and set half-window to N).
  u  ^U             *  Backward one half-window (and set half-window to N).
  ESC-)  RightArrow *  Left  one half screen width (or N positions).
  ESC-(  LeftArrow  *  Right one half screen width (or N positions).
  F                    Forward forever; like "tail -f".
  r  ^R  ^L            Repaint screen.
  R                    Repaint screen, discarding buffered input.
        ---------------------------------------------------
        Default "window" is the screen height.
        Default "half-window" is half of the screen height.
 ---------------------------------------------------------------------------

                          SEARCHING

  /pattern          *  Search forward for (N-th) matching line.
  ?pattern          *  Search backward for (N-th) matching line.
  n                 *  Repeat previous search (for N-th occurrence).
  N                 *  Repeat previous search in reverse direction.
  ESC-n             *  Repeat previous search, spanning files.
  ESC-N             *  Repeat previous search, reverse dir. & spanning files.
  ESC-u                Undo (toggle) search highlighting.
        ---------------------------------------------------
        Search patterns may be modified by one or more of:
        ^N or !  Search for NON-matching lines.
        ^E or *  Search multiple files (pass thru END OF FILE).
        ^F or @  Start search at FIRST file (for /) or last file (for ?).
        ^K       Highlight matches, but don't move (KEEP position).
        ^R       Don't use REGULAR EXPRESSIONS.
 ---------------------------------------------------------------------------

                           JUMPING

  g  <  ESC-<       *  Go to first line in file (or line N).
  G  >  ESC->       *  Go to last line in file (or line N).
  p  %              *  Go to beginning of file (or N percent into file).
  t                 *  Go to the (N-th) next tag.
  T                 *  Go to the (N-th) previous tag.
  {  (  [           *  Find close bracket } ) ].
  }  )  ]           *  Find open bracket { ( [.
  ESC-^F <c1> <c2>  *  Find close bracket <c2>.
  ESC-^B <c1> <c2>  *  Find open bracket <c1> 
        ---------------------------------------------------

How do I get the object if it exists, or None if it does not exist?

To make things easier, here is a snippet of the code I wrote, based on inputs from the wonderful replies here:

class MyManager(models.Manager):

    def get_or_none(self, **kwargs):
        try:
            return self.get(**kwargs)
        except ObjectDoesNotExist:
            return None

And then in your model:

class MyModel(models.Model):
    objects = MyManager()

That's it. Now you have MyModel.objects.get() as well as MyModel.objetcs.get_or_none()

Python reshape list to ndim array

Step by step:

# import numpy library
import numpy as np
# create list
my_list = [0,0,1,1,2,2,3,3]
# convert list to numpy array
np_array=np.asarray(my_list)
# reshape array into 4 rows x 2 columns, and transpose the result
reshaped_array = np_array.reshape(4, 2).T 

#check the result
reshaped_array
array([[0, 1, 2, 3],
       [0, 1, 2, 3]])

Django templates: If false?

Just ran into this again (certain I had before and came up with a less-than-satisfying solution).

For a tri-state boolean semantic (for example, using models.NullBooleanField), this works well:

{% if test.passed|lower == 'false' %} ... {% endif %}

Or if you prefer getting excited over the whole thing...

{% if test.passed|upper == 'FALSE' %} ... {% endif %}

Either way, this handles the special condition where you don't care about the None (evaluating to False in the if block) or True case.

AngularJS : Why ng-bind is better than {{}} in angular?

ng-bind is better than {{...}}

For example, you could do:

<div>
  Hello, {{variable}}
</div>

This means that the whole text Hello, {{variable}} enclosed by <div> will be copied and stored in memory.

If instead you do something like this:

<div>
  Hello, <span ng-bind="variable"></span>
</div>

Only the value of the value will be stored in memory, and angular will register a watcher (watch expression) which consists of the variable only.

Stack smashing detected

Stack corruptions ususally caused by buffer overflows. You can defend against them by programming defensively.

Whenever you access an array, put an assert before it to ensure the access is not out of bounds. For example:

assert(i + 1 < N);
assert(i < N);
a[i + 1] = a[i];

This makes you think about array bounds and also makes you think about adding tests to trigger them if possible. If some of these asserts can fail during normal use turn them into a regular if.

Get login username in java

System.getProperty("user.name") is not a good security option since that environment variable could be faked: C:\ set USERNAME="Joe Doe" java ... // will give you System.getProperty("user.name") You ought to do:

com.sun.security.auth.module.NTSystem NTSystem = new com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());

JDK 1.5 and greater.

I use it within an applet, and it has to be signed. info source

How to do one-liner if else statement?

A very similar construction is available in the language

**if <statement>; <evaluation> {
   [statements ...]
} else {
   [statements ...]
}*

*

i.e.

if path,err := os.Executable(); err != nil {
   log.Println(err)
} else {
   log.Println(path)
}

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

How to store Node.js deployment settings/configuration files?

My solution is fairly simple:

Load the environment config in ./config/index.js

var env = process.env.NODE_ENV || 'development'
  , cfg = require('./config.'+env);

module.exports = cfg;

Define some defaults in ./config/config.global.js

var config = module.exports = {};

config.env = 'development';
config.hostname = 'dev.example.com';

//mongo database
config.mongo = {};
config.mongo.uri = process.env.MONGO_URI || 'localhost';
config.mongo.db = 'example_dev';

Override the defaults in ./config/config.test.js

var config = require('./config.global');

config.env = 'test';
config.hostname = 'test.example';
config.mongo.db = 'example_test';

module.exports = config;

Using it in ./models/user.js:

var mongoose = require('mongoose')
, cfg = require('../config')
, db = mongoose.createConnection(cfg.mongo.uri, cfg.mongo.db);

Running your app in test environment:

NODE_ENV=test node ./app.js

urlencode vs rawurlencode?

One practical reason to choose one over the other is if you're going to use the result in another environment, for example JavaScript.

In PHP urlencode('test 1') returns 'test+1' while rawurlencode('test 1') returns 'test%201' as result.

But if you need to "decode" this in JavaScript using decodeURI() function then decodeURI("test+1") will give you "test+1" while decodeURI("test%201") will give you "test 1" as result.

In other words the space (" ") encoded by urlencode to plus ("+") in PHP will not be properly decoded by decodeURI in JavaScript.

In such cases the rawurlencode PHP function should be used.

python modify item in list, save back in list

You need to use the enumerate function: python docs

for place, item in enumerate(list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.

Since you had problems with enumerate, an alternative from the itertools library:

for place, item in itertools.zip(itertools.count(0), list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

There's a lot of information already answered, will just post my own findings that i've been using whenever i need to output the sql query before it's being executed.

Consider below sample:

$user = DB::table('user')->where('id',1);
echo $user->toSql();

echo $user->toSql() = This will just out put the raw query but will not show the parameter(s) passed.

To output the query with the parameter being passed we can use laravel getBindings() and helper str_replace_array like this:

$queryWithParam = str_replace_array('?',$user->getBindings(),$user->toSql());
echo $queryWithParam;

Hope this also helps.

How to make PDF file downloadable in HTML link?

Here's a different approach. I prefer rather than to rely on browser support, or address this at the application layer, to use web server logic.

If you are using Apache, and can put an .htaccess file in the relevant directory you could use the code below. Of course, you could put this in httpd.conf as well, if you have access to that.

<FilesMatch "\.(?i:pdf)$">
  Header set Content-Disposition attachment
</FilesMatch>

The FilesMatch directive is just a regex so it could be set as granularly as you want, or you could add in other extensions.

The Header line does the same thing as the first line in the PHP scripts above. If you need to set the Content-Type lines as well, you could do so in the same manner, but I haven't found that necessary.

How to toggle font awesome icon on click?

There is another solution you can try by using only the css here is the answer i posted in another post: jQuery Accordion change font awesome icon class on click

c# regex matches example

All the other responses I see are fine, but C# has support for named groups!

I'd use the following code:

const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";

static void Main(string[] args)
{
    Regex expression = new Regex(@"%download%#(?<Identifier>[0-9]*)");
    var results = expression.Matches(input);
    foreach (Match match in results)
    {
        Console.WriteLine(match.Groups["Identifier"].Value);
    }
}

The code that reads: (?<Identifier>[0-9]*) specifies that [0-9]*'s results will be part of a named group that we index as above: match.Groups["Identifier"].Value

Use <Image> with a local file

Using React Native 0.41 (in March 2017), targeting iOS, I just found it as easy as:

<Image source={require('./myimage.png')} />

The image file must exist in the same folder as the .js file requiring it.

I didn't have to change anything in the XCode project. It just worked. Maybe things have changed a lot in 2 years!

Note that if the filename has anything other than lower-case letters, or the path is anything more than "./", then for me, it started failing. Not sure what the restrictions are, but start simple and work forward.

Hope this helps someone, as many other answers here seem overly complex and full of (naughty) off-site links.

UPDATE: BTW - The official documentation for this is here: https://facebook.github.io/react-native/docs/images.html

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

The problem is that SQL 2008 MS has a bug where connecting to a remote server (say like a service provider collocation) it will always try to open the fist db in the list, and since the possibilities of been ur db the first on the list are really low, it will throw and error and fail to display the list of dbs... which using sql 2005 management studio it just works.

Wished I could use SQL 2008 MS, but looks like as far I connect to remote SQL 2005, SQL 2008 is out of the question on my dev machine :(

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

Determining complexity for recursive functions (Big O notation)

The key here is to visualise the call tree. Once done that, the complexity is:

nodes of the call tree * complexity of other code in the function

the latter term can be computed the same way we do for a normal iterative function.

Instead, the total nodes of a complete tree are computed as

                  C^L - 1
                  -------  , when C>1
               /   C - 1
              /
 # of nodes =
              \    
               \ 
                  L        , when C=1

Where C is number of children of each node and L is the number of levels of the tree (root included).

It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".

So, in the examples above:

  1. the call tree here is C = 1, L = n+1. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n+1) * O(1) = O(n)
n     level 1
n-1   level 2
n-2   level 3
n-3   level 4
... ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n/5) * O(1) = O(n)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5
  1. call tree here is C = 1, L = log(n). Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = log5(n) * O(1) = O(log(n))
n
n/5
n/5^2
n/5^3
... ~ log5(n) levels -> L = log5(n)
  1. call tree here is C = 2, L = n. Complexity of the rest of function is O(1). This time we use the full formula for the number of nodes in the call tree because C > 1. Therefore total complexity is (C^L-1)/(C-1) * O(1) = (2^n - 1) * O(1) = O(2^n).
               n                   level 1
      n-1             n-1          level 2
  n-2     n-2     n-2     n-2      ...
n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3    ...     
              ...                ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(n). Therefore total complexity is L * O(1) = (n/5) * O(n) = O(n^2)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

In my case I got the error simply because I had changed the Listen 80 to listen 443 in the file

/etc/httpd/conf/httpd.conf 

Since I had installed mod_ssl using the yum commands

yum -y install mod_ssl  

there was a duplicate listen 443 directive in the file ssl.conf created during mod_ssl installation.

You can verify this if you have duplicate listen 80 or 443 by running the below command in linux centos (My linux)

grep  '443' /etc/httpd/conf.d/*

below is sample output

/etc/httpd/conf.d/ssl.conf:Listen 443 https
/etc/httpd/conf.d/ssl.conf:<VirtualHost _default_:443>
/etc/httpd/conf.d/ssl.conf:#ServerName www.example.com:443

Simply reverting the listen 443 in httd.conf to listen 80 fixed my issue.

How to run script as another user without password?

`su -c "Your command right here" -s /bin/sh username`

The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example; execl: couldn't exec /bin/sh execl: Permission denied

I had to install setroubleshoot and setools and run the following to allow it:

yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

In your comment on @Kenneth's answer you're saying that ReadAsStringAsync() is returning empty string.

That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.

What you can do is this:

public static string GetRequestBody()
{
    var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
    bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
    var bodyText = bodyStream.ReadToEnd();
    return bodyText;
}

Open another application from your own (intent)

Launch an application from another application on Android

  Intent launchIntent = getActivity.getPackageManager().getLaunchIntentForPackage("com.ionicframework.uengage");
        startActivity(launchIntent);

Rename multiple files in a directory in Python

import os import string def rename_files():

#List all files in the directory
file_list = os.listdir("/Users/tedfuller/Desktop/prank/")
print(file_list)

#Change current working directory and print out it's location
working_location = os.chdir("/Users/tedfuller/Desktop/prank/")
working_location = os.getcwd()
print(working_location)

#Rename all the files in that directory
for file_name in file_list:
    os.rename(file_name, file_name.translate(str.maketrans("","",string.digits)))

rename_files()

Passing parameters to a JQuery function

Using POST

function DoAction( id, name )
{
    $.ajax({
         type: "POST",
         url: "someurl.php",
         data: "id=" + id + "&name=" + name,
         success: function(msg){
                     alert( "Data Saved: " + msg );
                  }
    });
}

Using GET

function DoAction( id, name )
{
     $.ajax({
          type: "GET",
          url: "someurl.php",
          data: "id=" + id + "&name=" + name,
          success: function(msg){
                     alert( "Data Saved: " + msg );
                   }
     });
}

EDIT:

A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.

<a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a>
<a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a>
<a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a>
...
<a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a>

<script type="text/javascript">
$(function() {
   $('.ajax-link').click( function() {
         $.get( $(this).attr('href'), function(msg) {
              alert( "Data Saved: " + msg );
         });
         return false; // don't follow the link!
   });
});
</script>

How to exclude a directory in find . command

None of previous answers is good on Ubuntu. Try this:

find . ! -path "*/test/*" -type f -name "*.js" ! -name "*-min-*" ! -name "*console*"

I have found this here

Convert String to int array in java

If you prefer an Integer[] instead array of an int[] array:

Integer[]

String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(","); 
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);

int[]

String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(","); 
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()

This works for Java 8 and higher.

Get list of a class' instance methods

According to Ruby Doc instance_methods

Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. If the optional parameter is false, the methods of any ancestors are not included. I am taking the official documentation example.

module A
  def method1()  
    puts "method1 say hi"
  end
end
class B
  include A #mixin
  def method2()  
     puts "method2 say hi"
  end
end
class C < B #inheritance
  def method3() 
     puts "method3 say hi"
  end
end

Let's see the output.

A.instance_methods(false)
  => [:method1]

A.instance_methods
  => [:method1]
B.instance_methods
 => [:method2, :method1, :nil?, :===, ...# ] # methods inherited from parent class, most important :method1 is also visible because we mix module A in class B

B.instance_methods(false)
  => [:method2]
C.instance_methods
  => [:method3, :method2, :method1, :nil?, :===, ...#] # same as above
C.instance_methods(false)
 => [:method3]

Switch statement for string matching in JavaScript

var token = 'spo';

switch(token){
    case ( (token.match(/spo/) )? token : undefined ) :
       console.log('MATCHED')    
    break;;
    default:
       console.log('NO MATCH')
    break;;
}


--> If the match is made the ternary expression returns the original token
----> The original token is evaluated by case

--> If the match is not made the ternary returns undefined
----> Case evaluates the token against undefined which hopefully your token is not.

The ternary test can be anything for instance in your case

( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined 

===========================================

(token.match(/spo/) )? token : undefined ) 

is a ternary expression.

The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).

If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).

Obviously token === token so the switch statement is matched and the case evaluated

It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.

Easiest way to compare arrays in C#

For some applications may be better:

string.Join(",", arr1) == string.Join(",", arr2)

Is there a command line utility for rendering GitHub flavored Markdown?

Maybe this might help:

gem install github-markdown

No documentation exists, but I got it from the gollum documentation. Looking at rubydoc.info, it looks like you can use:

require 'github/markdown'  
puts GitHub::Markdown.render_gfm('your markdown string')

in your Ruby code. You can wrap that easily in a script to turn it into a command line utility:

#!/usr/bin/env ruby

# render.rb
require 'github/markdown'

puts GitHub::Markdown.render_gfm File.read(ARGV[0])

Execute it with ./render.rb path/to/my/markdown/file.md. Note that this is not safe for use in production without sanitization.

I want to convert std::string into a const wchar_t *

If you are on Linux/Unix have a look at mbstowcs() and wcstombs() defined in GNU C (from ISO C 90).

  • mbs stand for "Multi Bytes String" and is basically the usual zero terminated C string.

  • wcs stand for Wide Char String and is an array of wchar_t.

For more background details on wide chars have a look at glibc documentation here.

Why is jquery's .ajax() method not sending my session cookie?

Perhaps not 100% answering the question, but i stumbled onto this thread in the hope of solving a session problem when ajax-posting a fileupload from the assetmanager of the innovastudio editor. Eventually the solution was simple: they have a flash-uploader. Disabling that (setting

var flashUpload = false;   

in asset.php) and the lights started blinking again.

As these problems can be very hard to debug i found that putting something like the following in the upload handler will set you (well, me in this case) on the right track:

$sn=session_name();
error_log("session_name: $sn ");

if(isset($_GET[$sn])) error_log("session as GET param");
if(isset($_POST[$sn])) error_log("session as POST param");
if(isset($_COOKIE[$sn])) error_log("session as Cookie");
if(isset($PHPSESSID)) error_log("session as Global");

A dive into the log and I quickly spotted the missing session, where no cookie was sent.

Customizing the template within a Directive

Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.

Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.

The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:

    angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
           var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
             return htmlText;
        }
        compile: function(element, attrs)
        {
           //do whatever else is necessary
        }
    }
})

Landscape printing from HTML

-webkit-transform: rotate(-90deg); -moz-transform:rotate(-90deg);
     filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

not working in Firefox 16.0.2 but it is working in Chrome

How to view an HTML file in the browser with Visual Studio Code

Recently came across this feature in one of the visual studio code tutorial in www.lynda.com

Press Ctrl + K followed by M, it will open the "Select Language Mode" ( or click on the right hand bottom corner that says HTML before that smiley ), type markdown and press enter

Now Press Ctrl + K followed by V, it will open your html in a near by tab.

Tadaaa !!!

Now emmet commands were not working in this mode in my html file, so I went back to the original state ( note - html tag tellisense were working perfectly )

To go to original state - Press Ctrl + K followed by M, select auto-detect. emmet commands started to work. If you are happy with html only viewer, then there is no need for you to come back to the original state.

Wonder why vscode is not having html viewer option by default, when it is able to dispaly the html file in the markdown mode.

Anyway it is cool. Happy vscoding :)

Android Relative Layout Align Center

You can use gravity with aligning top and bottom.

 android:gravity="center_vertical"
 android:layout_alignTop="@id/place_category_icon"
 android:layout_alignBottom="@id/place_category_icon"

Google Maps API OVER QUERY LIMIT per second limit

Instead of client-side geocoding

geocoder.geocode({
    'address': your_address
  }, function (results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       var geo_data = results[0];
       // your code ...
   } 
})

I would go to server-side geocoding API

var apikey = YOUR_API_KEY;
var query = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + apikey;
$.getJSON(query, function (data) {
  if (data.status === 'OK') { 
    var geo_data = data.results[0];
  } 
})

Microsoft.Office.Core Reference Missing

I faced the same problem when i tried to open my old c# project into visual studio 2017 version. This problem arises typically when you try to open a project that you made with previous version of VS and open it with latest version. what i did is,i opened my project and delete the reference from my project,then added Microsoft outlook 12.0 object library and Microsoft office 12.0 object libraryMicrosoft outlook 12.0 object library

How do you check "if not null" with Eloquent?

in laravel 5.4 this code Model::whereNotNull('column') was not working you need to add get() like this one Model::whereNotNull('column')->get(); this one works fine for me.

Warning: Failed propType: Invalid prop `component` supplied to `Route`

There is an stable release on the react-router-dom (v5) with the fix for this issue.

link to github issue

Android soft keyboard covers EditText field

Why not try to add a ScrollView to wrap whatever it is you want to scroll. Here is how I have done it, where I actually leave a header on top which does not scroll, while the dialog widgets (in particular the EditTexts) scroll when you open soft keypad.

<LinearLayout android:id="@+id/HeaderLayout" >
  <!-- Here add a header or whatever will not be scrolled. -->
</LinearLayout>
<ScrollView android:id="@+id/MainForm" >
  <!-- Here add your edittexts or whatever will scroll. -->
</ScrollView>

I would typically have a LinearLayout inside the ScrollView, but that is up to you. Also, setting Scrollbar style to outsideInset helps, at least on my devices.

Remove style attribute from HTML tags

In addition to Lorenzo Marcon's answer:

Using preg_replace to select everything except style attribute:

$html = preg_replace('/(<p.+?)style=".+?"(>.+?)/i', "$1$2", $html);

Add spaces between the characters of a string in Java?

StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
   if (i > 0) {
      result.append(" ");
    }

   result.append(input.charAt(i));
}

System.out.println(result.toString());

What's the difference between select_related and prefetch_related in Django ORM?

Both methods achieve the same purpose, to forego unnecessary db queries. But they use different approaches for efficiency.

The only reason to use either of these methods is when a single large query is preferable to many small queries. Django uses the large query to create models in memory preemptively rather than performing on demand queries against the database.

select_related performs a join with each lookup, but extends the select to include the columns of all joined tables. However this approach has a caveat.

Joins have the potential to multiply the number of rows in a query. When you perform a join over a foreign key or one-to-one field, the number of rows won't increase. However, many-to-many joins do not have this guarantee. So, Django restricts select_related to relations that won't unexpectedly result in a massive join.

The "join in python" for prefetch_related is a little more alarming then it should be. It creates a separate query for each table to be joined. It filters each of these table with a WHERE IN clause, like:

SELECT "credential"."id",
       "credential"."uuid",
       "credential"."identity_id"
FROM   "credential"
WHERE  "credential"."identity_id" IN
    (84706, 48746, 871441, 84713, 76492, 84621, 51472);

Rather than performing a single join with potentially too many rows, each table is split into a separate query.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.

My example code

$rexpenditure = <<<Expenditure
                  <tr>
                      <td>$row->payment_referencenumber</td>
                      <td>$row->payment_requestdate</td>
                      <td>$row->payment_description</td>
                      <td>$row->payment_fundingsource</td>
                      <td>$row->payment_agencyulo</td>
                      <td>$row->payment_agencyproject</td>
                      <td>$$row->payment_disbustment</td>
                      <td>$row->payment_payeename</td>
                      <td>$row->payment_processpayment</td>
                  </tr>
Expenditure;

It will error if there is a space on PHP 7.0.33.

Is there any use for unique_ptr with array?

If you need a dynamic array of objects that are not copy-constructible, then a smart pointer to an array is the way to go. For example, what if you need an array of atomics.

SyntaxError: cannot assign to operator

in python only work

a=4
b=3

i=a+b

which i is new operator

How to replace url parameter with javascript/jquery?

Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:

/search?searchquery=text and 'query' is provided.

In this case searchquery param value is changed.

Code:

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
    }
    return newUrl
}

"E: Unable to locate package python-pip" on Ubuntu 18.04

To solve the problem of:

E: Unable to locate package python-pip

you should do this. This works with the python2.7 and you not going to get disappointed by it. follow the steps that are mention below. go to get-pip.py and copy all the code from it.
open the terminal using CTRL + ALT +T

vi get-pip.py

paste the copied code here and then exit from the vi editor by pressing

ESC then :wq => press Enter

lastly, now run the code and see the magic

sudo python get-pip.py

It automatically adds the pip command in your Linux.
you can see the output of my machine

Programmatically get the version number of a DLL

First of all, there are two possible 'versions' that you might be interested in:

  • Windows filesystem file version, applicable to all executable files

  • Assembly build version, which is embedded in a .NET assembly by the compiler (obviously only applicable to .NET assembly dll and exe files)

In the former case, you should use Ben Anderson's answer; in the latter case, use AssemblyName.GetAssemblyName(@"c:\path\to\file.dll").Version, or Tataro's answer, in case the assembly is referenced by your code.

Note that you can ignore all the answers that use .Load()/.LoadFrom() methods, since these actually load the assembly in the current AppDomain - which is analogous to cutting down a tree to see how old it is.

how to set the query timeout from SQL connection string

you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend

Image resizing in React Native

This worked for me:

image: {
  flex: 1,
  width: 900,
  height: 900,
  resizeMode: 'contain'
}

Just need to make sure that the width and height are bigger than you need as it is limited to what you set.

Setting a log file name to include current date in Log4j

I have created an appender that will do that. http://stauffer.james.googlepages.com/DateFormatFileAppender.java

/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.txt file.  */

package sps.log.log4j;

import java.io.IOException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.*;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/**
 * DateFormatFileAppender is a log4j Appender and extends 
 * {@link FileAppender} so each log is 
 * named based on a date format defined in the File property.
 *
 * Sample File: 'logs/'yyyy/MM-MMM/dd-EEE/HH-mm-ss-S'.log'
 * Makes a file like: logs/2004/04-Apr/13-Tue/09-45-15-937.log
 * @author James Stauffer
 */
public class DateFormatFileAppender extends FileAppender {

  /**
   * The default constructor does nothing.
   */
  public DateFormatFileAppender() {
  }

  /**
   * Instantiate a <code>DailyRollingFileAppender</code> and open the
   * file designated by <code>filename</code>. The opened filename will
   * become the ouput destination for this appender.
   */
  public DateFormatFileAppender (Layout layout, String filename) throws IOException {
    super(layout, filename, true);
  }

  private String fileBackup;//Saves the file pattern
  private boolean separate = false;

  public void setFile(String file) {
    super.setFile(file);
    this.fileBackup = getFile();
  }

  /**
   * If true each LoggingEvent causes that file to close and open.
   * This is useful when the file is a pattern that would often
   * produce a different filename.
   */
  public void setSeparate(boolean separate) {
    this.separate = separate;
  }

  protected void subAppend(LoggingEvent event) {
    if(separate) {
        try {//First reset the file so each new log gets a new file.
            setFile(getFile(), getAppend(), getBufferedIO(), getBufferSize());
        } catch(IOException e) {
            LogLog.error("Unable to reset fileName.");
        }
    }
    super.subAppend(event);
  }


  public
  synchronized
  void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
                                                            throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);
    String actualFileName = sdf.format(new Date());
    makeDirs(actualFileName);
    super.setFile(actualFileName, append, bufferedIO, bufferSize);
  }

  /**
   * Ensures that all of the directories for the given path exist.
   * Anything after the last / or \ is assumed to be a filename.
   */
  private void makeDirs (String path) {
    int indexSlash = path.lastIndexOf("/");
    int indexBackSlash = path.lastIndexOf("\\");
    int index = Math.max(indexSlash, indexBackSlash);
    if(index > 0) {
        String dirs = path.substring(0, index);
//        LogLog.debug("Making " + dirs);
        File dir = new File(dirs);
        if(!dir.exists()) {
            boolean success = dir.mkdirs();
            if(!success) {
                LogLog.error("Unable to create directories for " + dirs);
            }
        }
    }
  }

}

How to do a JUnit assert on a message in a logger

For log4j2 the solution is slightly different because AppenderSkeleton is not available anymore. Additionally, using Mockito, or similar library to create an Appender with an ArgumentCaptor will not work if you're expecting multiple logging messages because the MutableLogEvent is reused over multiple log messages. The best solution I found for log4j2 is:

private static MockedAppender mockedAppender;
private static Logger logger;

@Before
public void setup() {
    mockedAppender.message.clear();
}

/**
 * For some reason mvn test will not work if this is @Before, but in eclipse it works! As a
 * result, we use @BeforeClass.
 */
@BeforeClass
public static void setupClass() {
    mockedAppender = new MockedAppender();
    logger = (Logger)LogManager.getLogger(MatchingMetricsLogger.class);
    logger.addAppender(mockedAppender);
    logger.setLevel(Level.INFO);
}

@AfterClass
public static void teardown() {
    logger.removeAppender(mockedAppender);
}

@Test
public void test() {
    // do something that causes logs
    for (String e : mockedAppender.message) {
        // add asserts for the log messages
    }
}

private static class MockedAppender extends AbstractAppender {

    List<String> message = new ArrayList<>();

    protected MockedAppender() {
        super("MockedAppender", null, null);
    }

    @Override
    public void append(LogEvent event) {
        message.add(event.getMessage().getFormattedMessage());
    }
}

How can I write variables inside the tasks file in ansible

Whenever you have a module followed by a variable on the same line in ansible the parser will treat the reference variable as the beginning of an in-line dictionary. For example:

- name: some example
  command: {{ myapp }} -a foo

The default here is to parse the first part of {{ myapp }} -a foo as a dictionary instead of a string and you will get an error.

So you must quote the argument like so:

- name: some example
  command: "{{ myapp }} -a foo"

Converting Milliseconds to Minutes and Seconds?

You can easily convert miliseconds into seconds, minutes and hours.

                val millis = **milliSecondsYouWantToConvert**
                val seconds = (millis / 1000) % 60
                val minutes = ((millis / 1000) / 60) % 60
                val hours = ((millis / 1000) / 60) / 60

                println("--------------------------------------------------------------------")
                println(String.format("%02dh : %02dm : %02ds remaining", hours, minutes, seconds))
                println("--------------------------------------------------------------------")
**RESULT :** 
--------------------------------------------------------------------
  01h : 23m : 37s remaining
--------------------------------------------------------------------

What is a good pattern for using a Global Mutex in C#?

Sometimes learning by example helps the most. Run this console application in three different console windows. You'll see that the application you ran first acquires the mutex first, while the other two are waiting their turn. Then press enter in the first application, you'll see that application 2 now continues running by acquiring the mutex, however application 3 is waiting its turn. After you press enter in application 2 you'll see that application 3 continues. This illustrates the concept of a mutex protecting a section of code to be executed only by one thread (in this case a process) like writing to a file as an example.

using System;
using System.Threading;

namespace MutexExample
{
    class Program
    {
        static Mutex m = new Mutex(false, "myMutex");//create a new NAMED mutex, DO NOT OWN IT
        static void Main(string[] args)
        {
            Console.WriteLine("Waiting to acquire Mutex");
            m.WaitOne(); //ask to own the mutex, you'll be queued until it is released
            Console.WriteLine("Mutex acquired.\nPress enter to release Mutex");
            Console.ReadLine();
            m.ReleaseMutex();//release the mutex so other processes can use it
        }
    }
}

enter image description here

ORA-00054: resource busy and acquire with NOWAIT specified

Depending on your situation, the table being locked may just be part of a normal operation & you don't want to just kill the blocking transaction. What you want to do is have your statement wait for the other resource. Oracle 11g has DDL timeouts which can be set to deal with this.

If you're dealing with 10g then you have to get more creative and write some PL/SQL to handle the re-try. Look at Getting around ORA-00054 in Oracle 10g This re-runs your statement when a resource_busy exception occurs.

How can I echo a newline in a batch file?

Just like Grimtron suggests - here is a quick example to define it:

@echo off
set newline=^& echo.
echo hello %newline%world

Output

C:\>test.bat
hello
world

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

Replace non ASCII character from string

CharMatcher.retainFrom can be used, if you're using the Google Guava library:

String s = "A função";
String stripped = CharMatcher.ascii().retainFrom(s);
System.out.println(stripped); // Prints "A funo"

Concatenate two JSON objects

If you'd rather copy the properties:

var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };


function jsonConcat(o1, o2) {
 for (var key in o2) {
  o1[key] = o2[key];
 }
 return o1;
}

var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);

Output of above code is{ value1: '1', value2: '4', value3: '3' }

If input value is blank, assign a value of "empty" with Javascript

You can do this:

var getValue  = function (input, defaultValue) {
    return input.value || defaultValue;
};

How to put a UserControl into Visual Studio toolBox

I'm assuming you're using VS2010 (that's what you've tagged the question as) I had problems getting them to add automatically to the toolbox as in VS2008/2005. There's actually an option to stop the toolbox auto populating!

Go to Tools > Options > Windows Forms Designer > General

At the bottom of the list you'll find Toolbox > AutoToolboxPopulate which on a fresh install defaults to False. Set it true and then rebuild your solution.

Hey presto they user controls in you solution should be automatically added to the toolbox. You might have to reload the solution as well.

All ASP.NET Web API controllers return 404

For reasons that aren't clear to me I had declared all of my Methods / Actions as static - apparently if you do this it doesn't work. So just drop the static off

[AllowAnonymous]
[Route()]
public static HttpResponseMessage Get()
{
    return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}

Became:-

[AllowAnonymous]
[Route()]
public HttpResponseMessage Get()
{
    return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}

What is the best JavaScript code to create an img element

oImg.setAttribute('width', '1px');

px is for CSS only. Use either:

oImg.width = '1';

to set a width through HTML, or:

oImg.style.width = '1px';

to set it through CSS.

Note that old versions of IE don't create a proper image with document.createElement(), and old versions of KHTML don't create a proper DOM Node with new Image(), so if you want to be fully backwards compatible use something like:

// IEWIN boolean previously sniffed through eg. conditional comments

function img_create(src, alt, title) {
    var img = IEWIN ? new Image() : document.createElement('img');
    img.src = src;
    if ( alt != null ) img.alt = alt;
    if ( title != null ) img.title = title;
    return img;
}

Also be slightly wary of document.body.appendChild if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the <body> element has started), you could try inserting it at the start of the body using body.insertBefore(body.firstChild).

To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page <div> as the body's first child and put any tracking/preload images you don't want to be visible in there.

How do operator.itemgetter() and sort() work?

#sorting first by age then profession,you can change it in function "fun".
a = []

def fun(v):
    return (v[1],v[2])

# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])

a.sort(key=fun)


print a

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

While I'm all for unblocking people's work issues, I don't think "push --force" or "--allow_unrelated_histories" should be taught to new users as general solutions because they can cause real havoc to a repository when one uses them without understand why things aren't working in the first place.

When you have a situation like this where you started with a local repository, and want to make a remote on GitHub to share your work with, there is something to watch out for.

When you create the new online repository, there's an option "Initialize this repository with a README". If you read the fine print, it says "Skip this step if you’re importing an existing repository."

You may have checked that box. Or similarly, you made an add/commit online before you attempted an initial push. What happens is you create a unique commit history in each place and they can't be reconciled without the special allowance mentioned in Nevermore's answer (because git doesn't want you to operate that way). You can follow some of the advice mentioned here, or more simply just don't check that option next time you want to link some local files to a brand new remote; keeping the remote clean for that initial push.

Reference: my first experience with git + hub was to run into this same problem and do a lot of learning to understand what had happened and why.

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

How to install PHP mbstring on CentOS 6.2

If you have cPanel hosting you can use Easy Apache to do this through shell. These are the steps.

  1. Type the Easy Apache PathType the path for Easy Apache

    root@vps#### [~]# /scripts/easyapache

  2. Do not say yes to the "cPanel update available".
  3. Continue through the screens with defaults till you get to the "Exhaustive options list".
  4. Page down till you see the Mbstring extension listed and select it.
  5. Continue through the Steps and Save the Apache PHP build.

Apache and PHP will now rebuild to include the mbstring extension. Wait for the process to finish ~10 to 30 minutes. Once the process is finished you should see the Mbstring extension in the phpinfo now.

For more detailed steps see the article Installing the mbstring extension with Easy Apache

How does the Java 'for each' loop work?

The concept of a foreach loop as mentioned in Wikipedia is highlighted below:

Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read.

So the concept of a foreach loop describes that the loop does not use any explicit counter which means that there is no need of using indexes to traverse in the list thus it saves user from off-by-one error. To describe the general concept of this off-by-one error, let us take an example of a loop to traverse in a list using indexes.

// In this loop it is assumed that the list starts with index 0
for(int i=0; i<list.length; i++){

}

But suppose if the list starts with index 1 then this loop is going to throw an exception as it will found no element at index 0 and this error is called an off-by-one error. So to avoid this off-by-one error the concept of a foreach loop is used. There may be other advantages too, but this is what I think is the main concept and advantage of using a foreach loop.

Reset the database (purge all), then seed a database

As of Rails 5, the rake commandline tool has been aliased as rails so now

rails db:reset instead of rake db:reset

will work just as well

How to download all dependencies and packages to directory

The aptitude --download-only ... approach only works if you have a debian distro with internet connection in your hands.

If you don't, I think it is better to run the following script on the disconnected debian machine:

apt-get --print-uris --yes install <my_package_name> | grep ^\' | cut -d\' -f2 >downloads.list

move the downloads.list file into a connected linux (or non linux) machine, and run:

wget --input-file myurilist

this downloads all your files into the current directory.After that you can copy them on an USB key and install in your disconnected debian machine.

credits: http://www.tuxradar.com/answers/517

PS I basically copied the blog post because it was not very readable, and in case the post will disappear.

Java 8 Stream and operation on arrays

Please note that Arrays.stream(arr) create a LongStream (or IntStream, ...) instead of Stream so the map function cannot be used to modify the type. This is why .mapToLong, mapToObject, ... functions are provided.

Take a look at why-cant-i-map-integers-to-strings-when-streaming-from-an-array

connect to host localhost port 22: Connection refused

If install Hadoop on Mac OSX, make sure turn on Remote Login under System Preferences then File Sharing. This worked on my machine.

Remote Login

Loading cross-domain endpoint with AJAX

Figured it out. Used this instead.

$('.div_class').load('http://en.wikipedia.org/wiki/Cross-origin_resource_sharing #toctitle');

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

Ran into the same issue and researched this for a few minutes.

I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.

There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.

Most of the changes are mentioned above:

  • Program Files vs Program Files (x86)

    In the beginning the 16/86bit files were written on, '86' Intel processors.

  • System32 really means System64 (on 64-bit Windows)

    When developers first started working with Windows7, there were several compatibility issues where other applications where stored.

  • SysWOW64 really means SysWOW32

    Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.

Here are two links with all the basic info you need:

Hope this clears things up!

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

At the latest Google Play Services 15.0.0, it occurs this error when you include entire play service like this

implementation 'com.google.android.gms:play-services:15.0.0'

Instead, you must specific the detail service like Google Drive

com.google.android.gms:play-services-drive:15.0.0

Error inflating when extending a class

I had the same problem extending a TextEdit. For me the mistake was I did non add "public" to the constructor. In my case it works even if I define only one constructor, the one with arguments Context and AttributeSet. The wired thing is that the bug reveals itself only when I build an APK (singed or not) and I transfer it to the devices. When the application is run via AndroidStudio -> RunApp on a USB connected device the app works.

Change form size at runtime in C#

In order to call this you will have to store a reference to your form and pass the reference to the run method. Then you can call this in an actionhandler.

public partial class Form1 : Form
{
    public void ChangeSize(int width, int height)
    {
        this.Size = new Size(width, height);
    }
}

How do you share code between projects/solutions in Visual Studio?

You would simply create a separate Class Library project to contain the common code. It need not be part of any solution that uses it. Reference the class library from any project that needs it.

The only trick at all is that you will need to use a file reference to reference the project, since it will not be part of the solutions that refer to it. This means that the actual output assembly will have to be placed in a location that can be accessed by anyone building a project that references it. This can be done by placing the assembly on a share, for instance.

How to add items to a spinner in Android?

Try this code:

final List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
list.add("Item 5");

final String[] str = {"Report 1", "Report 2", "Report 3", "Report 4", "Report 5"};

final Spinner sp1 = (Spinner) findViewById(R.id.spinner1);
final Spinner sp2 = (Spinner) findViewById(R.id.spinner2);

ArrayAdapter<String> adp1 = new ArrayAdapter<String>(this,
                              android.R.layout.simple_list_item_1, list);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adp1);

ArrayAdapter<String> adp2 = new ArrayAdapter<String>(this,
                                  android.R.layout.simple_spinner_item, str);
adp2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adp2);

sp1.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), list.get(position), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

sp2.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), str[position], Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

You can also add spinner item value through String array xml file..

<resources>
    <string name="app_name">Spinner_ex5</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string-array name="str2">
        <item>Data 1</item>
        <item>Data 2</item>
        <item>Data 3</item>
        <item>Data 4</item>
        <item>Data 5</item>
    </string-array>
</resources>

In mainActivity.java:

final Spinner sp3 = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter<CharSequence> adp3 = ArrayAdapter.createFromResource(this,
                                    R.array.str2, android.R.layout.simple_list_item_1);

adp3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adp3);
sp3.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            String ss = sp3.getSelectedItem().toString();
            Toast.makeText(getBaseContext(), ss, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

How to copy directory recursively in python and overwrite all?

Here's a simple solution to recursively overwrite a destination with a source, creating any necessary directories as it goes. This does not handle symlinks, but it would be a simple extension (see answer by @Michael above).

def recursive_overwrite(src, dest, ignore=None):
    if os.path.isdir(src):
        if not os.path.isdir(dest):
            os.makedirs(dest)
        files = os.listdir(src)
        if ignore is not None:
            ignored = ignore(src, files)
        else:
            ignored = set()
        for f in files:
            if f not in ignored:
                recursive_overwrite(os.path.join(src, f), 
                                    os.path.join(dest, f), 
                                    ignore)
    else:
        shutil.copyfile(src, dest)

How do I run a command on an already existing Docker container?

I would like to note that the top answer is a little misleading.

The issue with executing docker run is that a new container is created every time. However, there are cases where we would like to revisit old containers or not take up space with new containers.

(Given clever_bardeen is the name of the container created...)

In OP's case, make sure the docker image is first running by executing the following command:

docker start clever_bardeen

Then, execute the docker container using the following command:

docker exec -it clever_bardeen /bin/bash

"SMTP Error: Could not authenticate" in PHPMailer

I had the same issue which was fixed following the instructions below

Test enabling “Access for less secure apps” (which just means the client/app doesn’t use OAuth 2.0 - https://oauth.net/2/) for the account you are trying to access. It's found in the account settings on the Security tab, Account permissions (not available to accounts with 2-step verification enabled): https://support.google.com/accounts/answer/6010255?hl=en

original link for the answer: https://support.google.com/mail/thread/5621336?msgid=6292199

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

Here is a super simple one liner based on Eric's answer

function adjust(color, amount) {
    return '#' + color.replace(/^#/, '').replace(/../g, color => ('0'+Math.min(255, Math.max(0, parseInt(color, 16) + amount)).toString(16)).substr(-2));
}

Examples:

adjust('#ffffff', -20) => "#ebebeb"
adjust('000000', 20) => "#141414"

What is the C# equivalent of NaN or IsNumeric?

Yeah, IsNumeric is VB. Usually people use the TryParse() method, though it is a bit clunky. As you suggested, you can always write your own.

int i;
if (int.TryParse(string, out i))
{

}

How to install a certificate in Xcode (preparing for app store submission)

These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)

a) Part on the developers' website:

Sign in into: https://developer.apple.com/

Member Center

Certificates, Identifiers & Profiles

Certificates>All

Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.

b) XCode part:

After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.

Go back button in a page

You can either use:

<button onclick="window.history.back()">Back</button>

or..

<button onclick="window.history.go(-1)">Back</button>

The difference, of course, is back() only goes back 1 page but go() goes back/forward the number of pages you pass as a parameter, relative to your current page.

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

Simpler yet:

idx = (-arr).argsort()[:n]

where n is the number of maximum values.

How to run ssh-add on windows?

One could install Git for Windows and subsequently run ssh-add:

Step 3: Add your key to the ssh-agent

To configure the ssh-agent program to use your SSH key:

If you have GitHub for Windows installed, you can use it to clone repositories and not deal with SSH keys. It also comes with the Git Bash tool, which is the preferred way of running git commands on Windows.

  1. Ensure ssh-agent is enabled:

    • If you are using Git Bash, turn on ssh-agent:

      # start the ssh-agent in the background
      ssh-agent -s
      # Agent pid 59566
      
    • If you are using another terminal prompt, such as msysgit, turn on ssh-agent:

      # start the ssh-agent in the background
      eval $(ssh-agent -s)
      # Agent pid 59566
      
  2. Add your SSH key to the ssh-agent:

    ssh-add ~/.ssh/id_rsa
    

ASP.Net MVC How to pass data from view to controller

In case you don't want/need to post:

@Html.ActionLink("link caption", "actionName", new { Model.Page })  // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);

[HttpGet]
public ActionResult actionName(int reportID)
{

Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)

Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

How to run Selenium WebDriver test cases in Chrome

You should download the chromeDriver in a folder, and add this folder in your PATH environment variable.

You'll have to restart your console to make it work.

Maven artifact and groupId naming

Consider following as for building basic first Maven application:

groupId

  • com.companyname.project

artifactId

  • project

version

  • 0.0.1

Format date with Moment.js

Include moment.js and using the below code you can format your date

var formatDate= 1399919400000;

var responseDate = moment(formatDate).format('DD/MM/YYYY');

My output is "13/05/2014"

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

How do I create a branch?

Below are the steps to create a branch from trunk using TortoiseSVN in windows machine. This obviously needs TortoiseSVN client to be installed.

  1. Right Click on updated trunk from local windows machine
  2. Select TortoiseSVN
  3. Click branch/Tag
  4. Select the To path in SVN repository. Note that destination URL is updated according to the path and branch name given
  5. Do not create folder inside branches in repository browser
  6. Add branches path. For example, branches/
  7. Add a meaningful log message for your reference
  8. Click Ok, this creates new folder on local system
  9. Checkout the branch created into new folder

awk without printing newline

You can simply use ORS dynamically like this:

awk '{ORS="" ; print($1" "$2" "$3" "$4" "$5" "); ORS="\n"; print($6-=2*$6)}' file_in > file_out

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Not going to be everyone's fix, but it was for me:

So, i ran across this exact issue. The problem I seemed to have was when my DataTable didnt have an ID column, but the target destination had one with a primary key.

When i adapted my DataTable to have an id, the copy worked perfectly.

In my scenario, the Id column isnt very important to have the primary key so i deleted this column from the target destination table and the SqlBulkCopy is working without issue.

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

Try pd.ExcelFile:

xls = pd.ExcelFile('path_to_file.xls')
df1 = pd.read_excel(xls, 'Sheet1')
df2 = pd.read_excel(xls, 'Sheet2')

As noted by @HaPsantran, the entire Excel file is read in during the ExcelFile() call (there doesn't appear to be a way around this). This merely saves you from having to read the same file in each time you want to access a new sheet.

Note that the sheet_name argument to pd.read_excel() can be the name of the sheet (as above), an integer specifying the sheet number (eg 0, 1, etc), a list of sheet names or indices, or None. If a list is provided, it returns a dictionary where the keys are the sheet names/indices and the values are the data frames. The default is to simply return the first sheet (ie, sheet_name=0).

If None is specified, all sheets are returned, as a {sheet_name:dataframe} dictionary.

Pipe to/from the clipboard in Bash script

There are different clipboards in Linux; the X server has one, the window manager might have another one, etc. There is no standard device.

Oh, yes, on CLI, the screen program has its own clipboard as well, as do some other applications like Emacs and vi.

In X, you can use xclip.

You can check this thread for other possible answers: http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2004-07/0919.html

Get textarea text with javascript or Jquery

As @Darin Dimitrov said, if it is not an iframe on the same domain it is not posible, if it is, check that $("#frame1").contents() returns all it should, and then check if the textbox is found:

$("#frame1").contents().find("#area1").length should be 1.

Edit

If when your textarea is "empty" an empty string is returned and when it has some text entered that text is returned, then it is working perfect!! When the textarea is empty, an empty string is returned!

Edit 2 Ok. Here there is one way, it is not very pretty but it works:

Outside the iframe you will access the textarea like this:

window.textAreaInIframe

And inside the iframe (which I assume has jQuery) in the document ready put this code:

$("#area1").change(function() {
    window.parent.textAreaInIframe = $(this).val();
}).trigger("change");

Remove blank attributes from an Object in Javascript

Using ramda#pickBy you will remove all null, undefined and false values:

const obj = {a:1, b: undefined, c: null, d: 1}
R.pickBy(R.identity, obj)

As @manroe pointed out, to keep false values use isNil():

const obj = {a:1, b: undefined, c: null, d: 1, e: false}
R.pickBy(v => !R.isNil(v), obj)

How to output a multiline string in Bash?

Use -e option, then you can print new line character with \n in the string.

Sample (but not sure whether a good one or not)

The fun thing is that -e option is not documented in MacOS's man page while still usable. It is documented in the man page of Linux.

CSS /JS to prevent dragging of ghost image?

You can set the draggable attribute to false in either the markup or JavaScript code.

_x000D_
_x000D_
// As a jQuery method: $('#myImage').attr('draggable', false);_x000D_
document.getElementById('myImage').setAttribute('draggable', false);
_x000D_
<img id="myImage" src="http://placehold.it/150x150">
_x000D_
_x000D_
_x000D_

Java output formatting for Strings

System.out.println(String.format("%-20s= %s" , "label", "content" ));
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string

The output looks like this:

label               = content

As a reference I recommend Javadoc on formatter syntax

ActiveRecord: size vs count

As the other answers state:

  • count will perform an SQL COUNT query
  • length will calculate the length of the resulting array
  • size will try to pick the most appropriate of the two to avoid excessive queries

But there is one more thing. We noticed a case where size acts differently to count/lengthaltogether, and I thought I'd share it since it is rare enough to be overlooked.

  • If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

    class Image < ActiveRecord::Base
      belongs_to :product, counter_cache: true
    end
    
    class Product < ActiveRecord::Base
      has_many :images
    end
    
    > product = Product.first  # query, load product into memory
    > product.images.size      # no query, reads the :images_count column
    > product.images.count     # query, SQL COUNT
    > product.images.length    # query, loads images into memory
    

This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

I also have faced the same issue. Initially tried modifying System PATH which does not worked out. Later resolved by installing Micro Visual Studio express.

Why am I getting this error Premature end of file?

You are getting the error because the SAXBuilder is not intelligent enough to deal with "blank states". So it looks for at least an <xml ..> declaration, and when that causes a no data response it creates the exception you see rather than report the empty state.

Convert blob to base64

Another way is to use a simple wrapper around FileReader returning Observable:

  function toBase64(blob: Blob): Observable<string> {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return fromEvent(reader, 'load')
      .pipe(map(() => (reader.result as string).split(',')[1]));
  }

Usage:

toBase64(blob).subscribe(base64 => console.log(base64));

Why is Spring's ApplicationContext.getBean considered bad?

One of the coolest benefits of using something like Spring is that you don't have to wire your objects together. Zeus's head splits open and your classes appear, fully formed with all of their dependencies created and wired-in, as needed. It's magical and fantastic.

The more you say ClassINeed classINeed = (ClassINeed)ApplicationContext.getBean("classINeed");, the less magic you're getting. Less code is almost always better. If your class really needed a ClassINeed bean, why didn't you just wire it in?

That said, something obviously needs to create the first object. There's nothing wrong with your main method acquiring a bean or two via getBean(), but you should avoid it because whenever you're using it, you're not really using all of the magic of Spring.

Java for loop multiple variables

I think this should work:

    String rank = card.substring(0,1);
    String suit = card.substring(1);
    String cards = "A23456789TJQKDHSCl";

    String[] name = {"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Diamonds","Hearts","Spades","Clubs"};
    String c ="";
    for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++ )
    {
        if( rank.equals( cards.substring(a,b) ) )
        {
            c+=name[a];
        }


    }
    System.out.println(c);

How to download a file using a Java REST service and a data stream

"How can I directly (without saving the file on 2nd server) download the file from 1st server to client's machine?"

Just use the Client API and get the InputStream from the response

Client client = ClientBuilder.newClient();
String url = "...";
final InputStream responseStream = client.target(url).request().get(InputStream.class);

There are two flavors to get the InputStream. You can also use

Response response = client.target(url).request().get();
InputStream is = (InputStream)response.getEntity();

Which one is the more efficient? I'm not sure, but the returned InputStreams are different classes, so you may want to look into that if you care to.

From 2nd server I can get a ByteArrayOutputStream to get the file from 1st server, can I pass this stream further to the client using the REST service?

So most of the answers you'll see in the link provided by @GradyGCooper seem to favor the use of StreamingOutput. An example implementation might be something like

final InputStream responseStream = client.target(url).request().get(InputStream.class);
System.out.println(responseStream.getClass());
StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) throws IOException, WebApplicationException {  
        int length;
        byte[] buffer = new byte[1024];
        while((length = responseStream.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
        responseStream.close();
    }   
};
return Response.ok(output).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

But if we look at the source code for StreamingOutputProvider, you'll see in the writeTo, that it simply writes the data from one stream to another. So with our implementation above, we have to write twice.

How can we get only one write? Simple return the InputStream as the Response

final InputStream responseStream = client.target(url).request().get(InputStream.class);
return Response.ok(responseStream).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

If we look at the source code for InputStreamProvider, it simply delegates to ReadWriter.writeTo(in, out), which simply does what we did above in the StreamingOutput implementation

 public static void writeTo(InputStream in, OutputStream out) throws IOException {
    int read;
    final byte[] data = new byte[BUFFER_SIZE];
    while ((read = in.read(data)) != -1) {
        out.write(data, 0, read);
    }
}

Asides:

  • Client objects are expensive resources. You may want to reuse the same Client for request. You can extract a WebTarget from the client for each request.

    WebTarget target = client.target(url);
    InputStream is = target.request().get(InputStream.class);
    

    I think the WebTarget can even be shared. I can't find anything in the Jersey 2.x documentation (only because it is a larger document, and I'm too lazy to scan through it right now :-), but in the Jersey 1.x documentation, it says the Client and WebResource (which is equivalent to WebTarget in 2.x) can be shared between threads. So I'm guessing Jersey 2.x would be the same. but you may want to confirm for yourself.

  • You don't have to make use of the Client API. A download can be easily achieved with the java.net package APIs. But since you're already using Jersey, it doesn't hurt to use its APIs

  • The above is assuming Jersey 2.x. For Jersey 1.x, a simple Google search should get you a bunch of hits for working with the API (or the documentation I linked to above)


UPDATE

I'm such a dufus. While the OP and I are contemplating ways to turn a ByteArrayOutputStream to an InputStream, I missed the simplest solution, which is simply to write a MessageBodyWriter for the ByteArrayOutputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

@Provider
public class OutputStreamWriter implements MessageBodyWriter<ByteArrayOutputStream> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return ByteArrayOutputStream.class == type;
    }

    @Override
    public long getSize(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        t.writeTo(entityStream);
    }
}

Then we can simply return the ByteArrayOutputStream in the response

return Response.ok(baos).build();

D'OH!

UPDATE 2

Here are the tests I used (

Resource class

@Path("test")
public class TestResource {

    final String path = "some_150_mb_file";

    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response doTest() throws Exception {
        InputStream is = new FileInputStream(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        byte[] buffer = new byte[4096];
        while ((len = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, len);
        }
        System.out.println("Server size: " + baos.size());
        return Response.ok(baos).build();
    }
}

Client test

public class Main {
    public static void main(String[] args) throws Exception {
        Client client = ClientBuilder.newClient();
        String url = "http://localhost:8080/api/test";
        Response response = client.target(url).request().get();
        String location = "some_location";
        FileOutputStream out = new FileOutputStream(location);
        InputStream is = (InputStream)response.getEntity();
        int len = 0;
        byte[] buffer = new byte[4096];
        while((len = is.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        is.close();
    }
}

UPDATE 3

So the final solution for this particular use case was for the OP to simply pass the OutputStream from the StreamingOutput's write method. Seems the third-party API, required a OutputStream as an argument.

StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) {
        thirdPartyApi.downloadFile(.., .., .., out);
    }
}
return Response.ok(output).build();

Not quite sure, but seems the reading/writing within the resource method, using ByteArrayOutputStream`, realized something into memory.

The point of the downloadFile method accepting an OutputStream is so that it can write the result directly to the OutputStream provided. For instance a FileOutputStream, if you wrote it to file, while the download is coming in, it would get directly streamed to the file.

It's not meant for us to keep a reference to the OutputStream, as you were trying to do with the baos, which is where the memory realization comes in.

So with the way that works, we are writing directly to the response stream provided for us. The method write doesn't actually get called until the writeTo method (in the MessageBodyWriter), where the OutputStream is passed to it.

You can get a better picture looking at the MessageBodyWriter I wrote. Basically in the writeTo method, replace the ByteArrayOutputStream with StreamingOutput, then inside the method, call streamingOutput.write(entityStream). You can see the link I provided in the earlier part of the answer, where I link to the StreamingOutputProvider. This is exactly what happens