Programs & Examples On #Preg replace callback

preg_replace_callback() is a PHP function that uses regular expressions to find substrings and a PHP callback function to perform the replacement.

Replace preg_replace() e modifier with preg_replace_callback

In a regular expression, you can "capture" parts of the matched string with (brackets); in this case, you are capturing the (^|_) and ([a-z]) parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.

The /e modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'. It then (effectively) runs eval to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval in an insecure way).

The preg_replace_callback function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1', you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }, the first back-reference is $matches[1] inside that function.

So a /e argument of

'do_stuff(\\1) . "and" . do_stuff(\\2)'

could become a callback of

function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }

Or in your case

'strtoupper("\\2")'

could become

function($m) { return strtoupper($m[2]); }

Note that $m and $matches are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method), as with any callback in PHP, e.g.

function stuffy_callback($things) {
    return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');

As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was

'do_stuff(\\1, $foo)'

then the new callback might look like

function($m) use ($foo) { return do_stuff($m[1], $foo); }

Gotchas

  • Use of preg_replace_callback is instead of the /e modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei would become /blah(.*)blah/mi.
  • The /e modifier used a variant of addslashes() internally on the arguments, so some replacements used stripslashes() to remove it; in most cases, you probably want to remove the call to stripslashes from your new callback.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

How do I get logs/details of ansible-playbook module executions?

Ansible command-line help, such as ansible-playbook --help shows how to increase output verbosity by setting the verbose mode (-v) to more verbosity (-vvv) or to connection debugging verbosity (-vvvv). This should give you some of the details you're after in stdout, which you can then be logged.

Image encryption/decryption using AES256 symmetric block ciphers

Try with the below code it`s working for me.

public static String decrypt(String encrypted) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    byte[] key = your Key in byte array;
    byte[] input = salt in byte array;

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(input);
    Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    ecipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);

    byte[] raw = Base64.decode(encrypted, Base64.DEFAULT);
    byte[] originalBytes = ecipher.doFinal(raw);

    String original = new String(originalBytes, "UTF8");
    return original;
}

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

The annotation mappedBy ideally should always be used in the Parent side (Company class) of the bi directional relationship, in this case it should be in Company class pointing to the member variable 'company' of the Child class (Branch class)

The annotation @JoinColumn is used to specify a mapped column for joining an entity association, this annotation can be used in any class (Parent or Child) but it should ideally be used only in one side (either in parent class or in Child class not in both) here in this case i used it in the Child side (Branch class) of the bi directional relationship indicating the foreign key in the Branch class.

below is the working example :

parent class , Company

@Entity
public class Company {


    private int companyId;
    private String companyName;
    private List<Branch> branches;

    @Id
    @GeneratedValue
    @Column(name="COMPANY_ID")
    public int getCompanyId() {
        return companyId;
    }

    public void setCompanyId(int companyId) {
        this.companyId = companyId;
    }

    @Column(name="COMPANY_NAME")
    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    @OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="company")
    public List<Branch> getBranches() {
        return branches;
    }

    public void setBranches(List<Branch> branches) {
        this.branches = branches;
    }


}

child class, Branch

@Entity
public class Branch {

    private int branchId;
    private String branchName;
    private Company company;

    @Id
    @GeneratedValue
    @Column(name="BRANCH_ID")
    public int getBranchId() {
        return branchId;
    }

    public void setBranchId(int branchId) {
        this.branchId = branchId;
    }

    @Column(name="BRANCH_NAME")
    public String getBranchName() {
        return branchName;
    }

    public void setBranchName(String branchName) {
        this.branchName = branchName;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="COMPANY_ID")
    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }


}

PHP array() to javascript array()

<?php 
            $ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
            $disabledDaysRange = array();
            foreach($this->reservedDates as $dates) {
                 $date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
                 $disabledDaysRange[] = $date;
                 array_push($disabledDaysRange, $date);
            }

            $finalArr = json_encode($disabledDaysRange);
?>
<script>
var disabledDaysRange = <?=$finalArr?>;

</script>

Truncating all tables in a Postgres database

In this case it would probably be better to just have an empty database that you use as a template and when you need to refresh, drop the existing database and create a new one from the template.

How to detect a mobile device with JavaScript?

I know this answer is coming 3 years late but none of the other answers are indeed 100% correct. If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then you can use the following code:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
    // Take the user to a different screen here.
}

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

Swift 2.0

// Checking if app is running iOS 8
    if application.respondsToSelector("isRegisteredForRemoteNotifications") {

        print("registerApplicationForPushNotifications - iOS 8")

        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil));
        application.registerForRemoteNotifications()

    } else {
        // Register for Push Notifications before iOS 8
        print("registerApplicationForPushNotifications - <iOS 8")
        application.registerForRemoteNotificationTypes([UIRemoteNotificationType.Alert, UIRemoteNotificationType.Badge, UIRemoteNotificationType.Sound])

    }

Arrays in unix shell?

A Simple way :

arr=("sharlock"  "bomkesh"  "feluda" )  ##declare array

len=${#arr[*]}  #determine length of array

# iterate with for loop
for (( i=0; i<len; i++ ))
do
    echo ${arr[$i]}
done

Git on Mac OS X v10.7 (Lion)

If you do not want to install Xcode and/or MacPorts/Fink/Homebrew, you could always use the standalone installer: https://sourceforge.net/projects/git-osx-installer/

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

I had the same problem for different package. I was installing pyinstaller in conda on Mac Mojave. I did

conda create --name ai37 python=3.7
conda activate ai37

I got the mentioned error when I tried to install pyinstaller using

pip install pyinstaller

I was able to install the pyinstaller with the following command

conda install -c conda-forge pyinstaller 

How to list files inside a folder with SQL Server

Create a SQLCLR assembly with external access permission that returns the list of files as a result set. There are many examples how to do this, eg. Yet another TVF: returning files from a directory or Trading in xp_cmdshell for SQLCLR (Part 1) - List Directory Contents.

Why is it that "No HTTP resource was found that matches the request URI" here?

Please check the class you inherited. Whether it is simply Controller or APIController.

By mistake we might create a controller from MVC 5 controller. It should be from Web API Controller.

Timeout jQuery effects

Update: As of jQuery 1.4 you can use the .delay( n ) method. http://api.jquery.com/delay/

$('.notice').fadeIn().delay(2000).fadeOut('slow'); 

Note: $.show() and $.hide() by default are not queued, so if you want to use $.delay() with them, you need to configure them that way:

$('.notice')
    .show({duration: 0, queue: true})
    .delay(2000)
    .hide({duration: 0, queue: true});

You could possibly use the Queue syntax, this might work:

jQuery(function($){ 

var e = $('.notice'); 
e.fadeIn(); 
e.queue(function(){ 
  setTimeout(function(){ 
    e.dequeue(); 
  }, 2000 ); 
}); 
e.fadeOut('fast'); 

}); 

or you could be really ingenious and make a jQuery function to do it.

(function($){ 

  jQuery.fn.idle = function(time)
  { 
      var o = $(this); 
      o.queue(function()
      { 
         setTimeout(function()
         { 
            o.dequeue(); 
         }, time);
      });
  };
})(jQuery);

which would ( in theory , working on memory here ) permit you do to this:

$('.notice').fadeIn().idle(2000).fadeOut('slow'); 

How to pass a file path which is in assets folder to File(String path)?

Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.

You'll need to unpack the file or use it directly.

If you have a Context, you can use context.getAssets().open("myfoldername/myfilename"); to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).

Making HTML page zoom by default

In js you can change zoom by

document.body.style.zoom="90%"

But it doesn't work in FF http://caniuse.com/#search=zoom

For ff you can try

-moz-transform: scale(0.9);

And check next topic How can I zoom an HTML element in Firefox and Opera?

loading json data from local file into React JS

If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.

Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: How to open a local disk file with Javascript?

I will include a slightly modified version for using it in React:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
    this.handleFileSelect = this.handleFileSelect.bind(this);
  }

  displayData(content) {
    this.setState({data: content});
  }

  handleFileSelect(evt) {
    let files = evt.target.files;
    if (!files.length) {
      alert('No file select');
      return;
    }
    let file = files[0];
    let that = this;
    let reader = new FileReader();
    reader.onload = function(e) {
      that.displayData(e.target.result);
    };
    reader.readAsText(file);
  }

  render() {
    const data = this.state.data;
    return (
      <div>
        <input type="file" onChange={this.handleFileSelect}/>
        { data && <p> {data} </p> }
      </div>
    );
  }
}

What does the variable $this mean in PHP?

It's a reference to the current object, it's most commonly used in object oriented code.

Example:

<?php
class Person {
    public $name;

    function __construct( $name ) {
        $this->name = $name;
    }
};

$jack = new Person('Jack');
echo $jack->name;

This stores the 'Jack' string as a property of the object created.

JavaScript Number Split into individual digits

You can also do it in the "mathematical" way without treating the number as a string:

_x000D_
_x000D_
var num = 278;_x000D_
var digits = [];_x000D_
while (num > 0) {_x000D_
    digits.push(num % 10);_x000D_
    num = parseInt(num / 10);_x000D_
}_x000D_
digits.reverse();_x000D_
console.log(digits);
_x000D_
_x000D_
_x000D_

One upside I can see is that you won't have to run parseInt() on every digit, you're dealing with the actual digits as numeric values.

How do I schedule jobs in Jenkins?

Jenkins lets you set up multiple times, separated by line breaks.

If you need it to build daily at 7 am, along with every Sunday at 4 pm, the below works well.

H 7 * * *

H 16 * * 0

Android - How to get application name? (Not package name)

Okay guys another sleek option is

Application.Context.ApplicationInfo.NonLocalizedLabel

verified for hard coded android label on application element.

<application android:label="Big App"></application>

Reference: http://developer.android.com/reference/android/content/pm/PackageItemInfo.html#nonLocalizedLabel

Make absolute positioned div expand parent div height

I had a similar problem. To solve this (instead of calculate the iframe's height using the body, document or window) I created a div that wraps the whole page content (a div with an id="page" for example) and then I used its height.

I want to load another HTML page after a specific amount of time

use this JavaScript code:

<script>
    setTimeout(function(){
       window.location.href = 'form2.html';
    }, 5000);
</script>

Calling one Bash script from another Script passing it arguments with quotes and spaces

Quote your args in Testscript 1:

echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"

Java: Replace all ' in a string with \'

This doesn't say how to "fix" the problem - that's already been done in other answers; it exists to draw out the details and applicable documentation references.


When using String.replaceAll or any of the applicable Matcher replacers, pay attention to the replacement string and how it is handled:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

As pointed out by isnot2bad in a comment, Matcher.quoteReplacement may be useful here:

Returns a literal replacement String for the specified String. .. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes (\) and dollar signs ($) will be given no special meaning.

Form Validation With Bootstrap (jQuery)

I had your code setup on jsFiddle to try diagnose the problem.

http://jsfiddle.net/5WMff/

However, I don't seem to encounter your issue. Could you take a look and let us know?

HTML

<div class="hero-unit">
 <h1>Contact Form</h1> 
</br>
<form method="POST" action="contact-form-submission.php" class="form-horizontal" id="contact-form">
    <div class="control-group">
        <label class="control-label" for="name">Name</label>
        <div class="controls">
            <input type="text" name="name" id="name" placeholder="Your name">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="email">Email Address</label>
        <div class="controls">
            <input type="text" name="email" id="email" placeholder="Your email address">
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="subject">Subject</label>
        <div class="controls">
            <select id="subject" name="subject">
                <option value="na" selected="">Choose One:</option>
                <option value="service">Feedback</option>
                <option value="suggestions">Suggestion</option>
                <option value="support">Question</option>
                <option value="other">Other</option>
            </select>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="message">Message</label>
        <div class="controls">
            <textarea name="message" id="message" rows="8" class="span5" placeholder="The message you want to send to us."></textarea>
        </div>
    </div>
    <div class="form-actions">
        <input type="hidden" name="save" value="contact">
        <button type="submit" class="btn btn-success">Submit Message</button>
        <button type="reset" class="btn">Cancel</button>
    </div>
</form>

Javascript

$(document).ready(function () {

$('#contact-form').validate({
    rules: {
        name: {
            minlength: 2,
            required: true
        },
        email: {
            required: true,
            email: true
        },
        message: {
            minlength: 2,
            required: true
        }
    },
    highlight: function (element) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
    },
    success: function (element) {
        element.text('OK!').addClass('valid')
            .closest('.control-group').removeClass('error').addClass('success');
    }
});
});

Create nice column output in python

To get fancier tables like

---------------------------------------------------
| First Name | Last Name        | Age | Position  |
---------------------------------------------------
| John       | Smith            | 24  | Software  |
|            |                  |     | Engineer  |
---------------------------------------------------
| Mary       | Brohowski        | 23  | Sales     |
|            |                  |     | Manager   |
---------------------------------------------------
| Aristidis  | Papageorgopoulos | 28  | Senior    |
|            |                  |     | Reseacher |
---------------------------------------------------

you can use this Python recipe:

'''
From http://code.activestate.com/recipes/267662-table-indentation/
PSF License
'''
import cStringIO,operator

def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left',
           separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x):
    """Indents a table by column.
       - rows: A sequence of sequences of items, one sequence per row.
       - hasHeader: True if the first row consists of the columns' names.
       - headerChar: Character to be used for the row separator line
         (if hasHeader==True or separateRows==True).
       - delim: The column delimiter.
       - justify: Determines how are data justified in their column. 
         Valid values are 'left','right' and 'center'.
       - separateRows: True if rows are to be separated by a line
         of 'headerChar's.
       - prefix: A string prepended to each printed row.
       - postfix: A string appended to each printed row.
       - wrapfunc: A function f(text) for wrapping text; each element in
         the table is first wrapped by this function."""
    # closure for breaking logical rows to physical, using wrapfunc
    def rowWrapper(row):
        newRows = [wrapfunc(item).split('\n') for item in row]
        return [[substr or '' for substr in item] for item in map(None,*newRows)]
    # break each logical row into one or more physical ones
    logicalRows = [rowWrapper(row) for row in rows]
    # columns of physical rows
    columns = map(None,*reduce(operator.add,logicalRows))
    # get the maximum of each column by the string length of its items
    maxWidths = [max([len(str(item)) for item in column]) for column in columns]
    rowSeparator = headerChar * (len(prefix) + len(postfix) + sum(maxWidths) + \
                                 len(delim)*(len(maxWidths)-1))
    # select the appropriate justify method
    justify = {'center':str.center, 'right':str.rjust, 'left':str.ljust}[justify.lower()]
    output=cStringIO.StringIO()
    if separateRows: print >> output, rowSeparator
    for physicalRows in logicalRows:
        for row in physicalRows:
            print >> output, \
                prefix \
                + delim.join([justify(str(item),width) for (item,width) in zip(row,maxWidths)]) \
                + postfix
        if separateRows or hasHeader: print >> output, rowSeparator; hasHeader=False
    return output.getvalue()

# written by Mike Brown
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
def wrap_onspace(text, width):
    """
    A word-wrap function that preserves existing line breaks
    and most spaces in the text. Expects that existing line
    breaks are posix newlines (\n).
    """
    return reduce(lambda line, word, width=width: '%s%s%s' %
                  (line,
                   ' \n'[(len(line[line.rfind('\n')+1:])
                         + len(word.split('\n',1)[0]
                              ) >= width)],
                   word),
                  text.split(' ')
                 )

import re
def wrap_onspace_strict(text, width):
    """Similar to wrap_onspace, but enforces the width constraint:
       words longer than width are split."""
    wordRegex = re.compile(r'\S{'+str(width)+r',}')
    return wrap_onspace(wordRegex.sub(lambda m: wrap_always(m.group(),width),text),width)

import math
def wrap_always(text, width):
    """A simple word-wrap function that wraps text on exactly width characters.
       It doesn't split the text in words."""
    return '\n'.join([ text[width*i:width*(i+1)] \
                       for i in xrange(int(math.ceil(1.*len(text)/width))) ])

if __name__ == '__main__':
    labels = ('First Name', 'Last Name', 'Age', 'Position')
    data = \
    '''John,Smith,24,Software Engineer
       Mary,Brohowski,23,Sales Manager
       Aristidis,Papageorgopoulos,28,Senior Reseacher'''
    rows = [row.strip().split(',')  for row in data.splitlines()]

    print 'Without wrapping function\n'
    print indent([labels]+rows, hasHeader=True)
    # test indent with different wrapping functions
    width = 10
    for wrapper in (wrap_always,wrap_onspace,wrap_onspace_strict):
        print 'Wrapping function: %s(x,width=%d)\n' % (wrapper.__name__,width)
        print indent([labels]+rows, hasHeader=True, separateRows=True,
                     prefix='| ', postfix=' |',
                     wrapfunc=lambda x: wrapper(x,width))

    # output:
    #
    #Without wrapping function
    #
    #First Name | Last Name        | Age | Position         
    #-------------------------------------------------------
    #John       | Smith            | 24  | Software Engineer
    #Mary       | Brohowski        | 23  | Sales Manager    
    #Aristidis  | Papageorgopoulos | 28  | Senior Reseacher 
    #
    #Wrapping function: wrap_always(x,width=10)
    #
    #----------------------------------------------
    #| First Name | Last Name  | Age | Position   |
    #----------------------------------------------
    #| John       | Smith      | 24  | Software E |
    #|            |            |     | ngineer    |
    #----------------------------------------------
    #| Mary       | Brohowski  | 23  | Sales Mana |
    #|            |            |     | ger        |
    #----------------------------------------------
    #| Aristidis  | Papageorgo | 28  | Senior Res |
    #|            | poulos     |     | eacher     |
    #----------------------------------------------
    #
    #Wrapping function: wrap_onspace(x,width=10)
    #
    #---------------------------------------------------
    #| First Name | Last Name        | Age | Position  |
    #---------------------------------------------------
    #| John       | Smith            | 24  | Software  |
    #|            |                  |     | Engineer  |
    #---------------------------------------------------
    #| Mary       | Brohowski        | 23  | Sales     |
    #|            |                  |     | Manager   |
    #---------------------------------------------------
    #| Aristidis  | Papageorgopoulos | 28  | Senior    |
    #|            |                  |     | Reseacher |
    #---------------------------------------------------
    #
    #Wrapping function: wrap_onspace_strict(x,width=10)
    #
    #---------------------------------------------
    #| First Name | Last Name  | Age | Position  |
    #---------------------------------------------
    #| John       | Smith      | 24  | Software  |
    #|            |            |     | Engineer  |
    #---------------------------------------------
    #| Mary       | Brohowski  | 23  | Sales     |
    #|            |            |     | Manager   |
    #---------------------------------------------
    #| Aristidis  | Papageorgo | 28  | Senior    |
    #|            | poulos     |     | Reseacher |
    #---------------------------------------------

The Python recipe page contains a few improvements on it.

VSCode single to double quote automatic replace

Install prettier extension and paste below code in your VSCode settings.json file

 "prettier.useEditorConfig": false,
 "prettier.singleQuote": true

this will ignore your .editorconfig file setting.

How to disable all <input > inside a form with jQuery?

The definitive answer (covering changes to jQuery api at version 1.6) has been given by Gnarf

Counter increment in Bash loop not working

This is all you need to do:

$((COUNTER++))

Here's an excerpt from Learning the bash Shell, 3rd Edition, pp. 147, 148:

bash arithmetic expressions are equivalent to their counterparts in the Java and C languages.[9] Precedence and associativity are the same as in C. Table 6-2 shows the arithmetic operators that are supported. Although some of these are (or contain) special characters, there is no need to backslash-escape them, because they are within the $((...)) syntax.

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

The ++ and - operators are useful when you want to increment or decrement a value by one.[11] They work the same as in Java and C, e.g., value++ increments value by 1. This is called post-increment; there is also a pre-increment: ++value. The difference becomes evident with an example:

$ i=0
$ echo $i
0
$ echo $((i++))
0
$ echo $i
1
$ echo $((++i))
2
$ echo $i
2

See http://www.safaribooksonline.com/a/learning-the-bash/7572399/

How to do select from where x is equal to multiple values?

And even simpler using IN:

SELECT ads.*, location.county 
  FROM ads
  LEFT JOIN location ON location.county = ads.county_id
  WHERE ads.published = 1 
        AND ads.type = 13
        AND ads.county_id IN (2,5,7,9)

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

Check whether a string is not null and not empty

In case you are using Java 8 and want to have a more Functional Programming approach, you can define a Function that manages the control and then you can reuse it and apply() whenever is needed.

Coming to practice, you can define the Function as

Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)

Then, you can use it by simply calling the apply() method as:

String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true

If you prefer, you can define a Function that checks if the String is empty and then negate it with !.

In this case, the Function will look like as :

Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)

Then, you can use it by simply calling the apply() method as:

String emptyString = "";
!isEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true

PHPMailer: SMTP Error: Could not connect to SMTP host

I had a similar issue. I had installed PHPMailer version 1.72 which is not prepared to manage SSL connections. Upgrading to last version solved the problem.

shell script to remove a file if it already exist

A one liner shell script to remove a file if it already exist (based on Jindra Helcl's answer):

[ -f file ] && rm file

or with a variable:

#!/bin/bash

file="/path/to/file.ext"
[ -f $file ] && rm $file

How to center a Window in Java?

There's something really simple that you might be overlooking after trying to center the window using either setLocationRelativeTo(null) or setLocation(x,y) and it ends up being a little off center.

Make sure that you use either one of these methods after calling pack() because the you'll end up using the dimensions of the window itself to calculate where to place it on screen. Until pack() is called, the dimensions aren't what you'd think thus throwing off the calculations to center the window. Hope this helps.

Maven: Non-resolvable parent POM

It was fixed when I removed settings.xml from .m2 folder.

Port 80 is being used by SYSTEM (PID 4), what is that?

In case you use Razer product and install Razer Synapse software on your PC, it blocks the port 80 too.

It is not included in the netstat command so I am not able to troubleshoot it. Since there are many services included within the software, I can't analyze which one that blocks the port. After uninstalling the Razer Synapse, I can start the Apache server again on Windows 10.

How to change the button color when it is active using bootstrap?

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

How to set upload_max_filesize in .htaccess?

If your web server is running php5, I believe you must use php5_value. This resolved the same error I received when using php_value.

Remove spaces from a string in VB.NET

What about Regex.Replace solution?

myStr = Regex.Replace(myStr, "\s", "")

Is it possible to add an HTML link in the body of a MAILTO link

Please check below javascript in IE. Don't know if other modern browser will work or not.

<html>
    <head>
        <script type="text/javascript">
            function OpenOutlookDoc(){
                try {

                    var outlookApp = new ActiveXObject("Outlook.Application");
                    var nameSpace = outlookApp.getNameSpace("MAPI");
                    mailFolder = nameSpace.getDefaultFolder(6);
                    mailItem = mailFolder.Items.add('IPM.Note.FormA');
                    mailItem.Subject="a subject test";
                    mailItem.To = "[email protected]";
                    mailItem.HTMLBody = "<b>bold</b>";
                    mailItem.display (0); 
                }
                catch(e){
                    alert(e);
                    // act on any error that you get
                }
            }
        </script>
    </head>
    <body>
        <a href="javascript:OpenOutlookDoc()">Click</a>
    </body>
</html>

AngularJS sorting by property

As you can see in the code of angular-JS ( https://github.com/angular/angular.js/blob/master/src/ng/filter/orderBy.js ) ng-repeat does not work with objects. Here is a hack with sortFunction.

http://jsfiddle.net/sunnycpp/qaK56/33/

<div ng-app='myApp'>
    <div ng-controller="controller">
    <ul>
        <li ng-repeat="test in testData | orderBy:sortMe()">
            Order = {{test.value.order}} -> Key={{test.key}} Name=:{{test.value.name}}
        </li>
    </ul>
    </div>
</div>

myApp.controller('controller', ['$scope', function ($scope) {

    var testData = {
        a:{name:"CData", order: 2},
        b:{name:"AData", order: 3},
        c:{name:"BData", order: 1}
    };
    $scope.testData = _.map(testData, function(vValue, vKey) {
        return { key:vKey, value:vValue };
    }) ;
    $scope.sortMe = function() {
        return function(object) {
            return object.value.order;
        }
    }
}]);

Append text using StreamWriter

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

MySQL Query to select data from last week?

Simplified form:

Last week data:

SELECT id FROM tbl


WHERE 
WEEK (date) = WEEK( current_date ) - 1 AND YEAR( date) = YEAR( current_date );

2 weeks ago data:

SELECT id FROM tbl


WHERE 
WEEK (date) = WEEK( current_date ) - 2 AND YEAR( date) = YEAR( current_date );

SQL Fiddle

http://sqlfiddle.com/#!8/6fa6e/2

How does a hash table work?

Short and sweet:

A hash table wraps up an array, lets call it internalArray. Items are inserted into the array in this way:

let insert key value =
    internalArray[hash(key) % internalArray.Length] <- (key, value)
    //oversimplified for educational purposes

Sometimes two keys will hash to the same index in the array, and you want to keep both values. I like to store both values in the same index, which is simple to code by making internalArray an array of linked lists:

let insert key value =
    internalArray[hash(key) % internalArray.Length].AddLast(key, value)

So, if I wanted to retrieve an item out of my hash table, I could write:

let get key =
    let linkedList = internalArray[hash(key) % internalArray.Length]
    for (testKey, value) in linkedList
        if (testKey = key) then return value
    return null

Delete operations are just as simple to write. As you can tell, inserts, lookups, and removal from our array of linked lists is nearly O(1).

When our internalArray gets too full, maybe at around 85% capacity, we can resize the internal array and move all of the items from the old array into the new array.

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

How to rename array keys in PHP?

Talking about functional PHP, I have this more generic answer:

    array_map(function($arr){
        $ret = $arr;
        $ret['value'] = $ret['url'];
        unset($ret['url']);
        return $ret;
    }, $tag);
}

Value Change Listener to JTextField

The usual answer to this is "use a DocumentListener". However, I always find that interface cumbersome. Truthfully the interface is over-engineered. It has three methods, for insertion, removal, and replacement of text, when it only needs one method: replacement. (An insertion can be viewed as a replacement of no text with some text, and a removal can be viewed as a replacement of some text with no text.)

Usually all you want is to know is when the text in the box has changed, so a typical DocumentListener implementation has the three methods calling one method.

Therefore I made the following utility method, which lets you use a simpler ChangeListener rather than a DocumentListener. (It uses Java 8's lambda syntax, but you can adapt it for old Java if needed.)

/**
 * Installs a listener to receive notification when the text of any
 * {@code JTextComponent} is changed. Internally, it installs a
 * {@link DocumentListener} on the text component's {@link Document},
 * and a {@link PropertyChangeListener} on the text component to detect
 * if the {@code Document} itself is replaced.
 * 
 * @param text any text component, such as a {@link JTextField}
 *        or {@link JTextArea}
 * @param changeListener a listener to receieve {@link ChangeEvent}s
 *        when the text is changed; the source object for the events
 *        will be the text component
 * @throws NullPointerException if either parameter is null
 */
public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
    Objects.requireNonNull(text);
    Objects.requireNonNull(changeListener);
    DocumentListener dl = new DocumentListener() {
        private int lastChange = 0, lastNotifiedChange = 0;

        @Override
        public void insertUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            lastChange++;
            SwingUtilities.invokeLater(() -> {
                if (lastNotifiedChange != lastChange) {
                    lastNotifiedChange = lastChange;
                    changeListener.stateChanged(new ChangeEvent(text));
                }
            });
        }
    };
    text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
        Document d1 = (Document)e.getOldValue();
        Document d2 = (Document)e.getNewValue();
        if (d1 != null) d1.removeDocumentListener(dl);
        if (d2 != null) d2.addDocumentListener(dl);
        dl.changedUpdate(null);
    });
    Document d = text.getDocument();
    if (d != null) d.addDocumentListener(dl);
}

Unlike with adding a listener directly to the document, this handles the (uncommon) case that you install a new document object on a text component. Additionally, it works around the problem mentioned in Jean-Marc Astesana's answer, where the document sometimes fires more events than it needs to.

Anyway, this method lets you replace annoying code which looks like this:

someTextBox.getDocument().addDocumentListener(new DocumentListener() {
    @Override
    public void insertUpdate(DocumentEvent e) {
        doSomething();
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        doSomething();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        doSomething();
    }
});

With:

addChangeListener(someTextBox, e -> doSomething());

Code released to public domain. Have fun!

HttpClient won't import in Android Studio

Try this worked for me Add this dependency to your build.gradle File

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

How can I slice an ArrayList out of an ArrayList in Java?

This is how I solved it. I forgot that sublist was a direct reference to the elements in the original list, so it makes sense why it wouldn't work.

ArrayList<Integer> inputA = new ArrayList<Integer>(input.subList(0, input.size()/2));

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

How can I initialize a MySQL database with schema in a Docker container?

For the ones not wanting to create an entrypoint script like me, you actually can start mysqld at build-time and then execute the mysql commands in your Dockerfile like so:

RUN mysqld_safe & until mysqladmin ping; do sleep 1; done && \
    mysql -uroot -e "CREATE DATABASE somedb;" && \
    mysql -uroot -e "CREATE USER 'someuser'@'localhost' IDENTIFIED BY 'somepassword';" && \
    mysql -uroot -e "GRANT ALL PRIVILEGES ON somedb.* TO 'someuser'@'localhost';"

The key here is to send mysqld_safe to background with the single & sign.

Input length must be multiple of 16 when decrypting with padded cipher

This is a very old question, but my answer may help someone.

  • In the encrypt method, don't forget to encode your string to Base64
  • In the decrypt method, don't forget to decode your string to Base64

Below is the working code

    import java.util.Arrays;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    public class EncryptionDecryptionUtil {

    public static String encrypt(final String secret, final String data) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while encrypting data", e);
        }

    }

    public static String decrypt(final String secret,
            final String encryptedString) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.DECRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
            return new String(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while decrypting data", e);
        }
    }


    public static void main(String[] args) {

        String data = "This is not easy as you think";
        String key = "---------------------------------";
        String encrypted = encrypt(key, data);
        System.out.println(encrypted);
        System.out.println(decrypt(key, encrypted));
      }
  }

For Generating Key you can use below class

    import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyGenerator {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();
        int keyBitSize = 256;
        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();

 System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
    }

}

How do I configure different environments in Angular.js?

Very late to the thread, but a technique I've used, pre-Angular, is to take advantage of JSON and the flexibility of JS to dynamically reference collection keys, and use inalienable facts of the environment (host server name, current browser language, etc.) as inputs to selectively discriminate/prefer suffixed key names within a JSON data structure.

This provides not merely deploy-environment context (per OP) but any arbitrary context (such as language) to provide i18n or any other variance required simultaneously, and (ideally) within a single configuration manifest, without duplication, and readably obvious.

IN ABOUT 10 LINES VANILLA JS

Overly-simplified but classic example: An API endpoint base URL in a JSON-formatted properties file that varies per environment where (natch) the host server will also vary:

    ...
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        '[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
        '[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...

A key to the discrimination function is simply the server hostname in the request.

This, naturally, can be combined with an additional key based on the user's language settings:

    ...
    'app': {
        'NAME': 'Ferry Reservations',
        'NAME@fr': 'Réservations de ferry',
        'NAME@de': 'Fähren Reservierungen'
    },
    ...

The scope of the discrimination/preference can be confined to individual keys (as above) where the "base" key is only overwritten if there's a matching key+suffix for the inputs to the function -- or an entire structure, and that structure itself recursively parsed for matching discrimination/preference suffixes:

    'help': {
        'BLURB': 'This pre-production environment is not supported. Contact Development Team with questions.',
        'PHONE': '808-867-5309',
        'EMAIL': '[email protected]'
    },
    '[email protected]': {
        'BLURB': 'Please contact Customer Service Center',
        'BLURB@fr': 'S\'il vous plaît communiquer avec notre Centre de service à la clientèle',
        'BLURB@de': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': '[email protected]'
    },

SO, if a visiting user to the production website has German (de) language preference setting, the above configuration would collapse to:

    'help': {
        'BLURB': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': '[email protected]'
    },

What does such a magical preference/discrimination JSON-rewriting function look like? Not much:

// prefer(object,suffix|[suffixes]) by/par/durch storsoc
// prefer({ a: 'apple', a@env: 'banana', b: 'carrot' },'env') -> { a: 'banana', b: 'carrot' }
function prefer(o,sufs) {
    for (var key in o) {
        if (!o.hasOwnProperty(key)) continue; // skip non-instance props
        if(key.split('@')[1]) { // suffixed!
            // replace root prop with the suffixed prop if among prefs
            if(o[key] && sufs.indexOf(key.split('@')[1]) > -1) o[key.split('@')[0]] = JSON.parse(JSON.stringify(o[key]));

            // and nuke the suffixed prop to tidy up
            delete o[key];

            // continue with root key ...
            key = key.split('@')[0];
        }

        // ... in case it's a collection itself, recurse it!
        if(o[key] && typeof o[key] === 'object') prefer(o[key],sufs);

    };
};

In our implementations, which include Angular and pre-Angular websites, we simply bootstrap the configuration well ahead of other resource calls by placing the JSON within a self-executing JS closure, including the prefer() function, and fed basic properties of hostname and language-code (and accepts any additional arbitrary suffixes you might need):

(function(prefs){ var props = {
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        '[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
        '[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...
    /* yadda yadda moar JSON und bisque */

    function prefer(o,sufs) {
        // body of prefer function, broken for e.g.
    };

    // convert string and comma-separated-string to array .. and process it
    prefs = [].concat( ( prefs.split ? prefs.split(',') : prefs ) || []);
    prefer(props,prefs);
    window.app_props = JSON.parse(JSON.stringify(props));
})([location.hostname, ((window.navigator.userLanguage || window.navigator.language).split('-')[0])  ] );

A pre-Angular site would now have a collapsed (no @ suffixed keys) window.app_props to refer to.

An Angular site, as a bootstrap/init step, simply copies the dead-dropped props object into $rootScope, and (optionally) destroys it from global/window scope

app.constant('props',angular.copy(window.app_props || {})).run( function ($rootScope,props) { $rootScope.props = props; delete window.app_props;} );

to be subsequently injected into controllers:

app.controller('CtrlApp',function($log,props){ ... } );

or referred to from bindings in views:

<span>{{ props.help.blurb }} {{ props.help.email }}</span>

Caveats? The @ character is not valid JS/JSON variable/key naming, but so far accepted. If that's a deal-breaker, substitute for any convention you like, such as "__" (double underscore) as long as you stick to it.

The technique could be applied server-side, ported to Java or C# but your efficiency/compactness may vary.

Alternately, the function/convention could be part of your front-end compile script, so that the full gory all-environment/all-language JSON is never transmitted over the wire.

UPDATE

We've evolved usage of this technique to allow multiple suffixes to a key, to avoid being forced to use collections (you still can, as deeply as you want), and as well to honor the order of the preferred suffixes.

Example (also see working jsFiddle):

var o = { 'a':'apple', 'a@dev':'apple-dev', 'a@fr':'pomme',
          'b':'banana', 'b@fr':'banane', 'b@dev&fr':'banane-dev',
          'c':{ 'o':'c-dot-oh', 'o@fr':'c-point-oh' }, 'c@dev': { 'o':'c-dot-oh-dev', 'o@fr':'c-point-oh-dev' } };

/*1*/ prefer(o,'dev');        // { a:'apple-dev', b:'banana',     c:{o:'c-dot-oh-dev'}   }
/*2*/ prefer(o,'fr');         // { a:'pomme',     b:'banane',     c:{o:'c-point-oh'}     }
/*3*/ prefer(o,'dev,fr');     // { a:'apple-dev', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*4*/ prefer(o,['fr','dev']); // { a:'pomme',     b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*5*/ prefer(o);              // { a:'apple',     b:'banana',     c:{o:'c-dot-oh'}       }

1/2 (basic usage) prefers '@dev' keys, discards all other suffixed keys

3 prefers '@dev' over '@fr', prefers '@dev&fr' over all others

4 (same as 3 but prefers '@fr' over '@dev')

5 no preferred suffixes, drops ALL suffixed properties

It accomplishes this by scoring each suffixed property and promoting the value of a suffixed property to the non-suffixed property when iterating over the properties and finding a higher-scored suffix.

Some efficiencies in this version, including removing dependence on JSON to deep-copy, and only recursing into objects that survive the scoring round at their depth:

function prefer(obj,suf) {
    function pr(o,s) {
        for (var p in o) {
            if (!o.hasOwnProperty(p) || !p.split('@')[1] || p.split('@@')[1] ) continue; // ignore: proto-prop OR not-suffixed OR temp prop score
            var b = p.split('@')[0]; // base prop name
            if(!!!o['@@'+b]) o['@@'+b] = 0; // +score placeholder
            var ps = p.split('@')[1].split('&'); // array of property suffixes
            var sc = 0; var v = 0; // reset (running)score and value
            while(ps.length) {
                // suffix value: index(of found suffix in prefs)^10
                v = Math.floor(Math.pow(10,s.indexOf(ps.pop())));
                if(!v) { sc = 0; break; } // found suf NOT in prefs, zero score (delete later)
                sc += v;
            }
            if(sc > o['@@'+b]) { o['@@'+b] = sc; o[b] = o[p]; } // hi-score! promote to base prop
            delete o[p];
        }
        for (var p in o) if(p.split('@@')[1]) delete o[p]; // remove scores
        for (var p in o) if(typeof o[p] === 'object') pr(o[p],s); // recurse surviving objs
    }
    if( typeof obj !== 'object' ) return; // validate
    suf = ( (suf || suf === 0 ) && ( suf.length || suf === parseFloat(suf) ) ? suf.toString().split(',') : []); // array|string|number|comma-separated-string -> array-of-strings
    pr(obj,suf.reverse());
}

installing python packages without internet and using source code as .tar.gz and .whl

This isn't an answer. I was struggling but then realized that my install was trying to connect to internet to download dependencies.

So, I downloaded and installed dependencies first and then installed with below command. It worked

python -m pip install filename.tar.gz

Rename Files and Directories (Add Prefix)

Here is a simple script that you can use. I like using the non-standard module File::chdir to handle managing cd operations, so to use this script as-is you will need to install it (sudo cpan File::chdir).

#!/usr/bin/perl

use strict;
use warnings;

use File::Copy;
use File::chdir; # allows cd-ing by use of $CWD, much easier but needs CPAN module

die "Usage: $0 dir prefix" unless (@ARGV >= 2);
my ($dir, $pre) = @ARGV;

opendir(my $dir_handle, $dir) or die "Cannot open directory $dir";
my @files = readdir($dir_handle);
close($dir_handle);

$CWD = $dir; # cd to the directory, needs File::chdir

foreach my $file (@files) {
  next if ($file =~ /^\.+$/); # avoid folders . and ..
  next if ($0 =~ /$file/); # avoid moving this script if it is in the directory

  move($file, $pre . $file) or warn "Cannot rename file $file: $!";
}

How to terminate a window in tmux?

If you just want to do it once, without adding a shortcut, you can always type

<prefix> 
:
kill-window
<enter>

Setting a timeout for socket operations

Use the Socket() constructor, and connect(SocketAddress endpoint, int timeout) method instead.

In your case it would look something like:

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);

Quoting from the documentation

connect

public void connect(SocketAddress endpoint, int timeout) throws IOException

Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

Parameters:

endpoint - the SocketAddress
timeout - the timeout value to be used in milliseconds.

Throws:

IOException - if an error occurs during the connection
SocketTimeoutException - if timeout expires before connecting
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket

Since: 1.4

How to initialize a list with constructor?

ContactNumbers = new List<ContactNumber>();

If you want it to be passed in, just take

public Human(List<ContactNumber> numbers)
{
 ContactNumbers = numbers;
}

javascript filter array multiple conditions

This is an easily understandable functional solution

_x000D_
_x000D_
let filtersObject = {_x000D_
  address: "England",_x000D_
  name: "Mark"_x000D_
};_x000D_
_x000D_
let users = [{_x000D_
    name: 'John',_x000D_
    email: '[email protected]',_x000D_
    age: 25,_x000D_
    address: 'USA'_x000D_
  },_x000D_
  {_x000D_
    name: 'Tom',_x000D_
    email: '[email protected]',_x000D_
    age: 35,_x000D_
    address: 'England'_x000D_
  },_x000D_
  {_x000D_
    name: 'Mark',_x000D_
    email: '[email protected]',_x000D_
    age: 28,_x000D_
    address: 'England'_x000D_
  }_x000D_
];_x000D_
_x000D_
function filterUsers(users, filtersObject) {_x000D_
  //Loop through all key-value pairs in filtersObject_x000D_
  Object.keys(filtersObject).forEach(function(key) {_x000D_
    //Loop through users array checking each userObject_x000D_
    users = users.filter(function(userObject) {_x000D_
      //If userObject's key:value is same as filtersObject's key:value, they stay in users array_x000D_
      return userObject[key] === filtersObject[key]_x000D_
    })_x000D_
  });_x000D_
  return users;_x000D_
}_x000D_
_x000D_
//ES6_x000D_
function filterUsersES(users, filtersObject) {_x000D_
  for (let key in filtersObject) {_x000D_
    users = users.filter((userObject) => userObject[key] === filtersObject[key]);_x000D_
  }_x000D_
  return users;_x000D_
}_x000D_
_x000D_
console.log(filterUsers(users, filtersObject));_x000D_
console.log(filterUsersES(users, filtersObject));
_x000D_
_x000D_
_x000D_

How to trim leading and trailing white spaces of a string?

@peterSO has correct answer. I am adding more examples here:

package main

import (
    "fmt"
    strings "strings"
)

func main() { 
    test := "\t pdftk 2.0.2  \n"
    result := strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\n\r pdftk 2.0.2 \n\r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\r pdftk 2.0.2 \r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))   
}

You can find this in Go lang playground too.

Proper way to make HTML nested list?

I prefer option two because it clearly shows the list item as the possessor of that nested list. I would always lean towards semantically sound HTML.

How to check if a service is running on Android?

You can use this (I didn't try this yet, but I hope this works):

if(startService(someIntent) != null) {
    Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
else {
    Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
}

The startService method returns a ComponentName object if there is an already running service. If not, null will be returned.

See public abstract ComponentName startService (Intent service).

This is not like checking I think, because it's starting the service, so you can add stopService(someIntent); under the code.

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin to *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Make sure that you haven't already used header in another file, or you will get a nasty error. See the docs for more.

Why am I getting "Thread was being aborted" in ASP.NET?

I got this error when I did a Response.Redirect after a successful login of the user.

I fixed it by doing a FormsAuthentication.RedirectFromLoginPage instead.

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

Simple DatePicker-like Calendar

this datepicker is an excellent solution. datepickers are a must if you want to avoid code injection.

What Regex would capture everything from ' mark to the end of a line?

https://regex101.com/r/Jjc2xR/1

/(\w*\(Hex\): w*)(.*?)(?= |$)/gm

I'm sure this one works, it will capture de hexa serial in the badly structured text multilined bellow

     Space Reservation: disabled
         Serial Number: wCVt1]IlvQWv
   Serial Number (Hex): 77435674315d496c76515776
               Comment: new comment

I'm a eternal newbie in regex but I'll try explain this one

(\w*(Hex): w*) : Find text in line where string contains "Hex: "

(.*?) This is the second captured text and means everything after

(?= |$) create a limit that is the space between = and the |

So with the second group, you will have the value

%i or %d to print integer in C using printf()?

d and i conversion specifiers behave the same with fprintf but behave differently for fscanf.

As some other wrote in their answer, the idiomatic way to print an int is using d conversion specifier.

Regarding i specifier and fprintf, C99 Rationale says that:

The %i conversion specifier was added in C89 for programmer convenience to provide symmetry with fscanf’s %i conversion specifier, even though it has exactly the same meaning as the %d conversion specifier when used with fprintf.

Why do I need to explicitly push a new branch?

Output of git push when pushing a new branch

> git checkout -b new_branch
Switched to a new branch 'new_branch'
> git push
fatal: The current branch new_branch has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin new_branch

A simple git push assumes that there already exists a remote branch that the current local branch is tracking. If no such remote branch exists, and you want to create it, you must specify that using the -u (short form of --set-upstream) flag.

Why this is so? I guess the implementers felt that creating a branch on the remote is such a major action that it should be hard to do it by mistake. git push is something you do all the time.

"Isn't a branch a new change to be pushed by default?" I would say that "a change" in Git is a commit. A branch is a pointer to a commit. To me it makes more sense to think of a push as something that pushes commits over to the other repositories. Which commits are pushed is determined by what branch you are on and the tracking relationship of that branch to branches on the remote.

You can read more about tracking branches in the Remote Branches chapter of the Pro Git book.

Jinja2 shorthand conditional

Alternative way (but it's not python style. It's JS style)

{{ files and 'Update' or 'Continue' }}

Pass a local file in to URL in Java

new File(path).toURI().toURL();

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

In addition of Stack: to avoid floating container on keyboard, use this

return Scaffold(
    appBar: getAppBar(title),
    resizeToAvoidBottomInset: false,
    body:

Get most recent row for given ID

SELECT *
FROM   tbl
WHERE  id = 1
ORDER  BY signin DESC
LIMIT  1;

The obvious index would be on (id), or a multicolumn index on (id, signin DESC).

Conveniently for the case, MySQL sorts NULL values last in descending order. That's what you typically want if there can be NULL values: the row with the latest not-null signin.

To get NULL values first:

ORDER BY signin IS NOT NULL, signin DESC

You may want to append more expressions to ORDER BY to get a deterministic pick from (potentially) multiple rows with NULL.
The same applies without NULL if signin is not defined UNIQUE.

Related:

The SQL standard does not explicitly define a default sort order for NULL values. The behavior varies quite a bit across different RDBMS. See:

But there are the NULLS FIRST / NULLS LAST clauses defined in the SQL standard and supported by most major RDBMS, but not by MySQL. See:

AngularJS does not send hidden field value

I had facing the same problem, I really need to send a key from my jsp to java script, It spend around 4h or more of my day to solve it.

I include this tag on my JavaScript/JSP:

_x000D_
_x000D_
 $scope.sucessMessage = function (){  _x000D_
     var message =     ($scope.messages.sucess).format($scope.portfolio.name,$scope.portfolio.id);_x000D_
     $scope.inforMessage = message;_x000D_
     alert(message);  _x000D_
}_x000D_
 _x000D_
_x000D_
String.prototype.format = function() {_x000D_
    var formatted = this;_x000D_
    for( var arg in arguments ) {_x000D_
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);_x000D_
    }_x000D_
    return formatted;_x000D_
};
_x000D_
<!-- Messages definition -->_x000D_
<input type="hidden"  name="sucess"   ng-init="messages.sucess='<fmt:message  key='portfolio.create.sucessMessage' />'" >_x000D_
_x000D_
<!-- Message showed affter insert -->_x000D_
<div class="alert alert-info" ng-show="(inforMessage.length > 0)">_x000D_
    {{inforMessage}}_x000D_
</div>_x000D_
_x000D_
<!-- properties_x000D_
  portfolio.create.sucessMessage=Portf\u00f3lio {0} criado com sucesso! ID={1}. -->
_x000D_
_x000D_
_x000D_

The result was: Portfólio 1 criado com sucesso! ID=3.

Best Regards

start MySQL server from command line on Mac OS Lion

Try /usr/local/mysql/bin/mysqld_safe

Example:

shell> sudo /usr/local/mysql/bin/mysqld_safe
(Enter your password, if necessary)
(Press Control-Z)
shell> bg
(Press Control-D or enter "exit" to exit the shell)

You can also add these to your bash startup scripts:

export MYSQL_HOME=/usr/local/mysql
alias start_mysql='sudo $MYSQL_HOME/bin/mysqld_safe &'
alias stop_mysql='sudo $MYSQL_HOME/bin/mysqladmin shutdown'

How to get a random number in Ruby

While you can use rand(42-10) + 10 to get a random number between 10 and 42 (where 10 is inclusive and 42 exclusive), there's a better way since Ruby 1.9.3, where you are able to call:

rand(10...42) # => 13

Available for all versions of Ruby by requiring my backports gem.

Ruby 1.9.2 also introduced the Random class so you can create your own random number generator objects and has a nice API:

r = Random.new
r.rand(10...42) # => 22
r.bytes(3) # => "rnd"

The Random class itself acts as a random generator, so you call directly:

Random.rand(10...42) # => same as rand(10...42)

Notes on Random.new

In most cases, the simplest is to use rand or Random.rand. Creating a new random generator each time you want a random number is a really bad idea. If you do this, you will get the random properties of the initial seeding algorithm which are atrocious compared to the properties of the random generator itself.

If you use Random.new, you should thus call it as rarely as possible, for example once as MyApp::Random = Random.new and use it everywhere else.

The cases where Random.new is helpful are the following:

  • you are writing a gem and don't want to interfere with the sequence of rand/Random.rand that the main programs might be relying on
  • you want separate reproducible sequences of random numbers (say one per thread)
  • you want to be able to save and resume a reproducible sequence of random numbers (easy as Random objects can marshalled)

How to use log levels in java

The use of levels is really up tp you. You need to decide what is severe in your application, what is a warning and what is just information. You need to split your logging so that your users can easily set up a level of logging that doesn't kill the system with excessing IO but which will report serious errors so you can fix them.

How to Make Laravel Eloquent "IN" Query?

Here is how you do in Eloquent

$users = User::whereIn('id', array(1, 2, 3))->get();

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

Nginx location priority

It fires in this order.

  1. = (exactly)

    location = /path

  2. ^~ (forward match)

    location ^~ /path

  3. ~ (regular expression case sensitive)

    location ~ /path/

  4. ~* (regular expression case insensitive)

    location ~* .(jpg|png|bmp)

  5. /

    location /path

How to find time complexity of an algorithm

When you're analyzing code, you have to analyse it line by line, counting every operation/recognizing time complexity, in the end, you have to sum it to get whole picture.

For example, you can have one simple loop with linear complexity, but later in that same program you can have a triple loop that has cubic complexity, so your program will have cubic complexity. Function order of growth comes into play right here.

Let's look at what are possibilities for time complexity of an algorithm, you can see order of growth I mentioned above:

  • Constant time has an order of growth 1, for example: a = b + c.

  • Logarithmic time has an order of growth LogN, it usually occurs when you're dividing something in half (binary search, trees, even loops), or multiplying something in same way.

  • Linear, order of growth is N, for example

    int p = 0;
    for (int i = 1; i < N; i++)
      p = p + 2;
    
  • Linearithmic, order of growth is n*logN, usually occurs in divide and conquer algorithms.

  • Cubic, order of growth N^3, classic example is a triple loop where you check all triplets:

    int x = 0;
    for (int i = 0; i < N; i++)
       for (int j = 0; j < N; j++)
          for (int k = 0; k < N; k++)
              x = x + 2
    
  • Exponential, order of growth 2^N, usually occurs when you do exhaustive search, for example check subsets of some set.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

Following work for me in ubuntu 19.1

source ~/.rvm/scripts/rvm

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

Update 2nd table data in 1st table need to Inner join before SET :

`UPDATE `table1` INNER JOIN `table2` ON `table2`.`id`=`table1`.`id` SET `table1`.`name`=`table2`.`name`, `table1`.`template`=`table2`.`template`;

How to add a button to UINavigationBar?

Sample code to set the rightbutton on a NavigationBar.

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
    style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Title"];
item.rightBarButtonItem = rightButton;
item.hidesBackButton = YES;
[bar pushNavigationItem:item animated:NO];

But normally you would have a NavigationController, enabling you to write:

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
    style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

What is the best way to implement a "timer"?

By using System.Windows.Forms.Timer class you can achieve what you need.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();


t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
      //Call method
}

