Programs & Examples On #String evaluation

Center Oversized Image in Div

Do not use fixed or an explicit width or height to the image tag. Instead, code it:

      max-width:100%;
      max-height:100%;

ex: http://jsfiddle.net/xwrvxser/1/

Windows service start failure: Cannot start service from the command line or debugger

Your code has nothing to do with the service installation, it is not the problem.

In order to test the service, you must install it as indicated.

For more information about installing your service : Installing and Uninstalling Services

$(this).serialize() -- How to add a value?

While matt b's answer will work, you can also use .serializeArray() to get an array from the form data, modify it, and use jQuery.param() to convert it to a url-encoded form. This way, jQuery handles the serialisation of your extra data for you.

var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
    type: 'POST',
    url: this.action,
    data: $.param(data),
});

How to convert int to float in python?

You can just multiply 1.0

>>> 1.0*144/314
0.4585987261146497

Docker: How to use bash with an Alpine based docker image?

RUN /bin/sh -c "apk add --no-cache bash"

worked for me.

Chrome Extension: Make it run every page load

If it needs to run on the onload event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload.

The cast to value type 'Int32' failed because the materialized value is null

I have used this code and it responds correctly, only the output value is nullable.

var packesCount = await botContext.Sales.Where(s => s.CustomerId == cust.CustomerId && s.Validated)
                                .SumAsync(s => (int?)s.PackesCount);
                            if(packesCount != null)
                            {
                                // your code
                            }
                            else
                            {
                                // your code
                            }

MySQL select query with multiple conditions

Lets suppose there is a table with following describe command for table (hello)- name char(100), id integer, count integer, city char(100).

we have following basic commands for MySQL -

select * from hello;
select name, city from hello;
etc 

select name from hello where id = 8;
select id from hello where name = 'GAURAV';

now lets see multiple where condition -

select name from hello where id = 3 or id = 4 or id = 8 or id = 22;

select name from hello where id =3 and count = 3 city = 'Delhi';

This is how we can use multiple where commands in MySQL.

List<T> OrderBy Alphabetical Order

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

Is it ok to run docker from inside docker?

Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".

And also it would require to run the docker in privileged mode, so the commands would be:

sudo chmod 757 /var/run/docker.sock

docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...

SQL query for finding records where count > 1

create table payment(
    user_id int(11),
    account int(11) not null,
    zip int(11) not null,
    dt date not null
);

insert into payment values
(1,123,55555,'2009-12-12'),
(1,123,66666,'2009-12-12'),
(1,123,77777,'2009-12-13'),
(2,456,77777,'2009-12-14'),
(2,456,77777,'2009-12-14'),
(2,789,77777,'2009-12-14'),
(2,789,77777,'2009-12-14');

select foo.user_id, foo.cnt from
(select user_id,count(account) as cnt, dt from payment group by account, dt) foo
where foo.cnt > 1;

How can I read an input string of unknown length?

i also have a solution with standard inputs and outputs

#include<stdio.h>
#include<malloc.h>
int main()
{
    char *str,ch;
    int size=10,len=0;
    str=realloc(NULL,sizeof(char)*size);
    if(!str)return str;
    while(EOF!=scanf("%c",&ch) && ch!="\n")
    {
        str[len++]=ch;
        if(len==size)
        {
            str = realloc(str,sizeof(char)*(size+=10));
            if(!str)return str;
        }
    }
    str[len++]='\0';
    printf("%s\n",str);
    free(str);
}

When should I use double or single quotes in JavaScript?

After reading all the answers that say it may be be faster or may be have advantages, I would say double quotes are better or may be faster too because the Google Closure compiler converts single quotes to double quotes.

Invalid attempt to read when no data is present

You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

Ajax success event not working

I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:

  1. The result was not being returned in JSON format
  2. I was trying to convert an array to JSON format, but this array had non-utf characters

So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.

How to avoid pressing Enter with getchar() for reading a single character only?

This depends on your OS, if you are in a UNIX like environment the ICANON flag is enabled by default, so input is buffered until the next '\n' or EOF. By disabling the canonical mode you will get the characters immediately. This is also possible on other platforms, but there is no straight forward cross-platform solution.

EDIT: I see you specified that you use Ubuntu. I just posted something similar yesterday, but be aware that this will disable many default behaviors of your terminal.

#include<stdio.h>
#include <termios.h>            //termios, TCSANOW, ECHO, ICANON
#include <unistd.h>     //STDIN_FILENO


int main(void){   
    int c;   
    static struct termios oldt, newt;

    /*tcgetattr gets the parameters of the current terminal
    STDIN_FILENO will tell tcgetattr that it should write the settings
    of stdin to oldt*/
    tcgetattr( STDIN_FILENO, &oldt);
    /*now the settings will be copied*/
    newt = oldt;

    /*ICANON normally takes care that one line at a time will be processed
    that means it will return if it sees a "\n" or an EOF or an EOL*/
    newt.c_lflag &= ~(ICANON);          

    /*Those new settings will be set to STDIN
    TCSANOW tells tcsetattr to change attributes immediately. */
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);

    /*This is your part:
    I choose 'e' to end input. Notice that EOF is also turned off
    in the non-canonical mode*/
    while((c=getchar())!= 'e')      
        putchar(c);                 

    /*restore the old settings*/
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);


    return 0;
}

You will notice, that every character appears twice. This is because the input is immediately echoed back to the terminal and then your program puts it back with putchar() too. If you want to disassociate the input from the output, you also have to turn of the ECHO flag. You can do this by simply changing the appropriate line to:

newt.c_lflag &= ~(ICANON | ECHO); 

How do I compare 2 rows from the same table (SQL Server)?

SELECT COUNT(*) FROM (SELECT * FROM tbl WHERE id=1 UNION SELECT * FROM tbl WHERE id=2) a

If you got two rows, they different, if one - the same.

Is there a way to pass optional parameters to a function?

The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.

First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.

For instance, here's a function opt_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".

>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
...     if ('optional' in keyword_parameters):
...         print 'optional parameter found, it is ', keyword_parameters['optional']
...     else:
...         print 'no optional parameter, sorry'
... 
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is  yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry

Second, you can supply a default parameter value of some value like None which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.

Embed website into my site

**What's the best way to avoid a fixed size, i.e., to have the embedded website scale responsively to the browser's window size? I'd like to avoid scroll bars within my website. – CGFoX Feb 2 '19 at 15:52

**Is it possible to set width and height to percentages instead of absolute pixels? – CGFoX Mar 16 at 11:53

ANSWER: <embed src="https://YOURDOMAIN.com/PAGE.HTM" style="width:100%; height: 50vw;">

remove inner shadow of text input

Set border: 1px solid black to make all sides equals and remove any kind of custom border (other than solid). Also, set box-shadow: none to remove any inset shadow applied to it.

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

How to add a custom HTTP header to every WCF call?

If you just want to add the same header to all the requests to the service, you can do it with out any coding!
Just add the headers node with required headers under the endpoint node in your client config file

<client>  
  <endpoint address="http://localhost/..." >  
    <headers>  
      <HeaderName>Value</HeaderName>  
    </headers>   
 </endpoint>  

How to get the current date without the time?

Use DateTime.Today property. It will return date component of DateTime.Now. It is equivalent of DateTime.Now.Date.

Nested Recycler view height doesn't wrap its content

UPDATE March 2016

By Android Support Library 23.2.1 of a support library version. So all WRAP_CONTENT should work correctly.

Please update version of a library in gradle file.

compile 'com.android.support:recyclerview-v7:23.2.1'

This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible.

you’ll be required to call setAutoMeasureEnabled(true)

Fixed bugs related to various measure-spec methods in update

Check https://developer.android.com/topic/libraries/support-library/features.html

How to set the color of an icon in Angular Material?

That's because the color input only accepts three attributes: "primary", "accent" or "warn". Hence, you'll have to style the icons the CSS way:

  1. Add a class to style your icon:

    .white-icon {
        color: white;
    }
    /* Note: If you're using an SVG icon, you should make the class target the `<svg>` element */
    .white-icon svg {
        fill: white;
    }
    
  2. Add the class to your icon:

    <mat-icon class="white-icon">menu</mat-icon>
    

Adding a 'share by email' link to website

Easiest: http://www.addthis.com/

Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...

Managing SSH keys within Jenkins for Git

Have you tried logging in as the jenkins user?

Try this:

sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git

Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.

If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?

selecting rows with id from another table

SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'

jQuery append() vs appendChild()

No longer

now append is a method in JavaScript

MDN documentation on append method

Quoting MDN

The ParentNode.append method inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes.

This is not supported by IE and Edge but supported by Chrome(54+), Firefox(49+) and Opera(39+).

The JavaScript's append is similar to jQuery's append.

You can pass multiple arguments.

_x000D_
_x000D_
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
_x000D_
_x000D_

HttpUtility does not exist in the current context

SLaks has the right answer... but let me be a bit more specific for people, like me, who are annoyed by this and can't find it right away :

Project -> Properties -> Application -> Target Framework -> select ".Net Framework 4"

the project will then save and reload.

PHP is not recognized as an internal or external command in command prompt

I also got the following error when I run a command with PHP, I did the solution like that:

  1. From the desktop, right-click the Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced system settings link.
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  5. In the Edit System Variable window, Add C:\xampp\php to your PATH Environment Variable.

Very important note: restart command prompt

Aligning two divs side-by-side

I don't understand why Nick is using margin-left: 200px; instead off floating the other div to the left or right, I've just tweaked his markup, you can use float for both elements instead of using margin-left.

Demo

#main {
    margin: auto;
    width: 400px;
}

#sidebar    {
    width: 100px;
    min-height: 400px;
    background: red;
    float: left;
}

#page-wrap  {
    width: 300px;
    background: #0f0;
    min-height: 400px;
    float: left;
}

.clear:after {
    clear: both;
    display: table;
    content: "";
}

Also, I've used .clear:after which am calling on the parent element, just to self clear the parent.

How To limit the number of characters in JTextField?

Read the section from the Swing tutorial on Implementing a DocumentFilter for a more current solution.