By using stop() method you can stop timer.

t.Stop();

Python - How do you run a .py file?

On windows platform, you have 2 choices:

  1. In a command line terminal, type

    c:\python23\python xxxx.py

  2. Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.

For your posted code, the error is at this line:

def main(url, out_folder="C:\asdf\"):

It should be:

def main(url, out_folder="C:\\asdf\\"):

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

The answer is here: http://sysadminsjourney.com/content/2010/02/01/apache-modproxy-error-13permission-denied-error-rhel/

Which is a link to a blog that explains:

SELinux on RHEL/CentOS by default ships so that httpd processes cannot initiate outbound connections, which is just what mod_proxy attempts to do.

If this is the problem, it can be solved by running:

 /usr/sbin/setsebool -P httpd_can_network_connect 1

And for a more definitive source of information, see https://wiki.apache.org/httpd/13PermissionDenied

How to use <DllImport> in VB.NET?

I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs statement to state that the StringBuffer is equivalent to LPSTR.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function

Adding click event for a button created dynamically using jQuery

Just create a button element with jQuery, and add the event handler when you create it :

var div = $('<div />', {'data-role' : 'fieldcontain'}),
    btn = $('<input />', {
              type  : 'button',
              value : 'Dynamic Button',
              id    : 'btn_a',
              on    : {
                 click: function() {
                     alert ( this.value );
                 }
              }
          });

div.append(btn).appendTo( $('#pg_menu_content').empty() );

FIDDLE

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

Clip/Crop background-image with CSS

You can put the graphic in a pseudo-element with its own dimensional context:

#graphic {
  position: relative;
  width: 200px;
  height: 100px;
}
#graphic::before {
  position: absolute;
  content: '';
  z-index: -1;
  width: 200px;
  height: 50px;
  background-image: url(image.jpg);
}