This solution will work an any Document, not just a PlainDocument.

This is a more current solution than the one accepted.

How to customize an end time for a YouTube video?

Youtube doesn't provide any option for an end time, but there alternative sites that provide this, like Tubechop. Otherwise try writing a function that either pauses video/skips to next when your when your video has played its desired duration.

OR: using the Youtube Javascript player API, you could do something like this:

function onPlayerStateChange(evt) {
    if (evt.data == YT.PlayerState.PLAYING && !done) {
        setTimeout(stopVideo, 6000);
        done = true;
    }
}

Youtube API blog

Convert a positive number to negative in C#

Just for fun:

int negativeInt = int.Parse(String.Format("{0}{1}", 
    "-", positiveInt.ToString()));

Update: the beauty of this approach is that you can easily refactor it into an exception generator:

int negativeInt = int.Parse(String.Format("{0}{1}", 
    "thisisthedumbestquestioninstackoverflowhistory", positiveInt.ToString()));

Difference between break and continue in PHP?

Break ends the current loop/control structure and skips to the end of it, no matter how many more times the loop otherwise would have repeated.

Continue skips to the beginning of the next iteration of the loop.

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

Preview an image before it is uploaded

One-liner solution:

The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):

_x000D_
_x000D_
<img id="blah" alt="your image" width="100" height="100" />_x000D_
_x000D_
<input type="file" _x000D_
    onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">
_x000D_
_x000D_
_x000D_

Generated URL will be like:

blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345

How to know whether refresh button or browser back button is clicked in Firefox

Use 'event.currentTarget.performance.navigation.type' to determine the type of navigation. This is working in IE, FF and Chrome.

function CallbackFunction(event) {
    if(window.event) {
        if (window.event.clientX < 40 && window.event.clientY < 0) {
            alert("back button is clicked");
        }else{
            alert("refresh button is clicked");
        }
    }else{
        if (event.currentTarget.performance.navigation.type == 2) {
            alert("back button is clicked");
        }
        if (event.currentTarget.performance.navigation.type == 1) {
            alert("refresh button is clicked");
        }           
    }
}

Simple timeout in java

What you are looking for can be found here. It may exist a more elegant way to accomplish that, but one possible approach is

Option 1 (preferred):

final Duration timeout = Duration.ofSeconds(30);
ExecutorService executor = Executors.newSingleThreadExecutor();

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

try {
    handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
    handler.cancel(true);
}

executor.shutdownNow();

Option 2:

final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

executor.schedule(new Runnable() {
    @Override
    public void run(){
        handler.cancel(true);
    }      
}, timeout.toMillis(), TimeUnit.MILLISECONDS);

executor.shutdownNow();

Those are only a draft so that you can get the main idea.

How can I select random files from a directory in bash?

If you have more files in your folder, you can use the below piped command I found in unix stackexchange.

find /some/dir/ -type f -print0 | xargs -0 shuf -e -n 8 -z | xargs -0 cp -vt /target/dir/

Here I wanted to copy the files, but if you want to move files or do something else, just change the last command where I have used cp.

Laravel-5 how to populate select box from database with id value and name value

To populate the drop-down select box in laravel we have to follow the below steps.

From controller we have to get the value like this:

 public function addCustomerLoyaltyCardDetails(){
        $loyalityCardMaster = DB::table('loyality_cards')->pluck('loyality_card_id', 'loyalityCardNumber');
        return view('admin.AddCustomerLoyaltyCardScreen')->with('loyalityCardMaster',$loyalityCardMaster);
    }

And the same we can display in view:

 <select class="form-control" id="loyalityCardNumber" name="loyalityCardNumber" >
       @foreach ($loyalityCardMaster as $id => $name)                                     
            <option value="{{$name}}">{{$id}}</option>
       @endforeach
 </select>

This key value in drop down you can use as per your requirement. Hope it may help someone.

Switch case with conditions

What you are doing is to look for (0) or (1) results.

(cnt >= 10 && cnt <= 20) returns either true or false.

--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--

How to convert a column of DataTable to a List

var list = dataTable.Rows.OfType<DataRow>()
    .Select(dr => dr.Field<string>(columnName)).ToList();

[Edit: Add a reference to System.Data.DataSetExtensions to your project if this does not compile]

Checking during array iteration, if the current element is the last element

This always does the trick for me

foreach($array as $key => $value) {
   if (end(array_keys($array)) == $key)
       // Last key reached
}

Edit 30/04/15

$last_key = end(array_keys($array));
reset($array);

foreach($array as $key => $value) {
  if ( $key == $last_key)
      // Last key reached
}

To avoid the E_STRICT warning mentioned by @Warren Sergent

$array_keys = array_keys($array);
$last_key = end($array_keys);

What are the advantages of NumPy over regular Python lists?

NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.

Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!

The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!

How to remove all namespaces from XML with C#?

The reply's by Jimmy and Peter were a great help, but they actually removed all attributes, so I made a slight modification:

Imports System.Runtime.CompilerServices

Friend Module XElementExtensions

    <Extension()> _
    Public Function RemoveAllNamespaces(ByVal element As XElement) As XElement
        If element.HasElements Then
            Dim cleanElement = RemoveAllNamespaces(New XElement(element.Name.LocalName, element.Attributes))
            cleanElement.Add(element.Elements.Select(Function(el) RemoveAllNamespaces(el)))
            Return cleanElement
        Else
            Dim allAttributesExceptNamespaces = element.Attributes.Where(Function(attr) Not attr.IsNamespaceDeclaration)
            element.ReplaceAttributes(allAttributesExceptNamespaces)
            Return element
        End If

    End Function

End Module

Highlight label if checkbox is checked

You can't do this with CSS alone. Using jQuery you can do

HTML

<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />

CSS

.highlight{
    background:yellow;
}

jQuery

$('#check').click(function(){
    $('#lab').toggleClass('highlight')
})

This will work in all browsers

Check working example at http://jsfiddle.net/LgADZ/

isset in jQuery?

You can use length:

if($("#one").length) { // 0 == false; >0 == true
    alert('yes');
}

Why does "npm install" rewrite package-lock.json?

Short Answer:

  • npm install honors package-lock.json only if it satisfies the requirements of package.json.
  • If it doesn't satisfy those requirements, packages are updated & package-lock is overwritten.
  • If you want the install to fail instead of overwriting package-lock when this happens, use npm ci.

Here is a scenario that might explain things (Verified with NPM 6.3.0)

You declare a dependency in package.json like:

"depA": "^1.0.0"

Then you do, npm install which will generate a package-lock.json with:

"depA": "1.0.0"

Few days later, a newer minor version of "depA" is released, say "1.1.0", then the following holds true:

npm ci       # respects only package-lock.json and installs 1.0.0

npm install  # also, respects the package-lock version and keeps 1.0.0 installed 
             # (i.e. when package-lock.json exists, it overrules package.json)

Next, you manually update your package.json to:

"depA": "^1.1.0"

Then rerun:

npm ci      # will try to honor package-lock which says 1.0.0
            # but that does not satisfy package.json requirement of "^1.1.0" 
            # so it would throw an error 

npm install # installs "1.1.0" (as required by the updated package.json)
            # also rewrites package-lock.json version to "1.1.0"
            # (i.e. when package.json is modified, it overrules the package-lock.json)

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Is Secure.ANDROID_ID unique for each device?

Just list an alternaitve solution here, the Advertising ID:

https://support.google.com/googleplay/android-developer/answer/6048248?hl=en

Copied from the link above:

The advertising ID is a unique, user-resettable ID for advertising, provided by Google Play services. It gives users better controls and provides developers with a simple, standard system to continue to monetize their apps. It enables users to reset their identifier or opt out of personalized ads (formerly known as interest-based ads) within Google Play apps.

The limitations are:

  1. Google Play enabled devices only.
  2. Privacy Policy: https://support.google.com/googleplay/android-developer/answer/113469?hl=en&rd=1#privacy

How can I generate a 6 digit unique number?

<?php echo rand(100000,999999); ?>

you can generate random number

Are HTTP cookies port specific?

According to RFC2965 3.3.1 (which might or might not be followed by browsers), unless the port is explicitly specified via the port parameter of the Set-Cookie header, cookies might or might not be sent to any port.

Google's Browser Security Handbook says: by default, cookie scope is limited to all URLs on the current host name - and not bound to port or protocol information. and some lines later There is no way to limit cookies to a single DNS name only [...] likewise, there is no way to limit them to a specific port. (Also, keep in mind, that IE does not factor port numbers into its same-origin policy at all.)

So it does not seem to be safe to rely on any well-defined behavior here.

How to disable Compatibility View in IE

In JSF I used:

<h:head>
    <f:facet name="first">
        <meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
    </f:facet>

    <!-- ... other meta tags ... -->

</h:head>

Open source PDF library for C/C++ application?

  • LibHaru seems to be used by many.

A non-open source approach is: PDF Creator Pilot which provides more language options including C++, C#, Delphi, ASP, ASP.NET, VB, VB.NET, VBScript, PHP and Python

AVD Manager - Cannot Create Android Virtual Device

you need to avoid spaces in the AVD name. & Select the "Skin" option.

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Quick Way to Implement Dictionary in C

I am surprised no one mentioned hsearch/hcreate set of libraries which although is not available on windows, but is mandated by POSIX, and therefore available in Linux / GNU systems.

The link has a simple and complete basic example that very well explains its usage.

It even has thread safe variant, is easy to use and very performant.

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

The DateTime::ToString() method has a string formatter that can be used to output datetime in any required format. See DateTime.ToString Method (String) for more information.

How do I combine 2 select statements into one?

select Status, * from WorkItems t1
where  exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
AND TimeStamp>'2009-02-12 18:00:00'

UNION

select 'DELETED', * from WorkItems t1
where  exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) 
AND TimeStamp>'2009-02-12 18:00:00'
AND NOT (BoolField05=1)

Perhaps that'd do the trick. I can't test it from here though, and I'm not sure what version of SQL you're working against.

how to access iFrame parent page using jquery?

yeah it works for me as well.

Note : we need to use window.parent.document

    $("button", window.parent.document).click(function()
    {
        alert("Functionality defined by def");
    });

"Cannot instantiate the type..."

You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();.

PostgreSQL - query from bash script as database user 'postgres'

The safest way to pass commands to psql in a script is by piping a string or passing a here-doc.

The man docs for the -c/--command option goes into more detail when it should be avoided.

   -c command
   --command=command
       Specifies that psql is to execute one command string, command, and then exit. This is useful in shell scripts. Start-up files (psqlrc and ~/.psqlrc)
       are ignored with this option.

       command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single
       backslash command. Thus you cannot mix SQL and psql meta-commands with this option. To achieve that, you could pipe the string into psql, for
       example: echo '\x \\ SELECT * FROM foo;' | psql. (\\ is the separator meta-command.)

       If the command string contains multiple SQL commands, they are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands
       included in the string to divide it into multiple transactions. This is different from the behavior when the same string is fed to psql's standard
       input. Also, only the result of the last SQL command is returned.

       Because of these legacy behaviors, putting more than one command in the -c string often has unexpected results. It's better to feed multiple
       commands to psql's standard input, either using echo as illustrated above, or via a shell here-document, for example:

           psql <<EOF
           \x
           SELECT * FROM foo;
           EOF

Does JSON syntax allow duplicate keys in an object?

I came across a similar question when dealing with an API that accepts both XML and JSON, but doesn't document how it would handle what you'd expect to be duplicate keys in the JSON accepted.

The following is a valid XML representation of your sample JSON:

<object>
  <a>x</a>
  <a>y</a>
</object>

When this is converted into JSON, you get the following:

{
  "object": {
    "a": [
      "x",
      "y"
    ]
  }
}

A natural mapping from a language that handles what you might call duplicate keys to another, can serve as a potential best practice reference here.

Hope that helps someone!

Retrieve specific commit from a remote Git repository

You only clone once, so if you already have a clone of the remote repository, pulling from it won't download everything again. Just indicate what branch you want to pull, or fetch the changes and checkout the commit you want.

Fetching from a new repository is very cheap in bandwidth, as it will only download the changes you don't have. Think in terms of Git making the right thing, with minimum load.

Git stores everything in .git folder. A commit can't be fetched and stored in isolation, it needs all its ancestors. They are interrelated.


To reduce download size you can however ask git to fetch only objects related to a specific branch or commit:

git fetch origin refs/heads/branch:refs/remotes/origin/branch

This will download only commits contained in remote branch branch (and only the ones that you miss), and store it in origin/branch. You can then merge or checkout.

You can also specify only a SHA1 commit:

git fetch origin 96de5297df870:refs/remotes/origin/foo-commit

This will download only the commit of the specified SHA-1 96de5297df870 (and its ancestors that you miss), and store it as (non-existing) remote branch origin/foo-commit.

How to reset index in a pandas dataframe?

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True)

If you don't want to reassign:

df.reset_index(drop=True, inplace=True)

setHintTextColor() in EditText

Seems that EditText apply the hintTextColor only if the text is empty. So simple solution will be like this

Editable text = mEditText.getText();
mEditText.setText(null);
mEditText.setHintTextColor(color);
mEditText.setText(text);

If you have multiple fields, you can extend the EditText and write a method which executes this logic and use that method instead.

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

OraOLEDB.Oracle provider is not registered on the local machine

My team would stumble upon this issue every now and then in random machines that we would try to install our platform in (we use oracle drivers 12c ver 12.2.0.4 but we came across this bug with other versions as well)

After quite a bit of experimentation we realized what was wrong:

Said machines would have apps that were using the machine-wide oracle drivers silently locking them and preventing the oracle driver-installer from working its magic when would attempt to upgrade/reinstall said oracle-drivers. The sneakiest "app" would be websites running in IIS and the like because these apps essentially auto-start on reboot. To counter this we do the following:

  1. Disable IIS from starting automagically on restart. Do the same for any other apps/services that auto-start themselves on reboot.
  2. Uninstall any previous Oracle driver and double-check that there are no traces left behind in registry or folders.
  3. Reboot the machine
  4. (Re)Install the Oracle drivers and re-enable IIS and other auto-start apps.
  5. Reboot the machine <- This is vital. Oracle's OLE DB drivers won't work unless you reboot the machine.

If this doesn't work then rinse repeat until the OLE DB drivers work. Hope this helps someone out there struggling to figure out what's going on.

TypeError: Router.use() requires middleware function but got a Object

If your are using express above 2.x, you have to declare app.router like below code. Please try to replace your code

app.use('/', routes);

with

app.use(app.router);
routes.initialize(app);

Please click here to get more details about app.router

Note:

app.router is depreciated in express 3.0+. If you are using express 3.0+, refer to Anirudh's answer below.

React img tag issue with url and class

var Hello = React.createClass({
    render: function() {
      return (
        <div className="divClass">
           <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.props.name}</span>
        </div>
      );
    }
});

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

I got this to work:

explicit conversion

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                    JsonSerializer serializer)
    {
        var jsonObj = serializer.Deserialize<List<SomeObject>>(reader);
        var conversion = jsonObj.ConvertAll((x) => x as ISomeObject);

        return conversion;
    }

PHP preg replace only allow numbers

Try this:

return preg_replace("/[^0-9]/", "",$c);

Maven plugin not using Eclipse's proxy settings

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">

     <proxies>
       <proxy>
          <active>true</active>
          <protocol>http</protocol>
          <host>proxy.somewhere.com</host>
          <port>8080</port>
          <username>proxyuser</username>
          <password>somepassword</password>
          <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
        </proxy>
      </proxies>

    </settings>

Window > Preferences > Maven > User Settings

enter image description here

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Efficiently counting the number of lines of a text file. (200mb+)

If you're under linux you can simply do:

number_of_lines = intval(trim(shell_exec("wc -l ".$file_name." | awk '{print $1}'")));

You just have to find the right command if you're using another OS

Regards

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

OkHttp Post Body as JSON

In okhttp v4.* I got it working that way


// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody

// ...

json : String = "..."

val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)

// go on with Request.Builder() etc

C# - Making a Process.Start wait until the process has start-up

You can also check if the started process is responsive or not by trying something like this: while(process.responding)

How can I get a file's size in C++?

#include <stdio.h>

#define MAXNUMBER 1024

int main()
{
    int i;
    char a[MAXNUMBER];

    FILE *fp = popen("du -b  /bin/bash", "r");

    while((a[i++] = getc(fp))!= 9)
        ;

    a[i] ='\0';

    printf(" a is %s\n", a);

    pclose(fp);
    return 0;
}  

HTH

What does "./" (dot slash) refer to in terms of an HTML file path location?

. is a shorthand for the current directory and is used in Linux and Unix to execute a compiled program in the current directory. That is why you don't see this used in Web Development much except by open source, non-Windows frameworks like Google Angular which was written by people stuck on open source platforms.

./ also resolves to the current directory and is atypical in Web but supported as a path in some open source frameworks. Because it resolves the same as no path to the current file directory its not used. Example: ./image.jpg = image.jpg. Again, this is a relic of Unix operating systems that need path resolutions like this to run executables and resolve paths for security reasons. Its not a typical web path. That is why this syntax is redundant.

../ is a traditional web path that goes one directory up

/ is the ROOT of your website

These path resolutions below are true...

./folder= folder this is always true in web path resolution

./file.html = file.html this is always true in web path resolution

./ = {no path} an empty path is the same as ./ in the web world

{no path} = / an empty path is the same as the web root if your file is in the root directory

./ = / ONLY if you are in the root folder

../ = / ONLY if you are one folder below the web root

Print second last column/field in awk

Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.

(
echo       | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1     | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2   | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 3 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
)

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

I had the same issue as all of our servers run older versions of MySQL. This can be solved by running a PHP script. Save this code to a file and run it entering the database name, user and password and it'll change the collation from utf8mb4/utf8mb4_unicode_ci to utf8/utf8_general_ci

<!DOCTYPE html>
<html>
<head>
  <title>DB-Convert</title>
  <style>
    body { font-family:"Courier New", Courier, monospace; }
  </style>
</head>
<body>

<h1>Convert your Database to utf8_general_ci!</h1>

<form action="db-convert.php" method="post">
  dbname: <input type="text" name="dbname"><br>
  dbuser: <input type="text" name="dbuser"><br>
  dbpass: <input type="text" name="dbpassword"><br>
  <input type="submit">
</form>

</body>
</html>
<?php
if ($_POST) {
  $dbname = $_POST['dbname'];
  $dbuser = $_POST['dbuser'];
  $dbpassword = $_POST['dbpassword'];

  $con = mysql_connect('localhost',$dbuser,$dbpassword);
  if(!$con) { echo "Cannot connect to the database ";die();}
  mysql_select_db($dbname);
  $result=mysql_query('show tables');
  while($tables = mysql_fetch_array($result)) {
          foreach ($tables as $key => $value) {
           mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
     }}
  echo "<script>alert('The collation of your database has been successfully changed!');</script>";
}

?>

RestSharp simple complete example

I managed to find a blog post on the subject, which links off to an open source project that implements RestSharp. Hopefully of some help to you.

http://dkdevelopment.net/2010/05/18/dropbox-api-and-restsharp-for-a-c-developer/ The blog post is a 2 parter, and the project is here: https://github.com/dkarzon/DropNet

It might help if you had a full example of what wasn't working. It's difficult to get context on how the client was set up if you don't provide the code.

When to use async false and async true in ajax function in jquery

  1. When async setting is set to false, a Synchronous call is made instead of an Asynchronous call.
  2. When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.
  3. for more information please refer this link

Is it possible to implement a Python for range loop without an iterator variable?

I generally agree with solutions given above. Namely with:

  1. Using underscore in for-loop (2 and more lines)
  2. Defining a normal while counter (3 and more lines)
  3. Declaring a custom class with __nonzero__ implementation (many more lines)

If one is to define an object as in #3 I would recommend implementing protocol for with keyword or apply contextlib.

Further I propose yet another solution. It is a 3 liner and is not of supreme elegance, but it uses itertools package and thus might be of an interest.