_x000D_
_x000D_
#graphic {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    position: relative;_x000D_
}_x000D_
#graphic::before {_x000D_
    content: '';_x000D_
    _x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    z-index: -1;_x000D_
    _x000D_
    background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */_x000D_
}
_x000D_
<div id="graphic">lorem ipsum</div>
_x000D_
_x000D_
_x000D_

Browser support is good, but if you need to support IE8, use a single colon :before. IE has no support for either syntax in versions prior to that.

How to export settings?

Your user settings are in ~/Library/Application\ Support/Code/User.

If you're not concerned about syncing and it's a one time thing, you can just copy the files keybindings.json and settings.json to the corresponding folder on your new machine.

Your extensions are in the ~/.vscode folder. Most extensions aren't using any native bindings and they should be working properly when copied over. You can manually re-install those who do not.

Create Pandas DataFrame from a string

A simple way to do this is to use StringIO.StringIO (python2) or io.StringIO (python3) and pass that to the pandas.read_csv function. E.g:

import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA = StringIO("""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """)

df = pd.read_csv(TESTDATA, sep=";")

Get git branch name in Jenkins Pipeline/Jenkinsfile

Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.

Converting Secret Key into a String and Vice Versa

Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:

  1. *.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html

  2. Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html

  3. Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html

Code snippets: For encoding:

String temp = new String(Base64.getEncoder().encode(key.getEncoded()));

For decoding:

byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");

<hr> tag in Twitter Bootstrap not functioning correctly?

I was able to customize the hrTag by editing the inline styling as such:

<div class="row"> <!-- You can also position the row if need be. -->
<div class="col-md-12 col-lg-12"><!-- set width of column I wanted mine to stretch most of the screen-->
<hr style="min-width:85%; background-color:#a1a1a1 !important; height:1px;"/>
</div>
 </div>

The hrTag is now thicker and more visible; it's also a darker gray color. The bootstrap code is actually very flexible. As the snippet demonstrates above, you can use inline styling or your own custom code. Hope this helps someone.

Laravel: How to Get Current Route Name? (v5 ... v7)

In a controller action, you could just do:

public function someAction(Request $request)
{
    $routeName = $request->route()->getName();
}

$request here is resolved by Laravel's service container.

getName() returns the route name for named routes only, null otherwise (but you could still explore the \Illuminate\Routing\Route object for something else of interest).

In other words, you should have your route defined like this to have "nameOfMyRoute" returned:

Route::get('my/some-action', [
    'as' => 'nameOfMyRoute',
    'uses' => 'MyController@someAction'
]);

The preferred way of creating a new element with jQuery

According to the documentation for 3.4, It is preferred to use attributes with attr() method.

$('<div></div>').attr(
  {
    id: 'some dynanmic|static id',
    "class": 'some dynanmic|static class'
  }
).click(function() {
  $( "span", this ).addClass( "bar" ); // example from the docs
});

How to add a new project to Github using VS Code

You can also use command palette:

  1. (CTRL+SHIFT+P - Win) or (CMD+SHIFT+P - Mac) to open the palette.
  2. Enter 'git', select Git:Clone,
  3. paste github repo URL (https://github.com/Username/repo),
  4. than you are ready to go with Source control section from the left menu.

Does the same thing as the terminal.

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

This could be an error in the web.config file.

Open up your URL in your browser, example:

http://localhost:61277/Email.svc

Check if you have a 500 Error.

HTTP Error 500.19 - Internal Server Error

Look for the error in these sections:

Config Error

Config File

Eclipse C++: Symbol 'std' could not be resolved

The includes folder in the project is probably missing /usr/include/c++. Goto your project in project explorer, right click -> Properties -> C\C++ Build -> Environment -> add -> value= /usr/include/c++. Restart eclipse.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

No Main class found in NetBeans

Press the hammer to the left of the green arrow (run), for the program to clean & build project. Press green arrow. Select Main Class.

Hope it works for u.

error C4996: 'scanf': This function or variable may be unsafe in c programming

It sounds like it's just a compiler warning.

Usage of scanf_s prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s

Good explanation as to why scanf can be dangerous: Disadvantages of scanf

So as suggested, you can try replacing scanf with scanf_s or disable the compiler warning.

Overflow Scroll css is not working in the div

in my case, only height: 100vh fix the problem with the expected behavior

Is there a way to set background-image as a base64 encoded image?

Had the same problem with base64. For anyone in the future with the same problem:

url = "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";

This would work executed from console, but not from within a script:

$img.css("background-image", "url('" + url + "')");

But after playing with it a bit, I came up with this:

var img = new Image();
img.src = url;
$img.css("background-image", "url('" + img.src + "')");

No idea why it works with a proxy image, but it does. Tested on Firefox Dev 37 and Chrome 40.

Hope it helps someone.

EDIT

Investigated a little bit further. It appears that sometimes base64 encoding (at least in my case) breaks with CSS because of line breaks present in the encoded value (in my case value was generated dynamically by ActionScript).

Simply using e.g.:

$img.css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");

works too, and even seems to be faster by a few ms than using a proxy image.

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.7;
}

The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.

<div disabled>
  /* Contents */
</div>

How to print to console when using Qt

I found this most useful:

#include <QTextStream>

QTextStream out(stdout);
foreach(QString x, strings)
    out << x << endl;

MySQL: When is Flush Privileges in MySQL really needed?

2 points in addition to all other good answers:

1:

what are the Grant Tables?

from dev.mysql.com

The MySQL system database includes several grant tables that contain information about user accounts and the privileges held by them.

clari?cation: in MySQL, there are some inbuilt databases , one of them is "mysql" , all the tables on "mysql" database have been called as grant tables

2:

note that if you perform:

UPDATE a_grant_table SET password=PASSWORD('1234') WHERE test_col = 'test_val';

and refresh phpMyAdmin , you'll realize that your password has been changed on that table but even now if you perform:

mysql -u someuser -p

your access will be denied by your new password until you perform :

FLUSH PRIVILEGES;

Why does 'git commit' not save my changes?

if you have more files in my case i have 7000 image files when i try to add them from project's route folder it hasn't added them but when i go to the image folder everything is ok. Go through the target folder and command like abows

git add .
git commit -am "image uploading"
git push origin master

git push origin master Enumerating objects: 6574, done. Counting objects: 100% (6574/6574), done. Delta compression using up to 4 threads Compressing objects: 100% (6347/6347), done. Writing objects: 28% (1850/6569), 142.17 MiB | 414.00 KiB/s

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

In my case I had a Kotlin class with some fields which were not open so the generated Java setters and getters would be final. Solved it by adding open keyword to each field.

Before:

open class User(
    var id: String = "",
    var email: String = ""
)

After:

open class User(
    open var id: String = "",
    open var email: String = ""
)

Database, Table and Column Naming Conventions?

Take a look at ISO 11179-5: Naming and identification principles You can get it here: http://metadata-standards.org/11179/#11179-5

I blogged about it a while back here: ISO-11179 Naming Conventions

Make Frequency Histogram for Factor Variables

The reason you are getting the unexpected result is that hist(...) calculates the distribution from a numeric vector. In your code, table(animalFactor) behaves like a numeric vector with three elements: 1, 3, 7. So hist(...) plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.

Here's a way to do this using ggplot:

library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))

You would get precisely the same result using animalFactor instead of animals in the code above.

IsNumeric function in c#

To totally steal from Bill answer you can make an extension method and use some syntactic sugar to help you out.

Create a class file, StringExtensions.cs

Content:

public static class StringExt
{
    public static bool IsNumeric(this string text)
    {
        double test;
        return double.TryParse(text, out test);
    }
}

EDIT: This is for updated C# 7 syntax. Declaring out parameter in-line.

public static class StringExt
{
    public static bool IsNumeric(this string text) => double.TryParse(text, out _);

}

Call method like such:

var text = "I am not a number";
text.IsNumeric()  //<--- returns false

Copy an entire worksheet to a new worksheet in Excel 2010

It is simpler just to run an exact copy like below to put the copy in as the last sheet

Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Master")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub

Git update submodules recursively

git submodule update --recursive

You will also probably want to use the --init option which will make it initialize any uninitialized submodules:

git submodule update --init --recursive

Note: in some older versions of Git, if you use the --init option, already-initialized submodules may not be updated. In that case, you should also run the command without --init option.

Setting an environment variable before a command in Bash is not working for the second command in a pipe

Use env.

For example, env FOO=BAR command. Note that the environment variables will be restored/unchanged again when command finishes executing.

Just be careful about about shell substitution happening, i.e. if you want to reference $FOO explicitly on the same command line, you may need to escape it so that your shell interpreter doesn't perform the substitution before it runs env.

$ export FOO=BAR
$ env FOO=FUBAR bash -c 'echo $FOO'
FUBAR
$ echo $FOO
BAR

How to change an application icon programmatically in Android?

@P-A's solution partially works for me. Detail my findings below:

1) The first code snippet is incorrect, see below:

<activity
    ...
    <intent-filter>
        ==> <action android:name="android.intent.action.MAIN" /> <== This line shouldn't be deleted, otherwise will have compile error
        <category android:name="android.intent.category.LAUNCHER" /> //DELETE THIS LINE
    </intent-filter>
</activity>

2) Should use following code to disable all icons before enabling another one, otherwise it will add a new icon, instead of replacing it.

getPackageManager().setComponentEnabledSetting(
        getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

BUT, if you use code above, then shortcut on homescreen will be removed! And it won't be automatically added back. You might be able to programmatically add icon back, but it probably won't stay in the same position as before.

3) Note that the icon won't get changed immediately, it might take several seconds. If you click it right after changing, you might get an error saying: "App isn't installed".

So, IMHO this solution is only suitable for changing icon in app launcher only, not for shortcuts (i.e. the icon on homescreen)

Including a .js file within a .js file

I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

if (horus.script.broken) {
    document.writeln('<script type="text/javascript" src="'+script+'"></script>');   
    horus.script.loaded(script);
} else {
    var s=document.createElement('script');
    s.type='text/javascript';
    s.src=script;
    s.async=true;

    if (horus.brokenDOM){
        s.onreadystatechange=
            function () {
                if (this.readyState=='loaded' || this.readyState=='complete'){
                    horus.script.loaded(script);
                }
        }
    }else{
        s.onload=function () { horus.script.loaded(script) };
    }

    document.head.appendChild(s);
}

where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).

Get all messages from Whatsapp

You can get access to the WhatsApp data base located on the SD card only as a root user I think. if you open "\data\data\com.whatsapp" you will see that "databases" is linked to "\firstboot\sqlite\com.whatsapp\"

target="_blank" vs. target="_new"

Caution - remember to always include the "quotes" - at least on Chrome, target=_blank (no quotes) is NOT THE SAME as target="_blank" (with quotes).