from itertools import (chain, repeat)

times = chain(repeat(True, 2), repeat(False))
while next(times):
    print 'do stuff!'

In these example 2 is the number of times to iterate the loop. chain is wrapping two repeat iterators, the first being limited but the second is infinite. Remember that these are true iterator objects, hence they do not require infinite memory. Obviously this is much slower then solution #1. Unless written as a part of a function it might require a clean up for times variable.

What’s the best way to load a JSONObject from a json text file?

Another way of doing the same could be using the Gson Class

String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);

This will give an object obtained after parsing the json string to work with.

Is there a simple way to remove unused dependencies from a maven pom.xml?

I had similar kind of problem and decided to write a script that removes dependencies for me. Using that I got over half of the dependencies away rather easily.

http://samulisiivonen.blogspot.com/2012/01/cleanin-up-maven-dependencies.html

What is %timeit in python?

I just wanted to add a very subtle point about %%timeit. Given it runs the "magics" on the cell, you'll get error...

UsageError: Line magic function %%timeit not found

...if there is any code/comment lines above %%timeit. In other words, ensure that %%timeit is the first command in your cell.

I know it's a small point all the experts will say duh to, but just wanted to add my half a cent for the young wizards starting out with magic tricks.

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

In your entity for that table, add the DatabaseGenerated attribute above the column for which identity insert is set:

Example:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TaskId { get; set; }

Is it possible to cast a Stream in Java 8?

This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast Stream<Object> to a Stream<Client>?

No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List<Object> is not a super type of List<String>, so you can't just cast a List<Object> to a List<String>.

Similar is the issue here. You can't cast Stream<Object> to Stream<Client>. Of course you can cast it indirectly like this:

Stream<Client> intStream = (Stream<Client>) (Stream<?>)stream;

but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream it is at runtime. Everything is just Stream.

BTW, what's wrong with your approach? Looks fine to me.

Exception of type 'System.OutOfMemoryException' was thrown. Why?

Perhaps you're not disposing of the previous connection/ result classes from the previous run which means their still hanging around in memory.

Plotting multiple time series on the same plot using ggplot()

I know this is old but it is still relevant. You can take advantage of reshape2::melt to change the dataframe into a more friendly structure for ggplot2.

Advantages:

  • allows you plot any number of lines
  • each line with a different color
  • adds a legend for each line
  • with only one call to ggplot/geom_line

Disadvantage:

  • an extra package(reshape2) required
  • melting is not so intuitive at first

For example:

jobsAFAM1 <- data.frame(
  data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
  Percent.Change = runif(5,1,100)
)

jobsAFAM2 <- data.frame(
  data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
  Percent.Change = runif(5,1,100)
)

jobsAFAM <- merge(jobsAFAM1, jobsAFAM2, by="data_date")

jobsAFAMMelted <- reshape2::melt(jobsAFAM, id.var='data_date')

ggplot(jobsAFAMMelted, aes(x=data_date, y=value, col=variable)) + geom_line()

enter image description here

Styling HTML email for Gmail

I agree with everyone who supports classes AND inline styles. You might have learned this by now, but if there is a single mistake in your style sheet, Gmail will disregard it.

You might think that your CSS is perfect, because you've done it so often, why would I have mistakes in my CSS? Run it through the CSS Validator (for example http://www.css-validator.org/) and see what happens. I did that after encountering some Gmail display issues, and to my surprise, several Microsoft Outlook specific style declarations showed up as mistakes.

Which made sense to me, so I removed them from the style sheet and put them into a only for Microsoft code block, like so:

<!--[if mso]>
<style type="text/css">
body, table, td, .mobile-text {
font-family: Arial, sans-serif !important;
}
</style>
<xml>
  <o:OfficeDocumentSettings>
    <o:AllowPNG/>
    <o:PixelsPerInch>96</o:PixelsPerInch>
  </o:OfficeDocumentSettings>
</xml>
<![endif]-->

This is just a simple example, but, who know, it might come in handy some time.

WPF ListView turn off selection

Below code disable Focus on ListViewItem

<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <ContentPresenter />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Swap DIV position with CSS only

In some cases you can just use the flex-box property order.

Very simple:

.flex-item {
    order: 2;
}

See: https://css-tricks.com/almanac/properties/o/order/

How to exclude a directory in find . command

For FreeBSD users:

 find . -name '*.js' -not -path '*exclude/this/dir*'

GitHub Error Message - Permission denied (publickey)

I was using github earlier for one of my php project. While using github, I was using ssh instead of https. I had my machine set up like that and every time I used to commit and push the code, it would ask me my rsa key password.

After some days, I stopped working on the php project and forgot my rsa password. Recently, I started working on a java project and moved to bitbucket. Since, I had forgotten the password and there is no way to recover it I guess, I decided to use the https(recommended) protocol for the new project and got the same error asked in the question.

How I solved it?

  1. Ran this command to tell my git to use https instead of ssh:

    git config --global url."https://".insteadOf git://
    
  2. Remove any remote if any

    git remote rm origin
    
  3. Redo everything from git init to git push and it works!

PS: I also un-installed ssh from my machine during the debug process thinking that, removing it will fix the problem. Yes I know!! :)

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

Alternatively if you want to grab the private and public keys from a PuTTY formated key file you can use puttygen on *nix systems. For most apt-based systems puttygen is part of the putty-tools package.

Outputting a private key from a PuTTY formated keyfile:

$ puttygen keyfile.pem -O private-openssh -o avdev.pvk

For the public key:

$ puttygen keyfile.pem -L

Writing MemoryStream to Response Object

First We Need To Write into our Memory Stream and then with the help of Memory Stream method "WriteTo" we can write to the Response of the Page as shown in the below code.

   MemoryStream filecontent = null;
   filecontent =//CommonUtility.ExportToPdf(inputXMLtoXSLT);(This will be your MemeoryStream Content)
   Response.ContentType = "image/pdf";
   string headerValue = string.Format("attachment; filename={0}", formName.ToUpper() + ".pdf");
   Response.AppendHeader("Content-Disposition", headerValue);

   filecontent.WriteTo(Response.OutputStream);

   Response.End();

FormName is the fileName given,This code will make the generated PDF file downloadable by invoking a PopUp.

Change selected value of kendo ui dropdownlist

It's possible to "natively" select by value:

dropdownlist.select(1);

How to define global variable in Google Apps Script

You might be better off using the Properties Service as you can use these as a kind of persistent global variable.

click 'file > project properties > project properties' to set a key value, or you can use

PropertiesService.getScriptProperties().setProperty('mykey', 'myvalue');

The data can be retrieved with

var myvalue = PropertiesService.getScriptProperties().getProperty('mykey');

Get last field using awk substr

Like 5 years late, I know, thanks for all the proposals, I used to do this the following way:

$ echo /home/parent/child1/child2/filename | rev | cut -d '/' -f1 | rev
filename

Glad to notice there are better manners

Looping from 1 to infinity in Python

If you're doing that in C, then your judgement there is as cloudy as it would be in Python :-)

For a loop that exits on a simple condition check at the start of each iteration, it's more usual (and clearer, in my opinion) to just do that in the looping construct itself. In other words, something like (if you need i after loop end):

int i = 0;
while (! thereIsAReasonToBreak(i)) {
    // do something
    i++;
}

or (if i can be scoped to just the loop):

for (int i = 0; ! thereIsAReasonToBreak(i); ++i) {
    // do something
}

That would translate to the Python equivalent:

i = 0
while not there_is_a_reason_to_break(i):
    # do something
    i += 1

Only if you need to exit in the middle of the loop somewhere (or if your condition is complex enough that it would render your looping statement far less readable) would you need to worry about breaking.

When your potential exit is a simple one at the start of the loop (as it appears to be here), it's usually better to encode the exit into the loop itself.

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

Using FileShare fixed my issue of opening file even if it is opened by another process.

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}

MySQL - ignore insert error: duplicate entry

Try creating a duplicate table, preferably a temporary table, without the unique constraint and do your bulk load into that table. Then select only the unique (DISTINCT) items from the temporary table and insert into the target table.

How do I check which version of NumPy I'm using?

import numpy
print numpy.__version__

How can I time a code segment for testing performance with Pythons timeit?

If you are profiling your code and can use IPython, it has the magic function %timeit.

%%timeit operates on cells.

In [2]: %timeit cos(3.14)
10000000 loops, best of 3: 160 ns per loop

In [3]: %%timeit
   ...: cos(3.14)
   ...: x = 2 + 3
   ...: 
10000000 loops, best of 3: 196 ns per loop

How to center body on a page?

You have to specify the width to the body for it to center on the page.

Or put all the content in the div and center it.

<body>
    <div>
    jhfgdfjh
    </div>
</body>?

div {
    margin: 0px auto;
    width:400px;
}

?

Vue.js—Difference between v-model and v-bind

There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.

In these cases, it's not a good idea to use either watchers or computed properties.

Instead, take your v-model and split it as above answer indicates

<input
   :value="something"
   @input="something = $event.target.value"
>

In practice, if you are decoupling your logic this way, you'll probably be calling a method.