The latter opens each link in a new tab/window. The former (missing quotes) opens the first link you click in one new tab/window, then overwrites that same tab/window with each subsequent link you click (that's named also with the missing quotes).

How/when to generate Gradle wrapper files?

This is the command to use to tell Gradle to upgrade the wrapper such that it will grab the distribution versions of libraries that includes source code:

./gradlew wrapper --gradle-version <version> --distribution-type all

Specifying the distribution-type with "all" will make sure Gradle downloads source files for use by your development environment.

Pros:

  • IDEs will have immediate access to source code. For example, Intellij IDEA won't prompt you to update your build scripts to include the source distro (because this command already did that)

Cons:

  • Longer/Bigger build process because it's downloading source code. This is a waste of time/space on a build or CI server where the source code is not necessary.

Please comment or provide another answer if you know of any command line option to tell Gradle not to download sources on a build server.

How to stick a footer to bottom in css?

I think a lot of folks are looking for a footer on the bottom that scrolls instead of being fixed, called a sticky footer. Fixed footers will cover body content when the height is too short. You have to set the html, body, and page container to a height of 100%, set your footer to absolute position bottom. Your page content container needs a relative position for this to work. Your footer has a negative margin equal to height of footer minus bottom margin of page content. See the example page I posted.

Example with notes: http://markbokil.com/code/bottomfooter/

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

How to get file path in iPhone app

Remember that the "folders/groups" you make in xcode, those which are yellowish are not reflected as real folders in your iPhone app. They are just there to structure your XCode project. You can nest as many yellow group as you want and they still only serve the purpose of organizing code in XCode.

EDIT

Make a folder outside of XCode then drag it over, and select "Create folder references for any added folders" instead of "Create groups for any added folders" in the popup.

Can I open a dropdownlist using jQuery

You can easily simulate a click on an element, but a click on a <select> won’t open up the dropdown.

Using multiple selects can be problematic. Perhaps you should consider radio buttons inside a container element which you can expand and contract as needed.

jQuery: How to get to a particular child of a parent?

If I understood your problem correctly, $(this).parents('.box').children('.something1') Is this what you are looking for?

Multiple modals overlay

EDIT: Bootstrap 3.3.4 has solved this problem (and other modal issues) so if you can update your bootstrap CSS and JS that would be the best solution. If you can't update the solution below will still work and essentially does the same thing as bootstrap 3.3.4 (recalculate and apply padding).

As Bass Jobsen pointed out, newer versions of Bootstrap have the z-index solved. The modal-open class and padding-right were still problems for me but this scripts inspired by Yermo Lamers solution solves it. Just drop it in your JS file and enjoy.

$(document).on('hide.bs.modal', '.modal', function (event) {
    var padding_right = 0;
    $.each($('.modal'), function(){
        if($(this).hasClass('in') && $(this).modal().data('bs.modal').scrollbarWidth > padding_right) {
            padding_right = $(this).modal().data('bs.modal').scrollbarWidth
        }
    });
    $('body').data('padding_right', padding_right + 'px');
});

$(document).on('hidden.bs.modal', '.modal', function (event) {
    $('body').data('open_modals', $('body').data('open_modals') - 1);
    if($('body').data('open_modals') > 0) {
        $('body').addClass('modal-open');
        $('body').css('padding-right', $('body').data('padding_right'));
    }
});

$(document).on('shown.bs.modal', '.modal', function (event) {
    if (typeof($('body').data('open_modals')) == 'undefined') {
        $('body').data('open_modals', 0);
    }
    $('body').data('open_modals', $('body').data('open_modals') + 1);
    $('body').css('padding-right', (parseInt($('body').css('padding-right')) / $('body').data('open_modals') + 'px'));
});

In Maven how to exclude resources from the generated jar?

This calls exactly for the using the Maven JAR Plugin

For example, if you want to exclude everything under src/test/resources/ from the final jar, put this:

<build>

        <plugins>
            <!-- configure JAR build -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <excludes>
                        <exclude>src/test/resources/**</exclude>
                    </excludes>
                </configuration>
            </plugin>

...

Files under src/test/resources/ will still be available on class-path, they just won't be in resulting JAR.

Can't push image to Amazon ECR - fails with "no basic auth credentials"

Simply run whatever returned in step one would fix the issue.

Remove CSS class from element with JavaScript (no jQuery)

The right and standard way to do it is using classList. It is now widely supported in the latest version of most modern browsers:

ELEMENT.classList.remove("CLASS_NAME");

_x000D_
_x000D_
remove.onclick = () => {_x000D_
  const el = document.querySelector('#el');_x000D_
  if (el.classList.contains("red")) {_x000D_
    el.classList.remove("red");_x000D_
_x000D_
  }_x000D_
}
_x000D_
.red {_x000D_
  background: red_x000D_
}
_x000D_
<div id='el' class="red"> Test</div>_x000D_
<button id='remove'>Remove Class</button>
_x000D_
_x000D_
_x000D_

Documentation: https://developer.mozilla.org/en/DOM/element.classList

How do you query for "is not null" in Mongo?

In an ideal case, you would like to test for all three values, null, "" or empty(field doesn't exist in the record)

You can do the following.

db.users.find({$and: [{"name" : {$nin: ["", null]}}, {"name" : {$exists: true}}]})

Convert byte to string in Java

System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));

Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.

How can I make one python file run another?

from subprocess import Popen

Popen('python filename.py')

or how-can-i-make-one-python-file-run-another-file

Check if an array contains duplicate values

Wrote this to initialize a new array of length uniqueIndexCount. It's presented here minus unrelated logic.

    public Vector3[] StandardizeVertices(Vector3[] dimensions, int standard)
    {
        //determine the number of unique dimension vectors
        int uniqueIndexCount = 0;
        for (int a=0; a < dimensions.Length; ++a)
        {
            int duplicateIndexCount = 0;
            for (int b = a; b < dimensions.Length; ++b)
            {
                if(a!=b && dimensions[a] == dimensions[b])
                {
                    duplicateIndexCount++;
                }
            }
            if (duplicateIndexCount == 0)
            {
                uniqueIndexCount++;
            }
        }
        Debug.Log("uniqueIndexCount: "+uniqueIndexCount);
        return dimensions;
    }

What are some resources for getting started in operating system development?

I would like to include this repo How-to-Make-a-Computer-Operating-System by Samy Pesse. Is a work-in-progress. Very interesting.

Cross-reference (named anchor) in markdown

I will quickly complement for cases where the header contains emojis, in that case it is simpler to just remove the emoji in the link of the reference. For example

# ? Title 2
....
[Take me to title 2](#-title-2)

There are some cases where this does not work for a weird reason, for example here in setup. The solution in that case is to include the whole code for the emoji as well.

Unable to install Android Studio in Ubuntu

For Fedora (tested for Fedora 23/24) run

dnf install compat-libstdc++-296 compat-libstdc++-33 glibc libgcc nss-softokn-freebl libstdc++ ncurses-libs zlib-devel.i686 ncurses-devel.i686 ant

How to generate components in a specific folder with Angular CLI?

Try to use

ng g component plainsight/some-name.component.ts

Or try it manually, if you feel more comfortable.

VBA vlookup reference in different sheet

try this:

Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("Sheet2")

With ws
    .Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With

End Sub

This just the simplified version of what you want.
No need to use Application if you will just output the answer in the Range("E2").

If you want to stick with your logic, declare the variables.
See below for example.

Sub Test()

Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String

Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")

With ws2
    On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
    MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
    On Error GoTo 0
    If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With

End Sub

Hope this get's you started.

How do I make a WinForms app go Full Screen

On the Form Move Event add this:

private void Frm_Move (object sender, EventArgs e)
{
    Top = 0; Left = 0;
    Size = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}

How to replace a hash key with another key

h.inject({}) { |m, (k,v)| m[k.sub(/^_/,'')] = v; m }

illegal character in path

Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.

The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.

How do I enable php to work with postgresql?

$dbh = new PDO('pgsql:host=localhost;port=5432;dbname=###;user=###;password=##');

For PDO type connection uncomment

extension=php_pdo_pgsql.dll and comment with

;extension=php_pgsql.dll

$dbh = pg_connect("host=localhost dbname=### user=### password=####");

For pgconnect type connection comment

;extension=php_pdo_pgsql.dll and uncomment

extension=php_pgsql.dll

Both the connections should work.

Finding the median of an unsorted array

I have already upvoted the @dasblinkenlight answer since the Median of Medians algorithm in fact solves this problem in O(n) time. I only want to add that this problem could be solved in O(n) time by using heaps also. Building a heap could be done in O(n) time by using the bottom-up. Take a look to the following article for a detailed explanation Heap sort

Supposing that your array has N elements, you have to build two heaps: A MaxHeap that contains the first N/2 elements (or (N/2)+1 if N is odd) and a MinHeap that contains the remaining elements. If N is odd then your median is the maximum element of MaxHeap (O(1) by getting the max). If N is even, then your median is (MaxHeap.max()+MinHeap.min())/2 this takes O(1) also. Thus, the real cost of the whole operation is the heaps building operation which is O(n).

BTW this MaxHeap/MinHeap algorithm works also when you don't know the number of the array elements beforehand (if you have to resolve the same problem for a stream of integers for e.g). You can see more details about how to resolve this problem in the following article Median Of integer streams

Ping with timestamp on Windows CLI

Try this instead:

ping -c2 -s16 sntdn | awk '{print NR " | " strftime("%Y-%m-%d_%H:%M:%S") " | " $0  }'

Check if it suits you

How can I upgrade NumPy?

FYI, when you using or importing TensorFlow, a similar error may occur, like (caused by NumPy):

RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 23, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 60, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: numpy.core.multiarray failed to import


Error importing tensorflow.  Unless you are using bazel,
you should not try to import tensorflow from its source directory;
please exit the tensorflow source tree, and relaunch your python interpreter
from there.

I followed Elmira's and Drew's solution, sudo easy_install numpy, and it worked!

sudo easy_install numpy
Searching for numpy
Best match: numpy 1.11.3
Removing numpy 1.8.2 from easy-install.pth file
Adding numpy 1.11.3 to easy-install.pth file

Using /usr/local/lib/python2.7/dist-packages
Processing dependencies for numpy
Finished processing dependencies for numpy

After that I could use TensorFlow without error.

java.net.BindException: Address already in use: JVM_Bind <null>:80

If you have some process listening on port 8080 then you can always configure tomcat to listen on a different port. To change the listener port by editing your server.xml located under tomcat server conf directory.

Search for Connector port="8080" in server.xml and change the port number to some other port.

Add Insecure Registry to Docker

I happened to encounter a similar kind of issue after setting up local internal JFrog Docker Private Registry on Amazon Linux.

THE followings I did to solve the issue:

Added "--insecure-registry xx.xx.xx.xx:8081" by modifying the OPTIONS variable in the /etc/sysconfig/docker file:

OPTIONS="--default-ulimit nofile=1024:40961 --insecure-registry hostname:8081"

Then restarted the docker.

I was then able to login to the local docker registry using:

docker login -u admin -p password hostname:8081

What are metaclasses in Python?

What are metaclasses? What do you use them for?

TLDR: A metaclass instantiates and defines behavior for a class just like a class instantiates and defines behavior for an instance.

Pseudocode:

>>> Class(...)
instance

The above should look familiar. Well, where does Class come from? It's an instance of a metaclass (also pseudocode):

>>> Metaclass(...)
Class

In real code, we can pass the default metaclass, type, everything we need to instantiate a class and we get a class:

>>> type('Foo', (object,), {}) # requires a name, bases, and a namespace
<class '__main__.Foo'>

Putting it differently

  • A class is to an instance as a metaclass is to a class.

    When we instantiate an object, we get an instance:

    >>> object()                          # instantiation of class
    <object object at 0x7f9069b4e0b0>     # instance
    

    Likewise, when we define a class explicitly with the default metaclass, type, we instantiate it:

    >>> type('Object', (object,), {})     # instantiation of metaclass
    <class '__main__.Object'>             # instance
    
  • Put another way, a class is an instance of a metaclass:

    >>> isinstance(object, type)
    True
    
  • Put a third way, a metaclass is a class's class.

    >>> type(object) == type
    True
    >>> object.__class__
    <class 'type'>
    

When you write a class definition and Python executes it, it uses a metaclass to instantiate the class object (which will, in turn, be used to instantiate instances of that class).

Just as we can use class definitions to change how custom object instances behave, we can use a metaclass class definition to change the way a class object behaves.

What can they be used for? From the docs:

The potential uses for metaclasses are boundless. Some ideas that have been explored include logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.

Nevertheless, it is usually encouraged for users to avoid using metaclasses unless absolutely necessary.

You use a metaclass every time you create a class:

When you write a class definition, for example, like this,

class Foo(object): 
    'demo'

You instantiate a class object.

>>> Foo
<class '__main__.Foo'>
>>> isinstance(Foo, type), isinstance(Foo, object)
(True, True)

It is the same as functionally calling type with the appropriate arguments and assigning the result to a variable of that name:

name = 'Foo'
bases = (object,)
namespace = {'__doc__': 'demo'}
Foo = type(name, bases, namespace)

Note, some things automatically get added to the __dict__, i.e., the namespace:

>>> Foo.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'Foo' objects>, 
'__module__': '__main__', '__weakref__': <attribute '__weakref__' 
of 'Foo' objects>, '__doc__': 'demo'})

The metaclass of the object we created, in both cases, is type.

(A side-note on the contents of the class __dict__: __module__ is there because classes must know where they are defined, and __dict__ and __weakref__ are there because we don't define __slots__ - if we define __slots__ we'll save a bit of space in the instances, as we can disallow __dict__ and __weakref__ by excluding them. For example:

>>> Baz = type('Bar', (object,), {'__doc__': 'demo', '__slots__': ()})
>>> Baz.__dict__
mappingproxy({'__doc__': 'demo', '__slots__': (), '__module__': '__main__'})

... but I digress.)

We can extend type just like any other class definition:

Here's the default __repr__ of classes:

>>> Foo
<class '__main__.Foo'>

One of the most valuable things we can do by default in writing a Python object is to provide it with a good __repr__. When we call help(repr) we learn that there's a good test for a __repr__ that also requires a test for equality - obj == eval(repr(obj)). The following simple implementation of __repr__ and __eq__ for class instances of our type class provides us with a demonstration that may improve on the default __repr__ of classes:

class Type(type):
    def __repr__(cls):
        """
        >>> Baz
        Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
        >>> eval(repr(Baz))
        Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
        """
        metaname = type(cls).__name__
        name = cls.__name__
        parents = ', '.join(b.__name__ for b in cls.__bases__)
        if parents:
            parents += ','
        namespace = ', '.join(': '.join(
          (repr(k), repr(v) if not isinstance(v, type) else v.__name__))
               for k, v in cls.__dict__.items())
        return '{0}(\'{1}\', ({2}), {{{3}}})'.format(metaname, name, parents, namespace)
    def __eq__(cls, other):
        """
        >>> Baz == eval(repr(Baz))
        True            
        """
        return (cls.__name__, cls.__bases__, cls.__dict__) == (
                other.__name__, other.__bases__, other.__dict__)

So now when we create an object with this metaclass, the __repr__ echoed on the command line provides a much less ugly sight than the default:

>>> class Bar(object): pass
>>> Baz = Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
>>> Baz
Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})

With a nice __repr__ defined for the class instance, we have a stronger ability to debug our code. However, much further checking with eval(repr(Class)) is unlikely (as functions would be rather impossible to eval from their default __repr__'s).

An expected usage: __prepare__ a namespace

If, for example, we want to know in what order a class's methods are created in, we could provide an ordered dict as the namespace of the class. We would do this with __prepare__ which returns the namespace dict for the class if it is implemented in Python 3:

from collections import OrderedDict

class OrderedType(Type):
    @classmethod
    def __prepare__(metacls, name, bases, **kwargs):
        return OrderedDict()
    def __new__(cls, name, bases, namespace, **kwargs):
        result = Type.__new__(cls, name, bases, dict(namespace))
        result.members = tuple(namespace)
        return result

And usage:

class OrderedMethodsObject(object, metaclass=OrderedType):
    def method1(self): pass
    def method2(self): pass
    def method3(self): pass
    def method4(self): pass

And now we have a record of the order in which these methods (and other class attributes) were created:

>>> OrderedMethodsObject.members
('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4')

Note, this example was adapted from the documentation - the new enum in the standard library does this.

So what we did was instantiate a metaclass by creating a class. We can also treat the metaclass as we would any other class. It has a method resolution order:

>>> inspect.getmro(OrderedType)
(<class '__main__.OrderedType'>, <class '__main__.Type'>, <class 'type'>, <class 'object'>)

And it has approximately the correct repr (which we can no longer eval unless we can find a way to represent our functions.):

>>> OrderedMethodsObject
OrderedType('OrderedMethodsObject', (object,), {'method1': <function OrderedMethodsObject.method1 at 0x0000000002DB01E0>, 'members': ('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4'), 'method3': <function OrderedMet
hodsObject.method3 at 0x0000000002DB02F0>, 'method2': <function OrderedMethodsObject.method2 at 0x0000000002DB0268>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'OrderedMethodsObject' objects>, '__doc__': None, '__d
ict__': <attribute '__dict__' of 'OrderedMethodsObject' objects>, 'method4': <function OrderedMethodsObject.method4 at 0x0000000002DB0378>})

Solve Cross Origin Resource Sharing with Flask

I struggled a lot with something similar. Try the following:

  1. Use some sort of browser plugin which can display the HTML headers.
  2. Enter the URL to your service, and view the returned header values.
  3. Make sure Access-Control-Allow-Origin is set to one and only one domain, which should be the request origin. Do not set Access-Control-Allow-Origin to *.

If this doesn't help, take a look at this article. It's on PHP, but it describes exactly which headers must be set to which values for CORS to work.

CORS That Works In IE, Firefox, Chrome And Safari

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

This declaration has no storage class or type specifier in C++

You can declare an object of a class in another Class,that's possible but you cant initialize that object. For that you need to do something like this :--> (inside main)

Orderbook o1;
o1.m.check(side)

but that would be unnecessary. Keeping things short :-

You can't call functions inside a Class

Create excel ranges using column numbers in vba?

Range.EntireColumn

Yes! You can use Range.EntireColumn MSDN

dim column : column = 4

dim column_range : set column_range = Sheets(1).Cells(column).EntireColumn

Range("ColumnName:ColumnName")

If you were after a specific column, you could create a hard coded column range with the syntax e.g. Range("D:D").

However, I'd use entire column as it provides more flexibility to change that column at a later time.

Worksheet.Columns

Worksheet.Columns provides Range access to a column within a worksheet. MSDN

If you would like access to the first column of the first sheet. You would call the Columns function on the worksheet.

dim column_range: set column_range = Sheets(1).Columns(1)

The Columns property is also available on any Range MSDN

EntireRow can also be useful if you have a range for a single cell but would like to reach other cells on the row, akin to a LOOKUP

dim id : id = 12345


dim found : set found = Range("A:A").Find(id)

if not found is Nothing then
    'Get the fourth cell from the match
    MsgBox found.EntireRow.Cells(4)
end if

What is the difference between Forking and Cloning on GitHub?

While @AniketThakur's answer is very good. No one has answered the following question yet.

Can I only send pull requests via GitHub if I've forked a project?

No. If you are a contributor to a repository, you can: Make a local clone. Make a local branch. Add commits to that branch. Push the local branch back to github (creating a remote branch in the process). Make a pull request requesting for that branch to be merged into the master branch (or whatever branch you like).

How to save password when using Subversion from the console

I'm using the TortoiseSVN client on Windows, and for me, setting store-passwords parameter as yes in %USERPROFILE%\AppData\Roaming\Subversion\config does not help to store the password.

The password was successfully saved after removing this folder (just in case renaming):

%USERPROFILE%\AppData\Roaming\Subversion\auth

Environment:

Windows 7, TortoiseSVN 1.7.11 (Build 23600 - 64 bit, 2012-12-12T19:08:52), Subversion 1.7.8.

Using a global variable with a thread

Thanks so much Jason Pan for suggesting that method. The thread1 if statement is not atomic, so that while that statement executes, it's possible for thread2 to intrude on thread1, allowing non-reachable code to be reached. I've organized ideas from the prior posts into a complete demonstration program (below) that I ran with Python 2.7.

With some thoughtful analysis I'm sure we could gain further insight, but for now I think it's important to demonstrate what happens when non-atomic behavior meets threading.

# ThreadTest01.py - Demonstrates that if non-atomic actions on
# global variables are protected, task can intrude on each other.
from threading import Thread
import time

# global variable
a = 0; NN = 100

def thread1(threadname):
    while True:
      if a % 2 and not a % 2:
          print("unreachable.")
    # end of thread1

def thread2(threadname):
    global a
    for _ in range(NN):
        a += 1
        time.sleep(0.1)
    # end of thread2

thread1 = Thread(target=thread1, args=("Thread1",))
thread2 = Thread(target=thread2, args=("Thread2",))

thread1.start()
thread2.start()

thread2.join()
# end of ThreadTest01.py

As predicted, in running the example, the "unreachable" code sometimes is actually reached, producing output.

Just to add, when I inserted a lock acquire/release pair into thread1 I found that the probability of having the "unreachable" message print was greatly reduced. To see the message I reduced the sleep time to 0.01 sec and increased NN to 1000.

With a lock acquire/release pair in thread1 I didn't expect to see the message at all, but it's there. After I inserted a lock acquire/release pair also into thread2, the message no longer appeared. In hind signt, the increment statement in thread2 probably also is non-atomic.

OperationalError: database is locked

The practical reason for this is often that the python or django shells have opened a request to the DB and it wasn't closed properly; killing your terminal access often frees it up. I had this error on running command line tests today.

Edit: I get periodic upvotes on this. If you'd like to kill access without rebooting the terminal, then from commandline you can do:

from django import db
db.connections.close_all()

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

add this line in your build.gradle

 defaultConfig {
    ............
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    compileOptions.encoding = 'ISO-8859-1'
    multiDexEnabled true
}

How do I calculate someone's age based on a DateTime type birthday?

This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb.

public int GetAge(DateTime birthDate)
{
    int age = DateTime.Now.Year - birthDate.Year;

    if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
        age--;

    return age;
}




How can I dynamically add a directive in AngularJS?

Josh David Miller is correct.

PCoelho, In case you're wondering what $compile does behind the scenes and how HTML output is generated from the directive, please take a look below

The $compile service compiles the fragment of HTML("< test text='n' >< / test >") that includes the directive("test" as an element) and produces a function. This function can then be executed with a scope to get the "HTML output from a directive".

var compileFunction = $compile("< test text='n' > < / test >");
var HtmlOutputFromDirective = compileFunction($scope);

More details with full code samples here: http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs

Temporarily disable all foreign key constraints

A good reference is given at : http://msdn.microsoft.com/en-us/magazine/cc163442.aspx under the section "Disabling All Foreign Keys"

Inspired from it, an approach can be made by creating a temporary table and inserting the constraints in that table, and then dropping the constraints and then reapplying them from that temporary table. Enough said here is what i am talking about

 SET NOCOUNT ON

    DECLARE @temptable TABLE(
       Id INT PRIMARY KEY IDENTITY(1, 1),
       FKConstraintName VARCHAR(255),
       FKConstraintTableSchema VARCHAR(255),
       FKConstraintTableName VARCHAR(255),
       FKConstraintColumnName VARCHAR(255),
       PKConstraintName VARCHAR(255),
       PKConstraintTableSchema VARCHAR(255),
       PKConstraintTableName VARCHAR(255),
       PKConstraintColumnName VARCHAR(255)    
    )

    INSERT INTO @temptable(FKConstraintName, FKConstraintTableSchema, FKConstraintTableName, FKConstraintColumnName)
    SELECT 
       KeyColumnUsage.CONSTRAINT_NAME, 
       KeyColumnUsage.TABLE_SCHEMA, 
       KeyColumnUsage.TABLE_NAME, 
       KeyColumnUsage.COLUMN_NAME 
    FROM 
       INFORMATION_SCHEMA.KEY_COLUMN_USAGE KeyColumnUsage
          INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TableConstraints
             ON KeyColumnUsage.CONSTRAINT_NAME = TableConstraints.CONSTRAINT_NAME
    WHERE
       TableConstraints.CONSTRAINT_TYPE = 'FOREIGN KEY'

    UPDATE @temptable SET
       PKConstraintName = UNIQUE_CONSTRAINT_NAME
    FROM 
       @temptable tt
          INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ReferentialConstraint
             ON tt.FKConstraintName = ReferentialConstraint.CONSTRAINT_NAME

    UPDATE @temptable SET
       PKConstraintTableSchema  = TABLE_SCHEMA,
       PKConstraintTableName  = TABLE_NAME
    FROM @temptable tt
       INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TableConstraints
          ON tt.PKConstraintName = TableConstraints.CONSTRAINT_NAME

    UPDATE @temptable SET
       PKConstraintColumnName = COLUMN_NAME
    FROM @temptable tt
       INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KeyColumnUsage
          ON tt.PKConstraintName = KeyColumnUsage.CONSTRAINT_NAME


    --Now to drop constraint:
    SELECT
       '
       ALTER TABLE [' + FKConstraintTableSchema + '].[' + FKConstraintTableName + '] 
       DROP CONSTRAINT ' + FKConstraintName + '

       GO'
    FROM
       @temptable

    --Finally to add constraint:
    SELECT
       '
       ALTER TABLE [' + FKConstraintTableSchema + '].[' + FKConstraintTableName + '] 
       ADD CONSTRAINT ' + FKConstraintName + ' FOREIGN KEY(' + FKConstraintColumnName + ') REFERENCES [' + PKConstraintTableSchema + '].[' + PKConstraintTableName + '](' + PKConstraintColumnName + ')

       GO'
    FROM
       @temptable

    GO

What exactly does += do in python?

It is not mere a syntactic sugar. Try this:

x = []                 # empty list
x += "something"       # iterates over the string and appends to list
print(x)               # ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']

versus

x = []                 # empty list
x = x + "something"    # TypeError: can only concatenate list (not "str") to list

The += operator invokes the __iadd__() list method, while + one invokes the __add__() one. They do different things with lists.

Java: Get last element after split

You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of lastone.length and lastwo.length .

Hiding the address bar of a browser (popup)

You could make the webpage scroll down to a position where you can't see the address bar, and if the user scrolls, the page should return to your set position. In that way, Mobile browsers when scrolled down , will try to guve you full-screen experience. So it will hide the address bar. I don't know the code, someone else might put up the code.

Java: Retrieving an element from a HashSet

It sounds like you're essentially trying to use the hash code as a key in a map (which is what HashSets do behind the scenes). You could just do it explicitly, by declaring HashMap<Integer, MyHashObject>.

There is no get for HashSets because typically the object you would supply to the get method as a parameter is the same object you would get back.

What is the difference between null and System.DBNull.Value?

Well, null is not an instance of any type. Rather, it is an invalid reference.

However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

*We would normally say null, but I don't want to confound the issue.

So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

How to check whether a variable is a class or not?

This check is compatible with both Python 2.x and Python 3.x.

import six
isinstance(obj, six.class_types)

This is basically a wrapper function that performs the same check as in andrea_crotti answer.

Example:

>>> import datetime
>>> isinstance(datetime.date, six.class_types)
>>> True
>>> isinstance(datetime.date.min, six.class_types)
>>> False

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

Detect Safari using jQuery

The only way I found is check if navigator.userAgent contains iPhone or iPad word

if (navigator.userAgent.toLowerCase().match(/(ipad|iphone)/)) {
    //is safari
}

WordPress asking for my FTP credentials to install plugins

There's a lot of similar responses to this question, but none of them fully touch on the root cause. Sebastian Schmid's comment on the original post touches on it but not fully. Here's my take as of 2018-11-06:

Root Cause

When you try to upload a plugin through the WordPress admin interface, WordPress will make a call over to a function called "get_filesystem_method()" (ref: /wp-admin/includes/file.php:1549). This routine will attempt to write a file to the location in question (in this case the plugin directory). It can of course fail here immediately if file permissions aren't setup right to allow the WordPress user (think the user identity executing the php) to write the file to the location in question.

If the file can be created, this function then detects the file owner of the temporary file, along with the file owner of the function's current file (ref: /wp-admin/includes/file.php:1572) and compares the two. If they match then, in WordPress's words, "WordPress is creating files as the same owner as the WordPress files, this means it's safe to modify & create new files via PHP" and your plugin is uploaded successfully without the FTP Credentials prompt. If they don't match, you get the FTP Credentials prompt.

Fixes

  1. Ensure the plugin directory is writable by the identity running your php process.
  2. Ensure the identity that is running your php process is the file owner for either:

    a) All WordPress application files, or...
    b) At the very least the /wp-admin/includes/file.php file

Final Comments

I'm not overly keen on specifically applying file ownership to the file.php to work around this issue (it feels a tad hacky to say the least!). It seems to me at this point that the WordPress code base is leaning towards having us execute the PHP process under the same user principal as the file owner for the WordPress application files. I would welcome some comments from the community on this.

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

How to get the command line args passed to a running process on unix/linux systems?

If you want to get a long-as-possible (not sure what limits there are), similar to Solaris' pargs, you can use this on Linux & OSX:

ps -ww -o pid,command [-p <pid> ... ]

How to change the timeout on a .NET WebClient object

For completeness, here's kisp's solution ported to VB (can't add code to a comment)

Namespace Utils

''' <summary>
''' Subclass of WebClient to provide access to the timeout property
''' </summary>
Public Class WebClient
    Inherits System.Net.WebClient

    Private _TimeoutMS As Integer = 0

    Public Sub New()
        MyBase.New()
    End Sub
    Public Sub New(ByVal TimeoutMS As Integer)
        MyBase.New()
        _TimeoutMS = TimeoutMS
    End Sub
    ''' <summary>
    ''' Set the web call timeout in Milliseconds
    ''' </summary>
    ''' <value></value>
    Public WriteOnly Property setTimeout() As Integer
        Set(ByVal value As Integer)
            _TimeoutMS = value
        End Set
    End Property


    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
        If _TimeoutMS <> 0 Then
            w.Timeout = _TimeoutMS
        End If
        Return w
    End Function

End Class

End Namespace

Drawing Isometric game worlds

Real problem is when you need draw some tile/sprites intersecting/spanning two or more other tiles.

After 2 (hard) months of personal analisys of problem I finally found and implemented a "correct render drawing" for my new cocos2d-js game. Solution consists in mapping, for each tile (susceptible), which sprites are "front, back, top and behind". Once doing that you can draw them following a "recursive logic".

Composer update memory limit

You can change the memory_limit value in your php.ini

Try increasing the limit in your php.ini file

Use -1 for unlimited or define an explicit value like 2G

memory_limit = -1

Note: Composer internally increases the memory_limit to 1.5G.

Read the documentation getcomposer.org

How to set breakpoints in inline Javascript in Google Chrome?

Refresh the page containing the script whilst the developer tools are open on the scripts tab. This will add a (program) entry in the file list which shows the html of the page including the script. From here you can add breakpoints.

StringStream in C#

Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?

The library provides a StringWriter: TextWriter but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?


After the Update:

void Main() 
{
  string myString;  // outside using

  using (MemoryStream stream = new MemoryStream ())
  {
     Print(stream);
     myString = Encoding.UTF8.GetString(stream.ToArray());
  }
  ... 

}

You may want to change UTF8 to ASCII, depending on the encoding used by Print().

NGINX - No input file specified. - php Fast/CGI

server {
    server_name www.test.com test.com;
    access_log /sites/test/logs/access.log;
    error_log /sites/test/logs/error.log;
    root /sites/test;

 location ~ / {

index index.php
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME `$document_root/service/public$fastcgi_script_name`;
}

Java check if boolean is null

boolean can only be true or false because it's a primitive datatype (+ a boolean variables default value is false). You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example:

Boolean testvar = null;
if (testvar == null) { ...}

Constructor overloading in Java - best practice

Well, here's an example for overloaded constructors.

public class Employee
{
   private String name;
   private int age;

   public Employee()
   {
      System.out.println("We are inside Employee() constructor");
   }

   public Employee(String name)
   {
      System.out.println("We are inside Employee(String name) constructor");
      this.name = name;
   }

   public Employee(String name, int age)
   {
      System.out.println("We are inside Employee(String name, int age) constructor");
      this.name = name;
      this.age = age;
   }

   public Employee(int age)
   {
      System.out.println("We are inside Employee(int age) constructor");
      this.age = age; 
   }

   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   public int getAge()
   {
      return age;
   }

   public void setAge(int age)
   {
      this.age = age;
   }
}

In the above example you can see overloaded constructors. Name of the constructors is same but each constructors has different parameters.

Here are some resources which throw more light on constructor overloading in java,

Constructors.

Constructor explanation.

Check if value exists in enum in TypeScript

There is a very simple and easy solution to your question:

var districtId = 210;

if (DistrictsEnum[districtId] != null) {

// Returns 'undefined' if the districtId not exists in the DistrictsEnum 
    model.handlingDistrictId = districtId;
}

AngularJS - How can I do a redirect with a full page load?

We had the same issue, working from JS code (i.e. not from HTML anchor). This is how we solved that:

  1. If needed, virtually alter current URL through $location service. This might be useful if your destination is just a variation on the current URL, so that you can take advantage of $location helper methods. E.g. we ran $location.search(..., ...) to just change value of a querystring paramater.

  2. Build up the new destination URL, using current $location.url() if needed. In order to work, this new one had to include everything after schema, domain and port. So e.g. if you want to move to:

    http://yourdomain.com/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en

    then you should set URL as in:

    var destinationUrl = '/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en';

    (with the leading '/' as well).

  3. Assign new destination URL at low-level: $window.location.href = destinationUrl;

  4. Force reload, still at low-level: $window.location.reload();

Removing multiple files from a Git repo that have already been deleted from disk

To stage only the deleted files:

for x in $(git status | grep deleted | awk '{print $2}'); do git rm $x; done

Or (the xargs way):

git status | awk '/deleted/ {print $2}' | xargs git rm

You can alias your preferred command set for convenient later use.

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

Proxy setting for R

Inspired by all the responses related on the internet, finally I've found the solution to correctly configure the Proxy for R and Rstudio.

There are several steps to follow, perhaps some of the steps are useless, but the combination works!

  1. Add environment variables http_proxy and https_proxy with proxy details.

    variable name: http_proxy
    variable value: https://user_id:password@your_proxy:your_port/
    
    variable name: https_proxy
    variable value: https:// user_id:password@your_proxy:your_port
    
  2. If you start R from a desktop icon, you can add the --internet flag to the target line (right click -> Properties)

    e.g."C:\Program Files\R\R-2.8.1\bin\Rgui.exe" --internet2

  3. For RStudio just you have to do this:

    Firstly, open RStudio like always, select from the top menu:

    Tools-Global Options-Packages

    Uncheck the option: Use Internet Explorer library/proxy for HTTP

  4. Find the file (.Renviron) in your computer, most probably you would find it here: C:\Users\your user name\Documents.

    Note that: if it does not exist you can create it just by writing this command in R:

    file.edit('~/.Renviron')
    

    Then add these six lines to the initials of the file:

    options(internet.info = 0)
    
    http_proxy = https:// user_id:password@your_proxy:your_port
    
    http_proxy_user = user_id:password
    
    https_proxy = https:// user_id:password0@your_proxy:your_port
    
    https_proxy_user = user_id:password
    
    ftp_proxy = user_id:password@your_proxy:your_port
    
  5. Restart R. Type the following commands in R to assure that the configuration above works well:

    Sys.getenv("http_proxy")
    
    Sys.getenv("http_proxy_user")
    
    Sys.getenv("https_proxy")
    
    Sys.getenv("https_proxy_user")
    
    Sys.getenv("ftp_proxy")
    
  6. Now you can install the packages as you want by using the command like:

    install.packages("mlr",method="libcurl")
    

    It's important to add method="libcurl", otherwise it won't work.

JavaScript/jQuery - "$ is not defined- $function()" error

Im using Asp.Net Core 2.2 with MVC and Razor cshtml My JQuery is referenced in a layout page I needed to add the following to my view.cshtml:

@section Scripts {
$script-here
}

How to add (vertical) divider to a horizontal LinearLayout?

Frustratingly, you have to enable showing the dividers from code in your activity. For example:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the view to your layout
    setContentView(R.layout.yourlayout);

    // Find the LinearLayout within and enable the divider
    ((LinearLayout)v.findViewById(R.id.llTopBar)).
        setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);

}

How to get option text value using AngularJS?

The best way is to use the ng-options directive on the select element.

Controller

function Ctrl($scope) {
  // sort options
  $scope.products = [{
    value: 'prod_1',
    label: 'Product 1'
  }, {
    value: 'prod_2',
    label: 'Product 2'
  }];   
}

HTML

<select ng-model="selected_product" 
        ng-options="product as product.label for product in products">           
</select>

This will bind the selected product object to the ng-model property - selected_product. After that you can use this:

<p>Ordered by: {{selected_product.label}}</p>

jsFiddle: http://jsfiddle.net/bmleite/2qfSB/

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

body{
    background-image: url(../url/imageName.jpg);
    background-attachment: fixed;
    background-size: auto 100%;
    background-position: center;
}

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

javac: file not found: first.java Usage: javac <options> <source files>

Here is the way I executed the program without environment variable configured.

Java file execution procedure: After you saved a file MyFirstJavaProgram.java

Enter the whole Path of "Javac" followed by java file For executing output Path of followed by comment <-cp> followed by followed by

Given below is the example of execution

C:\Program Files\Java\jdk1.8.0_101\bin>javac C:\Sample\MyFirstJavaProgram2.java C:\Program Files\Java\jdk1.8.0_101\bin>java -cp C:\Sample MyFirstJavaProgram2 Hello World

Different CURRENT_TIMESTAMP and SYSDATE in oracle

SYSDATE returns the system date, of the system on which the database resides

CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value of datatype TIMESTAMP WITH TIME ZONE

execute this comman

    ALTER SESSION SET TIME_ZONE = '+3:0';

and it will provide you the same result.

Find file in directory from command line

If you're looking to do something with a list of files, you can use find combined with the bash $() construct (better than backticks since it's allowed to nest).

for example, say you're at the top level of your project directory and you want a list of all C files starting with "btree". The command:

find . -type f -name 'btree*.c'

will return a list of them. But this doesn't really help with doing something with them.

So, let's further assume you want to search all those file for the string "ERROR" or edit them all. You can execute one of:

grep ERROR $(find . -type f -name 'btree*.c')
vi $(find . -type f -name 'btree*.c')

to do this.