This is what it would look like in a real world scenario:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
  <p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
  var app = new Vue({_x000D_
    el: "#app",_x000D_
    data: function(){_x000D_
      return {_x000D_
        extendedCost: 0,_x000D_
      }_x000D_
    },_x000D_
    methods: {_x000D_
      _onInputExtendedCost: function($event) {_x000D_
        this.extendedCost = parseInt($event.target.value);_x000D_
        // Go update other inputs here_x000D_
    }_x000D_
  }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Removing duplicate values from a PowerShell array

This is how you get unique from an array with two or more properties. The sort is vital and the key to getting it to work correctly. Otherwise you just get one item returned.

PowerShell Script:

$objects = @(
    [PSCustomObject] @{ Message = "1"; MachineName = "1" }
    [PSCustomObject] @{ Message = "2"; MachineName = "1" }
    [PSCustomObject] @{ Message = "3"; MachineName = "1" }
    [PSCustomObject] @{ Message = "4"; MachineName = "1" }
    [PSCustomObject] @{ Message = "5"; MachineName = "1" }
    [PSCustomObject] @{ Message = "1"; MachineName = "2" }
    [PSCustomObject] @{ Message = "2"; MachineName = "2" }
    [PSCustomObject] @{ Message = "3"; MachineName = "2" }
    [PSCustomObject] @{ Message = "4"; MachineName = "2" }
    [PSCustomObject] @{ Message = "5"; MachineName = "2" }
    [PSCustomObject] @{ Message = "1"; MachineName = "1" }
    [PSCustomObject] @{ Message = "2"; MachineName = "1" }
    [PSCustomObject] @{ Message = "3"; MachineName = "1" }
    [PSCustomObject] @{ Message = "4"; MachineName = "1" }
    [PSCustomObject] @{ Message = "5"; MachineName = "1" }
    [PSCustomObject] @{ Message = "1"; MachineName = "2" }
    [PSCustomObject] @{ Message = "2"; MachineName = "2" }
    [PSCustomObject] @{ Message = "3"; MachineName = "2" }
    [PSCustomObject] @{ Message = "4"; MachineName = "2" }
    [PSCustomObject] @{ Message = "5"; MachineName = "2" }
)

Write-Host "Sorted on both properties with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message,MachineName -Unique | Out-Host

Write-Host "Sorted on just Message with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message -Unique | Out-Host

Write-Host "Sorted on just MachineName with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property MachineName -Unique | Out-Host

Output:

Sorted on both properties with -Unique

Message MachineName
------- -----------
1       1          
1       2          
2       1          
2       2          
3       1          
3       2          
4       1          
4       2          
5       1          
5       2          


Sorted on just Message with -Unique

Message MachineName
------- -----------
1       1          
2       1          
3       1          
4       1          
5       2          


Sorted on just MachineName with -Unique

Message MachineName
------- -----------
1       1          
3       2  

Source: https://powershell.org/forums/topic/need-to-unique-based-on-multiple-properties/

Python regular expressions return true/false

You can use re.match() or re.search(). Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default). refer this

How to efficiently use try...catch blocks in PHP

There is no any problem to write multiple lines of execution withing a single try catch block like below

try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}

The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

try{
    install_engine();
    install_break();
    }
    catch(Exception $e){
    show_exception($e->getMessage());
    }
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}

How to press back button in android programmatically?

Simply add finish(); in your first class' (login activity) onPause(); method. that's all

how to check if input field is empty

This snippet will handle more than two checkboxes in case you decide to expand the form.

$("input[type=text]").keyup(function(){
    var count = 0, attr = "disabled", $sub = $("#submit"), $inputs = $("input[type=text]");  
    $inputs.each(function(){
        count += ($.trim($(this).val())) ? 1:0;
    });
    (count >= $inputs.length ) ? $sub.removeAttr(attr):$sub.attr(attr,attr);       
});

Working Example: http://jsfiddle.net/sr4gq/

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

When to use reinterpret_cast?

The meaning of reinterpret_cast is not defined by the C++ standard. Hence, in theory a reinterpret_cast could crash your program. In practice compilers try to do what you expect, which is to interpret the bits of what you are passing in as if they were the type you are casting to. If you know what the compilers you are going to use do with reinterpret_cast you can use it, but to say that it is portable would be lying.

For the case you describe, and pretty much any case where you might consider reinterpret_cast, you can use static_cast or some other alternative instead. Among other things the standard has this to say about what you can expect of static_cast (§5.2.9):

An rvalue of type “pointer to cv void” can be explicitly converted to a pointer to object type. A value of type pointer to object converted to “pointer to cv void” and back to the original pointer type will have its original value.

So for your use case, it seems fairly clear that the standardization committee intended for you to use static_cast.

Why am I getting this redefinition of class error?

You should wrap the .h file like so:

#ifndef Included_NameModel_H

#define Included_NameModel_H

// Existing code goes here

#endif

Extracting a parameter from a URL in WordPress

You can try this function

/**
 * Gets the request parameter.
 *
 * @param      string  $key      The query parameter
 * @param      string  $default  The default value to return if not found
 *
 * @return     string  The request parameter.
 */

function get_request_parameter( $key, $default = '' ) {
    // If not request set
    if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
        return $default;
    }

    // Set so process it
    return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}

Here is what is happening in the function

Here three things are happening.

  • First we check if the request key is present or not. If not, then just return a default value.
  • If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
  • Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.

All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

Material effect on button with background color

When you use android:background, you are replacing much of the styling and look and feel of a button with a blank color.

Update: As of the version 23.0.0 release of AppCompat, there is a new Widget.AppCompat.Button.Colored style which uses your theme's colorButtonNormal for the disabled color and colorAccent for the enabled color.

This allows you apply it to your button directly via

<Button
  ...
  style="@style/Widget.AppCompat.Button.Colored" />

If you need a custom colorButtonNormal or colorAccent, you can use a ThemeOverlay as explained in this pro-tip and android:theme on the button.

Previous Answer

You can use a drawable in your v21 directory for your background such as:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?attr/colorControlHighlight">
    <item android:drawable="?attr/colorPrimary"/>
</ripple>

This will ensure your background color is ?attr/colorPrimary and has the default ripple animation using the default ?attr/colorControlHighlight (which you can also set in your theme if you'd like).

Note: you'll have to create a custom selector for less than v21:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/primaryPressed" android:state_pressed="true"/>
    <item android:drawable="@color/primaryFocused" android:state_focused="true"/>
    <item android:drawable="@color/primary"/>
</selector>

Assuming you have some colors you'd like for the default, pressed, and focused state. Personally, I took a screenshot of a ripple midway through being selected and pulled the primary/focused state out of that.

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

How to declare a inline object with inline variables without a parent class

You can also do this:

var x = new object[] {
    new { firstName = "john", lastName = "walter" },
    new { brand = "BMW" }
};

And if they are the same anonymous type (firstName and lastName), you won't need to cast as object.

var y = new [] {
    new { firstName = "john", lastName = "walter" },
    new { firstName = "jill", lastName = "white" }
};

Java: String - add character n-times

You can use Guava's Strings.repeat method:

String existingString = ...
existingString += Strings.repeat("foo", n);

Simple Vim commands you wish you'd known earlier

Typing a line number followed by gg will take you to that line.

RedirectToAction with parameter

The following succeeded with asp.net core 2.1. It may apply elsewhere. The dictionary ControllerBase.ControllerContext.RouteData.Values is directly accessible and writable from within the action method. Perhaps this is the ultimate destination of the data in the other solutions. It also shows where the default routing data comes from.

[Route("/to/{email?}")]
public IActionResult ToAction(string email)
{
    return View("To", email);
}
[Route("/from")]
public IActionResult FromAction()
{
    ControllerContext.RouteData.Values.Add("email", "[email protected]");
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/[email protected]
}
[Route("/FromAnother/{email?}")]`
public IActionResult FromAnotherAction(string email)
{
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/<whatever the email param says>
         // no need to specify the route part explicitly
}

How to flush output of print function?

Using the -u command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the -u option. I usually use a custom stdout, like this:

class flushfile:
  def __init__(self, f):
    self.f = f

  def write(self, x):
    self.f.write(x)
    self.f.flush()

import sys
sys.stdout = flushfile(sys.stdout)

... Now all your print calls (which use sys.stdout implicitly), will be automatically flushed.

How to copy text from a div to clipboard

Adding the link as an Answer to draw more attention to Aaron Lavers' comment below the first answer.

This works like a charm - http://clipboardjs.com. Just add the clipboard.js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.

bool to int conversion

There seems to be no problem since the int to bool cast is done implicitly. This works in Microsoft Visual C++, GCC and Intel C++ compiler. No problem in either C or C++.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

Try the following steps:

  1. Make sure you have connectivity (you can browse) (This kind of error is usually due to connectivity with Internet)

  2. Download Maven and unzip it

  3. Create a JAVA_HOME System Variable

  4. Create an M2_HOME System Variable

  5. Add %JAVA_HOME%\bin;%M2_HOME%\bin; to your PATH variable

  6. Open a command window cmd. Check: mvn -v

  7. If you have a proxy, you will need to configure it

http://maven.apache.org/guides/mini/guide-proxies.html

  1. Make sure you have .m2/repository (erase all the folders and files below)

  2. If you are going to use Eclipse, You will need to create the settings.xml

Maven plugin in Eclipse - Settings.xml file is missing

You can see more detail in

http://maven.apache.org/ref/3.2.5/maven-settings/settings.html

Draw line in UIView

Maybe this is a bit late, but I want to add that there is a better way. Using UIView is simple, but relatively slow. This method overrides how the view draws itself and is faster:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0f);

    CGContextMoveToPoint(context, 0.0f, 0.0f); //start at this point

    CGContextAddLineToPoint(context, 20.0f, 20.0f); //draw to this point

    // and now draw the Path!
    CGContextStrokePath(context);
}

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

A function to convert null to string

Convert.ToString(object) converts to string. If the object is null, Convert.ToString converts it to an empty string.

Calling .ToString() on an object with a null value throws a System.NullReferenceException.

EDIT:

Two exceptions to the rules:

1) ConvertToString(string) on a null string will always return null.

2) ToString(Nullable<T>) on a null value will return "" .

Code Sample:

// 1) Objects:

object obj = null;

//string valX1 = obj.ToString();           // throws System.NullReferenceException !!!
string val1 = Convert.ToString(obj);    

Console.WriteLine(val1 == ""); // True
Console.WriteLine(val1 == null); // False


// 2) Strings

String str = null;
//string valX2 = str.ToString();    // throws System.NullReferenceException !!!
string val2 = Convert.ToString(str); 

Console.WriteLine(val2 == ""); // False
Console.WriteLine(val2 == null); // True            


// 3) Nullable types:

long? num = null;
string val3 = num.ToString();  // ok, no error

Console.WriteLine(num == null); // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False 

val3 = Convert.ToString(num);  

Console.WriteLine(num == null);  // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False

How to count the number of rows in excel with data?

Found this approach on another site. It works with the new larger sizes of Excel and doesn't require you to hardcode the max number of rows and columns.

iLastRow = Cells(Rows.Count, "a").End(xlUp).Row
iLastCol = Cells(i, Columns.Count).End(xlToLeft).Column

Thanks to mudraker in Melborne, Australia

How do you represent a JSON array of strings?

String strJson="{\"Employee\":
[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},
{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},
{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";

This is an example of a JSON string with Employee as object, then multiple strings and values in an array as a reference to @cregox...

A bit complicated but can explain a lot in a single JSON string.

How do I conditionally apply CSS styles in AngularJS?

There is one more option that I recently discovered that some people may find useful because it allows you to change a CSS rule within a style element - thus avoiding the need for repeated use of an angular directive such as ng-style, ng-class, ng-show, ng-hide, ng-animate, and others.

This option makes use of a service with service variables which are set by a controller and watched by an attribute-directive I call "custom-style". This strategy could be used in many different ways, and I attempted to provide some general guidance with this fiddle.

var app = angular.module('myApp', ['ui.bootstrap']);
app.service('MainService', function(){
    var vm = this;
});
app.controller('MainCtrl', function(MainService){
    var vm = this;
    vm.ms = MainService;
});
app.directive('customStyle', function(MainService){
    return {
        restrict : 'A',
        link : function(scope, element, attr){
            var style = angular.element('<style></style>');
            element.append(style);
            scope.$watch(function(){ return MainService.theme; },
                function(){
                    var css = '';
                    angular.forEach(MainService.theme, function(selector, key){
                        angular.forEach(MainService.theme[key], function(val, k){
                            css += key + ' { '+k+' : '+val+'} ';
                        });                        
                    });
                    style.html(css);
                }, true);
        }
    };
});

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Transfer data between databases with PostgreSQL

  1. If your source and target database resides in the same local machine, you can use:

Note:- Sourcedb already exists in your database.

CREATE DATABASE targetdb WITH TEMPLATE sourcedb;

This statement copies the sourcedb to the targetdb.

  1. If your source and target databases resides on different servers, you can use following steps:

Step 1:- Dump the source database to a file.

pg_dump -U postgres -O sourcedb sourcedb.sql

Note:- Here postgres is the username so change the name accordingly.

Step 2:- Copy the dump file to the remote server.

Step 3:- Create a new database in the remote server

CREATE DATABASE targetdb;

Step 4:- Restore the dump file on the remote server

psql -U postgres -d targetdb -f sourcedb.sql

(pg_dump is a standalone application (i.e., something you run in a shell/command-line) and not an Postgres/SQL command.)

This should do it.

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

The '-Wait' option seemed to block for me even though my process had finished.

I tried Adrian's solution and it works. But I used Wait-Process instead of relying on a side effect of retrieving the process handle.

So:

$proc = Start-Process $msbuild -PassThru
Wait-Process -InputObject $proc

if ($proc.ExitCode -ne 0) {
    Write-Warning "$_ exited with status code $($proc.ExitCode)"
}

Eslint: How to disable "unexpected console statement" in Node.js?

In package.json you will find an eslintConfig line. Your 'rules' line can go in there like this:

  "eslintConfig": {
   ...
    "extends": [
      "eslint:recommended"
    ],
    "rules": {
      "no-console": "off"
    },
   ...
  },

SQL error "ORA-01722: invalid number"

You can always use TO_NUMBER() function in order to remove this error.This can be included as INSERT INTO employees phone_number values(TO_NUMBER('0419 853 694');

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

Convert normal date to unix timestamp

parseInt((new Date('2012.08.10').getTime() / 1000).toFixed(0))

It's important to add the toFixed(0) to remove any decimals when dividing by 1000 to convert from milliseconds to seconds.

The .getTime() function returns the timestamp in milliseconds, but true unix timestamps are always in seconds.

How can I rollback an UPDATE query in SQL server 2005?

As already stated there is nothing you can do except restore from a backup. At least now you will have learned to always wrap statements in a transaction to see what happens before you decide to commit. Also, if you don't have a backup of your database this will also teach you to make regular backups of your database.

While we haven't been much help for your imediate problem...hopefully these answers will ensure you don't run into this problem again in the future.

How can I check if a View exists in a Database?

if exists (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') )

Find the nth occurrence of substring in a string

Def:

def get_first_N_words(mytext, mylen = 3):
    mylist = list(mytext.split())
    if len(mylist)>=mylen: return ' '.join(mylist[:mylen])

To use:

get_first_N_words('  One Two Three Four ' , 3)

Output:

'One Two Three'

Getting a list of files in a directory with a glob

stringWithFileSystemRepresentation doesn't appear to be available in iOS.

Java List.add() UnsupportedOperationException

Form the Inheritance concept, If some perticular method is not available in the current class it will search for that method in super classes. If available it executes.

It executes AbstractList<E> class add() method which throws UnsupportedOperationException.


When you are converting from an Array to a Collection Obejct. i.e., array-based to collection-based API then it is going to provide you fixed-size collection object, because Array's behaviour is of Fixed size.

java.util.Arrays.asList( T... a )

Souce samples for conformation.

public class Arrays {
    public static <T> List<T> asList(T... a) {
        return new java.util.Arrays.ArrayList.ArrayList<>(a); // Arrays Inner Class ArrayList
    }
    //...
    private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable {
        //...
    }
}
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }

    public Iterator<E> iterator() {
        return new Itr();
    }
    private class Itr implements Iterator<E> {
        //...
    }

    public ListIterator<E> listIterator() {
        return listIterator(0);
    }
    private class ListItr extends Itr implements ListIterator<E> {
        //...
    }
}

Form the above Source you may observe that java.util.Arrays.ArrayList class doesn't @Override add(index, element), set(index, element), remove(index). So, From inheritance it executes super AbstractList<E> class add() function which throws UnsupportedOperationException.

As AbstractList<E> is an abstract class it provides the implementation to iterator() and listIterator(). So, that we can iterate over the list object.

List<String> list_of_Arrays = Arrays.asList(new String[] { "a", "b" ,"c"});

try {
    list_of_Arrays.add("Yashwanth.M");
} catch(java.lang.UnsupportedOperationException e) {
    System.out.println("List Interface executes AbstractList add() fucntion which throws UnsupportedOperationException.");
}
System.out.println("Arrays ? List : " + list_of_Arrays);

Iterator<String> iterator = list_of_Arrays.iterator();
while (iterator.hasNext()) System.out.println("Iteration : " + iterator.next() );

ListIterator<String> listIterator = list_of_Arrays.listIterator();
while (listIterator.hasNext())    System.out.println("Forward  iteration : " + listIterator.next() );
while(listIterator.hasPrevious()) System.out.println("Backward iteration : " + listIterator.previous());

You can even create Fixed-Size array form Collections class Collections.unmodifiableList(list);

Sample Source:

public class Collections {
    public static <T> List<T> unmodifiableList(List<? extends T> list) {
        return (list instanceof RandomAccess ?
                new UnmodifiableRandomAccessList<>(list) :
                new UnmodifiableList<>(list));
    }
}

A Collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.

@see also

INNER JOIN in UPDATE sql for DB2

Joins in update statements are non-standard and not supported by all vendors. What you're trying to do can be accomplished with a sub-select:

update
  file1
set
  firstfield = (select 'stuff' concat something from file2 where substr(file1.field1, 10, 20) = substr(file2.xxx,1,10) )
where
  file1.foo like 'BLAH%'

How do I decrease the size of my sql server log file?

Welcome to the fickle world of SQL Server log management.

SOMETHING is wrong, though I don't think anyone will be able to tell you more than that without some additional information. For example, has this database ever been used for Transactional SQL Server replication? This can cause issues like this if a transaction hasn't been replicated to a subscriber.

In the interim, this should at least allow you to kill the log file:

  1. Perform a full backup of your database. Don't skip this. Really.
  2. Change the backup method of your database to "Simple"
  3. Open a query window and enter "checkpoint" and execute
  4. Perform another backup of the database
  5. Change the backup method of your database back to "Full" (or whatever it was, if it wasn't already Simple)
  6. Perform a final full backup of the database.

You should now be able to shrink the files (if performing the backup didn't do that for you).

Good luck!

Downgrade npm to an older version

Even I run npm install -g npm@4, it is not ok for me.

Finally, I download and install the old node.js version.

https://nodejs.org/download/release/v7.10.1/

It is npm version 4.

You can choose any version here https://nodejs.org/download/release/

How can I check whether a numpy array is empty or not?

http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2

NumPy's main object is the homogeneous multidimensional array. In Numpy dimensions are called axes. The number of axes is rank. Numpy's array class is called ndarray. It is also known by the alias array. The more important attributes of an ndarray object are:

ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.

ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.

How do I use a pipe to redirect the output of one command to the input of another?

You can also run exactly same command at Cmd.exe command-line using PowerShell. I'd go with this approach for simplicity...

C:\>PowerShell -Command "temperature | prismcom.exe usb"

Please read up on Understanding the Windows PowerShell Pipeline

You can also type in C:\>PowerShell at the command-line and it'll put you in PS C:\> mode instanctly, where you can directly start writing PS.

How to find and replace with regex in excel

Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

To answer your question:

  1. Copy the data from Excel and paste into Google Sheets
  2. Use the find and replace dialog with regex
  3. Copy the data from Google Sheets and paste back into Excel

Controller 'ngModel', required by directive '...', can't be found

As described here: Angular NgModelController, you should provide the <input with the required controller ngModel

<input submit-required="true" ng-model="user.Name"></input>

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

The Network Adapter could not establish the connection when connecting with Oracle DB

Take a look at this post on Java Ranch:

http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could

"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."

Sorting a vector in descending order

With c++14 you can do this:

std::sort(numbers.begin(), numbers.end(), std::greater<>());

Rounding numbers to 2 digits after comma

Though we have many answers here with plenty of useful suggestions, each of them still misses some steps.
So here is a complete solution wrapped into small function:

function roundToTwoDigitsAfterComma(floatNumber) {
    return parseFloat((Math.round(floatNumber * 100) / 100).toFixed(2));
}

Just in case you are interested how this works:

  1. Multiple with 100 and then do round to keep precision of 2 digits after comma
  2. Divide back into 100 and use toFixed(2) to keep 2 digits after comma and throw other unuseful part
  3. Convert it back to float by using parseFloat() function as toFixed(2) returns string instead

Note: If you keep last 2 digits after comma because of working with monetary values, and doing financial calculations keep in mind that it's not a good idea and you'd better use integer values instead.

C# - using List<T>.Find() with custom objects

Previous answers don't account for the fact that you've overloaded the equals operator and are using that to test for the sought element. In that case, your code would look like this:

list.Find(x => x == objectToFind);

Or, if you don't like lambda syntax, and have overriden object.Equals(object) or have implemented IEquatable<T>, you could do this:

list.Find(objectToFind.Equals);

Prevent text selection after double click

Old thread, but I came up with a solution that I believe is cleaner since it does not disable every even bound to the object, and only prevent random and unwanted text selections on the page. It is straightforward, and works well for me. Here is an example; I want to prevent text-selection when I click several time on the object with the class "arrow-right":

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH !

Select rows of a matrix that meet a condition

Subset is a very slow function , and I personally find it useless.

I assume you have a data.frame, array, matrix called Mat with A, B, C as column names; then all you need to do is:

  • In the case of one condition on one column, lets say column A

    Mat[which(Mat[,'A'] == 10), ]
    

In the case of multiple conditions on different column, you can create a dummy variable. Suppose the conditions are A = 10, B = 5, and C > 2, then we have:

    aux = which(Mat[,'A'] == 10)
    aux = aux[which(Mat[aux,'B'] == 5)]
    aux = aux[which(Mat[aux,'C'] > 2)]
    Mat[aux, ]

By testing the speed advantage with system.time, the which method is 10x faster than the subset method.

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

I've discovered similar problems with the openjdk-6-jre and openjdk-6-jre-headless packages in Ubuntu.

My problem was solved by purging the openjdk-6-jre and openjdk-6-jre-headless packages and re-installing. The alternatives are only updated on a fresh install of the openjdk-6-jre and openjdk-6-jre-headless packages.

Below is a sample of installing after purging:

aptitude purge openjdk-6-jre openjdk-6-jre-headless # to ensure no configuration exists
aptitude install --without-recommends openjdk-6-jre # Installing without some extras
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
  ca-certificates-java{a} java-common{a} libavahi-client3{a} libavahi-common-data{a} libavahi-common3{a} libcups2{a} libflac8{a} libgif4{a} libnspr4-0d{a} libnss3-1d{a} libogg0{a} libpulse0{a} libsndfile1{a} libvorbis0a{a} libvorbisenc2{a} libxi6{a} libxtst6{a}
  openjdk-6-jre openjdk-6-jre-headless{a} openjdk-6-jre-lib{a} tzdata-java{a}
The following packages are RECOMMENDED but will NOT be installed:
  icedtea-6-jre-cacao icedtea-netx ttf-dejavu-extra
0 packages upgraded, 21 newly installed, 0 to remove and 119 not upgraded.
Need to get 0B/34.5MB of archives. After unpacking 97.6MB will be used.
Do you want to continue? [Y/n/?]
Writing extended state information... Done
Selecting previously deselected package openjdk-6-jre-lib.
(Reading database ... 62267 files and directories currently installed.)
Unpacking openjdk-6-jre-lib (from .../openjdk-6-jre-lib_6b24-1.11.5-0ubuntu1~10.04.2_all.deb) ...
...
Processing triggers for man-db ...
Setting up tzdata-java (2012e-0ubuntu0.10.04) ...
...
Setting up openjdk-6-jre-headless (6b24-1.11.5-0ubuntu1~10.04.2) ...
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/java to provide /usr/bin/java (java) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/keytool to provide /usr/bin/keytool (keytool) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/pack200 to provide /usr/bin/pack200 (pack200) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/rmid to provide /usr/bin/rmid (rmid) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/rmiregistry to provide /usr/bin/rmiregistry (rmiregistry) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/unpack200 to provide /usr/bin/unpack200 (unpack200) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/orbd to provide /usr/bin/orbd (orbd) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/servertool to provide /usr/bin/servertool (servertool) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/tnameserv to provide /usr/bin/tnameserv (tnameserv) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/lib/jexec to provide /usr/bin/jexec (jexec) in auto mode.
Setting up openjdk-6-jre (6b24-1.11.5-0ubuntu1~10.04.2) ...
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/policytool to provide /usr/bin/policytool (policytool) in auto mode.
...

You can see above that update-alternatives is run to set up links for the various Java binaries.

After this install, there are also links in /usr/bin, links in /etc/alternatives, and files for each binary in /var/lib/dpkg/alternatives.

ls -l /usr/bin/java /etc/alternatives/java /var/lib/dpkg/alternatives/java
lrwxrwxrwx 1 root root  40 2013-01-16 14:44 /etc/alternatives/java -> /usr/lib/jvm/java-6-openjdk/jre/bin/java
lrwxrwxrwx 1 root root  22 2013-01-16 14:44 /usr/bin/java -> /etc/alternatives/java
-rw-r--r-- 1 root root 158 2013-01-16 14:44 /var/lib/dpkg/alternatives/java

Let's contast this with installing without purging.

aptitude remove openjdk-6-jre
aptitude install --without-recommends openjdk-6-jre
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
  ca-certificates-java{a} java-common{a} libavahi-client3{a} libavahi-common-data{a} libavahi-common3{a} libcups2{a} libflac8{a} libgif4{a} libnspr4-0d{a} libnss3-1d{a} libogg0{a} libpulse0{a} libsndfile1{a} libvorbis0a{a} libvorbisenc2{a} libxi6{a} libxtst6{a}
  openjdk-6-jre openjdk-6-jre-headless{a} openjdk-6-jre-lib{a} tzdata-java{a}
The following packages are RECOMMENDED but will NOT be installed:
  icedtea-6-jre-cacao icedtea-netx ttf-dejavu-extra
0 packages upgraded, 21 newly installed, 0 to remove and 119 not upgraded.
Need to get 0B/34.5MB of archives. After unpacking 97.6MB will be used.
Do you want to continue? [Y/n/?]
Writing extended state information... Done
Selecting previously deselected package openjdk-6-jre-lib.
(Reading database ... 62293 files and directories currently installed.)
Unpacking openjdk-6-jre-lib (from .../openjdk-6-jre-lib_6b24-1.11.5-0ubuntu1~10.04.2_all.deb) ...
...
Processing triggers for man-db ...
...
Setting up openjdk-6-jre-headless (6b24-1.11.5-0ubuntu1~10.04.2) ...

Setting up openjdk-6-jre (6b24-1.11.5-0ubuntu1~10.04.2) ...
...

As you see, update-alternatives is not triggered.

After this install, there are no files for the Java binaries in /var/lib/dpkg/alternatives, no links in /etc/alternatives, and no links in /usr/bin.

The removal of the files in /var/lib/dpkg/alternatives also breaks update-java-alternatives.

Is 'bool' a basic datatype in C++?

Yes, bool is a built-in type.

WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.

How to get correct timestamp in C#

For UTC:

string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);

For local system:

string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);

Python CSV error: line contains NULL byte

One case is that - If the CSV file contains empty rows this error may show up. Check for row is necessary before we proceed to write or read.

for row in csvreader:
        if (row):       
            do something

I solved my issue by adding this check in the code.

Interfaces — What's the point?

In the absence of duck typing as you can use it in Python, C# relies on interfaces to provide abstractions. If the dependencies of a class were all concrete types, you could not pass in any other type - using interfaces you can pass in any type that implements the interface.

How to create Custom Ratings bar in Android

The following code works:

@Override
protected synchronized void onDraw(Canvas canvas)
{
    int stars = getNumStars();
    float rating = getRating();
    try
    {
        bitmapWidth = getWidth() / stars;
    }
    catch (Exception e)
    {
        bitmapWidth = getWidth();
    }
    float x = 0;

    for (int i = 0; i < stars; i++)
    {
        Bitmap bitmap;
        Resources res = getResources();
        Paint paint = new Paint();

        if ((int) rating > i)
        {
            bitmap = BitmapFactory.decodeResource(res, starColor);
        }
        else
        {
            bitmap = BitmapFactory.decodeResource(res, starDefault);
        }
        Bitmap scaled = Bitmap.createScaledBitmap(bitmap, getHeight(), getHeight(), true);
        canvas.drawBitmap(scaled, x, 0, paint);
        canvas.save();
        x += bitmapWidth;
    }

    super.onDraw(canvas);
}

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

How to count number of files in each directory?

You could arrange to find all the files, remove the file names, leaving you a line containing just the directory name for each file, and then count the number of times each directory appears:

find . -type f |
sed 's%/[^/]*$%%' |
sort |
uniq -c

The only gotcha in this is if you have any file names or directory names containing a newline character, which is fairly unlikely. If you really have to worry about newlines in file names or directory names, I suggest you find them, and fix them so they don't contain newlines (and quietly persuade the guilty party of the error of their ways).


If you're interested in the count of the files in each sub-directory of the current directory, counting any files in any sub-directories along with the files in the immediate sub-directory, then I'd adapt the sed command to print only the top-level directory:

find . -type f |
sed -e 's%^\(\./[^/]*/\).*$%\1%' -e 's%^\.\/[^/]*$%./%' |
sort |
uniq -c

The first pattern captures the start of the name, the dot, the slash, the name up to the next slash and the slash, and replaces the line with just the first part, so:

./dir1/dir2/file1

is replaced by

./dir1/

The second replace captures the files directly in the current directory; they don't have a slash at the end, and those are replace by ./. The sort and count then works on just the number of names.

Function for Factorial in Python

Non-recursive solution, no imports:

def factorial(x):
    return eval(' * '.join(map(str, range(1, x + 1))))

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

FragmentStatePagerAdapter:

  • with FragmentStatePagerAdapter,your unneeded fragment is destroyed.A transaction is committed to completely remove the fragment from your activity's FragmentManager.

  • The state in FragmentStatePagerAdapter comes from the fact that it will save out your fragment's Bundle from savedInstanceState when it is destroyed.When the user navigates back,the new fragment will be restored using the fragment's state.

FragmentPagerAdapter:

  • By comparision FragmentPagerAdapter does nothing of the kind.When the fragment is no longer needed.FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).

  • This destroy's the fragment's view but leaves the fragment's instance alive in the FragmentManager.so the fragments created in the FragmentPagerAdapter are never destroyed.

Python Function to test ping

It looks like you want the return keyword

def check_ping():
    hostname = "taylor"
    response = os.system("ping -c 1 " + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
    else:
        pingstatus = "Network Error"

    return pingstatus

You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:

pingstatus = check_ping()

NOTE: ping -c is for Linux, for Windows use ping -n

Some info on python functions:

http://www.tutorialspoint.com/python/python_functions.htm

http://www.learnpython.org/en/Functions

It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals. I recommend investigating Udacity.com and codeacademy.com

Listing files in a specific "folder" of a AWS S3 bucket

If your goal is only to take the files and not the folder, the approach I made was to use the file size as a filter. This property is the current size of the file hosted by AWS. All the folders return 0 in that property. The following is a C# code using linq but it shouldn't be hard to translate to Java.

var amazonClient = new AmazonS3Client(key, secretKey, region);
var listObjectsRequest= new ListObjectsRequest
            {
                BucketName = 'someBucketName',
                Delimiter = 'someDelimiter',
                Prefix = 'somePrefix'
            };
var objects = amazonClient.ListObjects(listObjectsRequest);
var objectsInFolder = objects.S3Objects.Where(file => file.Size > 0).ToList();

MongoDB: Is it possible to make a case-insensitive query?

db.zipcodes.find({city : "NEW YORK"}); // Case-sensitive
db.zipcodes.find({city : /NEW york/i}); // Note the 'i' flag for case-insensitivity

SQL, Postgres OIDs, What are they and why are they useful?

OIDs being phased out

The core team responsible for Postgres is gradually phasing out OIDs.

Postgres 12 removes special behavior of OID columns

The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:

  • CREATE TABLE … WITH OIDS command
  • default_with_oids (boolean) compatibility setting

The data type OID remains in Postgres 12. You can explicitly create a column of the type OID.

After migrating to Postgres 12, any optionally-defined system column oid will no longer be invisible by default. Performing a SELECT * will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.

REST URI convention - Singular or plural name of resource while creating it

Singular

Convenience Things can have irregular plural names. Sometimes they don't have one. But Singular names are always there.

e.g. CustomerAddress over CustomerAddresses

Consider this related resource.

This /order/12/orderdetail/12 is more readable and logical than /orders/12/orderdetails/4.

Database Tables

A resource represents an entity like a database table. It should have a logical singular name. Here's the answer over table names.

Class Mapping

Classes are always singular. ORM tools generate tables with the same names as class names. As more and more tools are being used, singular names are becoming a standard.

Read more about A REST API Developer's Dilemma

For things without singular names

In the case of trousers and sunglasses, they don't seem to have a singular counterpart. They are commonly known and they appear to be singular by use. Like a pair of shoes. Think about naming the class file Shoe or Shoes. Here these names must be considered as a singular entity by their use. You don't see anyone buying a single shoe to have the URL as

/shoe/23

We have to see Shoes as a singular entity.

Reference: Top 6 REST Naming Best Practices

Composer Warning: openssl extension is missing. How to enable in WAMP

I had the same problem even though openssl was enabled. The issue was that the Composer installer was looking at this config file:

C:\wamp\bin\php\php5.4.3\php.ini

But the config file that's loaded is actually here:

C:\wamp\bin\apache\apache2.2.22\bin\php.ini

So I just had to uncomment it in the first php.ini file and that did the trick. This is how WAMP was installed on my machine by default. I didn't go changing anything, so this will probably happen to others as well. This is basically the same as Augie Gardner's answer above, but I just wanted to point out that you might have two php.ini files.

Errno 13 Permission denied Python

If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.

Python Key Error=0 - Can't find Dict error in code

It only comes when your list or dictionary not available in the local function.

Django - iterate number in for loop of a template

{% for days in days_list %}
    <h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

or if you want to start from 0

{% for days in days_list %}
        <h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
    {% endfor %}

how to know status of currently running jobs

This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.

   WITH
    CTE_Sysession (AgentStartDate)
    AS 
    (
        SELECT MAX(AGENT_START_DATE) AS AgentStartDate FROM MSDB.DBO.SYSSESSIONS
    )   
SELECT sjob.name AS JobName
        ,CASE 
            WHEN SJOB.enabled = 1 THEN 'Enabled'
            WHEN sjob.enabled = 0 THEN 'Disabled'
            END AS JobEnabled
        ,sjob.description AS JobDescription
        ,CASE 
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL  THEN 'Running'
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
            WHEN HIST.run_status = 0 THEN 'Failed'
            WHEN HIST.run_status = 3 THEN 'Canceled'
        END AS JobActivity
        ,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
        ,hist.run_date AS JobRunDate
        ,run_DURATION/10000 AS Hours
        ,(run_DURATION%10000)/100 AS Minutes 
        ,(run_DURATION%10000)%100 AS Seconds
        ,hist.run_time AS JobRunTime 
        ,hist.run_duration AS JobRunDuration
        ,'tulsql11\dba' AS JobServer
        ,act.start_execution_date AS JobStartDate
        ,act.last_executed_step_id AS JobLastExecutedStep
        ,act.last_executed_step_date AS JobExecutedStepDate
        ,act.stop_execution_date AS JobStopDate
        ,act.next_scheduled_run_date AS JobNextRunDate
        ,sjob.date_created AS JobCreated
        ,sjob.date_modified AS JobModified      
            FROM MSDB.DBO.syssessions AS SYS1
        INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
        JOIN  msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
        JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
        LEFT JOIN  msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
        WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
        ORDER BY ACT.start_execution_date DESC

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

How to add conditional attribute in Angular 2?

Inline-Maps are handy, too.

They're a little more explicit & readable as well.

[class]="{ 'true': 'active', 'false': 'inactive', 'true&false': 'some-other-class' }[ trinaryBoolean ]"

Just another way of accomplishing the same thing, in case you don't like the ternary syntax or ngIfs (etc).

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You can use JavaScript as well, in case the textfield is dithered.

WebDriver driver=new FirefoxDriver();
driver.get("http://localhost/login.do");
driver.manage().window().maximize();
RemoteWebDriver r=(RemoteWebDriver) driver;
String s1="document.getElementById('username').value='admin'";
r.executeScript(s1);

How to install latest version of Node using Brew

If you have installed current node via Homebrew, just use these commands.

brew update
brew upgrade node

Check node version by

node -v

How do I check the difference, in seconds, between two dates?

We have function total_seconds() with Python 2.7 Please see below code for python 2.6

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)

pdftk compression option

Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook setting for gs. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.

pdftk compress:

no change in size
bookmarks TOC are gone

gs screen:

takes a ridiculously long time and 100% CPU
errors:
    sfopen: gs_parse_file_name failed.                                 ? 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone

gs printer:

takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone

gs ebook:

errors:
    sfopen: gs_parse_file_name failed.
      ./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone

qpdf --linearize:

very fast, a few seconds
no size change
bookmarks TOC are gone

pdf2ps:

took very long time
output_pdf2ps.ps 74.8MB-->331.6MB

ps2pdf:

pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone

How do I check if a string is a number (float)?

For strings of non-numbers, try: except: is actually slower than regular expressions. For strings of valid numbers, regex is slower. So, the appropriate method depends on your input.

If you find that you are in a performance bind, you can use a new third-party module called fastnumbers that provides a function called isfloat. Full disclosure, I am the author. I have included its results in the timings below.


from __future__ import print_function
import timeit

prep_base = '''\
x = 'invalid'
y = '5402'
z = '4.754e3'
'''

prep_try_method = '''\
def is_number_try(val):
    try:
        float(val)
        return True
    except ValueError:
        return False

'''

prep_re_method = '''\
import re
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number_re(val):
    return bool(float_match(val))

'''

fn_method = '''\
from fastnumbers import isfloat

'''

print('Try with non-number strings', timeit.timeit('is_number_try(x)',
    prep_base + prep_try_method), 'seconds')
print('Try with integer strings', timeit.timeit('is_number_try(y)',
    prep_base + prep_try_method), 'seconds')
print('Try with float strings', timeit.timeit('is_number_try(z)',
    prep_base + prep_try_method), 'seconds')
print()
print('Regex with non-number strings', timeit.timeit('is_number_re(x)',
    prep_base + prep_re_method), 'seconds')
print('Regex with integer strings', timeit.timeit('is_number_re(y)',
    prep_base + prep_re_method), 'seconds')
print('Regex with float strings', timeit.timeit('is_number_re(z)',
    prep_base + prep_re_method), 'seconds')
print()
print('fastnumbers with non-number strings', timeit.timeit('isfloat(x)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print('fastnumbers with integer strings', timeit.timeit('isfloat(y)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print('fastnumbers with float strings', timeit.timeit('isfloat(z)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print()

Try with non-number strings 2.39108395576 seconds
Try with integer strings 0.375686168671 seconds
Try with float strings 0.369210958481 seconds

Regex with non-number strings 0.748660802841 seconds
Regex with integer strings 1.02021503448 seconds
Regex with float strings 1.08564686775 seconds

fastnumbers with non-number strings 0.174362897873 seconds
fastnumbers with integer strings 0.179651021957 seconds
fastnumbers with float strings 0.20222902298 seconds

As you can see

  • try: except: was fast for numeric input but very slow for an invalid input
  • regex is very efficient when the input is invalid
  • fastnumbers wins in both cases

EnterKey to press button in VBA Userform

Here you can simply use:

SendKeys "{ENTER}" at the end of code linked to the Username field.

And so you can skip pressing ENTER Key once (one time).
And as a result, the next button ("Log In" button here) will be activated. And when you press ENTER once (your desired outcome), It will run code which is linked with "Log In" button.