Programs & Examples On #Option strict

The Option Strict Statement restricts implicit data type conversions to only widening conversions which disallows late binding, and also disallows implicit typing which results in an Object type.

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

How to break nested loops in JavaScript?

Break 1st loop:

for(i=0;i<5;i++)
{
  for(j=i+1;j<5;j++)
  {
    //do something

    break;
  }
  alert(1);
};

Break both loops:

for(i=0;i<5;i++)
{
  var breakagain = false;
  for(j=i+1;j<5;j++)
  {
    //do something

    breakagain = true;
    break;
  }
  alert(1);
  if(breakagain)
    break;
};

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

SQL where datetime column equals today's date?

Easy way out is to use a condition like this ( use desired date > GETDATE()-1)

your sql statement "date specific" > GETDATE()-1

Calling a Javascript Function from Console

An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function

//this will fail
$(document).ready(function () {
          myFunction(alert('doing something!'));
          //other stuff
}

To succeed move the function outside the document ready function

//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {

          //other stuff
}

Then in the console window, type the function name with the '()' to execute the function

myFunction()

Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name

function myFunction(alert('doing something!'))

Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.

How to show grep result with complete path or file name

I fall here when I was looking exactly for the same problem and maybe it can help other.

I think the real solution is:

cat *.log | grep -H somethingtosearch

How to make function decorators and chain them together?

You could make two separate decorators that do what you want as illustrated directly below. Note the use of *args, **kwargs in the declaration of the wrapped() function which supports the decorated function having multiple arguments (which isn't really necessary for the example say() function, but is included for generality).

For similar reasons, the functools.wraps decorator is used to change the meta attributes of the wrapped function to be those of the one being decorated. This makes error messages and embedded function documentation (func.__doc__) be those of the decorated function instead of wrapped()'s.

from functools import wraps

def makebold(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<b>" + fn(*args, **kwargs) + "</b>"
    return wrapped

def makeitalic(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<i>" + fn(*args, **kwargs) + "</i>"
    return wrapped

@makebold
@makeitalic
def say():
    return 'Hello'

print(say())  # -> <b><i>Hello</i></b>

Refinements

As you can see there's a lot of duplicate code in these two decorators. Given this similarity it would be better for you to instead make a generic one that was actually a decorator factory—in other words, a decorator function that makes other decorators. That way there would be less code repetition—and allow the DRY principle to be followed.

def html_deco(tag):
    def decorator(fn):
        @wraps(fn)
        def wrapped(*args, **kwargs):
            return '<%s>' % tag + fn(*args, **kwargs) + '</%s>' % tag
        return wrapped
    return decorator

@html_deco('b')
@html_deco('i')
def greet(whom=''):
    return 'Hello' + (' ' + whom) if whom else ''

print(greet('world'))  # -> <b><i>Hello world</i></b>

To make the code more readable, you can assign a more descriptive name to the factory-generated decorators:

makebold = html_deco('b')
makeitalic = html_deco('i')

@makebold
@makeitalic
def greet(whom=''):
    return 'Hello' + (' ' + whom) if whom else ''

print(greet('world'))  # -> <b><i>Hello world</i></b>

or even combine them like this:

makebolditalic = lambda fn: makebold(makeitalic(fn))

@makebolditalic
def greet(whom=''):
    return 'Hello' + (' ' + whom) if whom else ''

print(greet('world'))  # -> <b><i>Hello world</i></b>

Efficiency

While the above examples do all work, the code generated involves a fair amount of overhead in the form of extraneous function calls when multiple decorators are applied at once. This may not matter, depending the exact usage (which might be I/O-bound, for instance).

If speed of the decorated function is important, the overhead can be kept to a single extra function call by writing a slightly different decorator factory-function which implements adding all the tags at once, so it can generate code that avoids the addtional function calls incurred by using separate decorators for each tag.

This requires more code in the decorator itself, but this only runs when it's being applied to function definitions, not later when they themselves are called. This also applies when creating more readable names by using lambda functions as previously illustrated. Sample:

def multi_html_deco(*tags):
    start_tags, end_tags = [], []
    for tag in tags:
        start_tags.append('<%s>' % tag)
        end_tags.append('</%s>' % tag)
    start_tags = ''.join(start_tags)
    end_tags = ''.join(reversed(end_tags))

    def decorator(fn):
        @wraps(fn)
        def wrapped(*args, **kwargs):
            return start_tags + fn(*args, **kwargs) + end_tags
        return wrapped
    return decorator

makebolditalic = multi_html_deco('b', 'i')

@makebolditalic
def greet(whom=''):
    return 'Hello' + (' ' + whom) if whom else ''

print(greet('world'))  # -> <b><i>Hello world</i></b>

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

How to remove the first character of string in PHP?

To remove every : from the beginning of a string, you can use ltrim:

$str = '::f:o:';
$str = ltrim($str, ':');
var_dump($str); //=> 'f:o:'

Get UserDetails object from Security Context in Spring MVC controller

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

    ModelAndView mv = new ModelAndView("index");

    String userName = "not logged in"; // Any default user  name
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        userName = principal.getName();
    }

    mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

    return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

Set 4 Space Indent in Emacs in Text Mode

Do not confuse variable tab-width with variable tab-stop-list. The former is used for the display of literal TAB characters. The latter controls what characters are inserted when you press the TAB character in certain modes.

-- GNU Emacs Manual

(customize-variable (quote tab-stop-list))

or add tab-stop-list entry to custom-set-variables in .emacs file:

(custom-set-variables
  ;; custom-set-variables was added by Custom.
  ;; If you edit it by hand, you could mess it up, so be careful.
  ;; Your init file should contain only one such instance.
  ;; If there is more than one, they won't work right.
 '(tab-stop-list (quote (4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 116 120))))

Another way to edit the tab behavior is with with M-x edit-tab-stops.

See the GNU Emacs Manual on Tab Stops for more information on edit-tab-stops.

How do I jump out of a foreach loop in C#?

Either return straight out of the loop:

foreach(string s in sList){
   if(s.equals("ok")){
      return true;
   }
}

// if you haven't returned by now, no items are "ok"
return false;

Or use break:

bool isOk = false;
foreach(string s in sList){
   if(s.equals("ok")){
      isOk = true;
      break; // jump out of the loop
   }
}

if(isOk)
{
    // do something
}

However, in your case it might be better to do something like this:

if(sList.Contains("ok"))
{
    // at least one element is "ok"
}
else
{
   // no elements are "ok"
}

Make Div overlay ENTIRE page (not just viewport)?

body:before {
    content: " ";
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: -1;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
}

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

getApplication() vs. getApplicationContext()

To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.

How to insert a string which contains an "&"

INSERT INTO TEST_TABLE VALUES('Jonhy''s Sport &'||' Fitness')

This query's output : Jonhy's Sport & Fitness

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • performing HTTP requests with cURL (using PROXY)

    From man curl:

    -x, --proxy <[protocol://][user:password@]proxyhost[:port]>
    
         Use the specified HTTP proxy. 
         If the port number is not specified, it is assumed at port 1080.
    

    General way:

    export http_proxy=http://your.proxy.server:port/
    

    Then you can connect through proxy from (many) application.

    And, as per comment below, for https:

    export https_proxy=https://your.proxy.server:port/
    

    macro run-time error '9': subscript out of range

    When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:

    Sheets("Sheet1").protect Password:="btfd"
    

    because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:

    ActiveWorkbook.Save
    

    Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?

    Call an overridden method from super class in typescript

    If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.

    This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)

    abstract class A {
        // The abstract method the subclass will have to call
        protected abstract doStuff():void;
    
        constructor(){
         alert("Super class A constructed, calling now 'doStuff'")
         this.doStuff();
        }
    }
    
    class B extends A{
    
        // Define here the abstract method
        protected doStuff()
        {
            alert("Submethod called");
        }
    }
    
    var b = new B();
    

    Test it Here

    And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.

    abstract class A {
        constructor() {
            alert("Super class A constructed, calling now 'doStuff'")
            this.doStuff();
        }
    
        // The fallback method the subclass will call if not overridden
        protected doStuff(): void {
            alert("Default doStuff");
        };
    }
    
    class B extends A {
        // Override doStuff()
        protected doStuff() {
            alert("Submethod called");
        }
    }
    
    class C extends A {
        // No doStuff() overriding, fallback on A.doStuff()
    }
    
    var b = new B();
    var c = new C();
    

    Try it Here

    Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

    look like this demo:

    void Main()
    {
        foreach(var f in GetFilesToProcess("c:\\", new[] {".xml", ".txt"}))
            Debug.WriteLine(f);
    }
    private static IEnumerable<string> GetFilesToProcess(string path, IEnumerable<string> extensions)
    {
       return Directory.GetFiles(path, "*.*")
           .Where(f => extensions.Contains(Path.GetExtension(f).ToLower()));
    }
    

    How to get Client location using Google Maps API v3?

    No need to do your own implementation. I can recommend using geolocationmarker from google-maps-utility-library-v3.

    Using HTTPS with REST in Java

    Check this out: http://code.google.com/p/resting/. I could use resting to consume HTTPS REST services.

    Load json from local file with http.get() in angular 2

    For Angular 5+ only preform steps 1 and 4


    In order to access your file locally in Angular 2+ you should do the following (4 steps):

    [1] Inside your assets folder create a .json file, example: data.json

    [2] Go to your angular.cli.json (angular.json in Angular 6+) inside your project and inside the assets array put another object (after the package.json object) like this:

    { "glob": "data.json", "input": "./", "output": "./assets/" }

    full example from angular.cli.json

    "apps": [
        {
          "root": "src",
          "outDir": "dist",
          "assets": [
            "assets",
            "favicon.ico",
            { "glob": "package.json", "input": "../", "output": "./assets/" },
            { "glob": "data.json", "input": "./", "output": "./assets/" }
          ],
    

    Remember, data.json is just the example file we've previously added in the assets folder (you can name your file whatever you want to)

    [3] Try to access your file via localhost. It should be visible within this address, http://localhost:your_port/assets/data.json

    If it's not visible then you've done something incorrectly. Make sure you can access it by typing it in the URL field in your browser before proceeding to step #4.

    [4] Now preform a GET request to retrieve your .json file (you've got your full path .json URL and it should be simple)

     constructor(private http: HttpClient) {}
            // Make the HTTP request:
            this.http.get('http://localhost:port/assets/data.json')
                     .subscribe(data => console.log(data));
    

    Winforms TableLayoutPanel adding rows programmatically

    Here's my code for adding a new row to a two-column TableLayoutColumn:

    private void AddRow(Control label, Control value)
    {
        int rowIndex = AddTableRow();
        detailTable.Controls.Add(label, LabelColumnIndex, rowIndex);
        if (value != null)
        {
            detailTable.Controls.Add(value, ValueColumnIndex, rowIndex);
        }
    }
    
    private int AddTableRow()
    {
        int index = detailTable.RowCount++;
        RowStyle style = new RowStyle(SizeType.AutoSize);
        detailTable.RowStyles.Add(style);
        return index;
    }
    

    The label control goes in the left column and the value control goes in the right column. The controls are generally of type Label and have their AutoSize property set to true.

    I don't think it matters too much, but for reference, here is the designer code that sets up detailTable:

    this.detailTable.ColumnCount = 2;
    this.detailTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
    this.detailTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
    this.detailTable.Dock = System.Windows.Forms.DockStyle.Fill;
    this.detailTable.Location = new System.Drawing.Point(0, 0);
    this.detailTable.Name = "detailTable";
    this.detailTable.RowCount = 1;
    this.detailTable.RowStyles.Add(new System.Windows.Forms.RowStyle());
    this.detailTable.Size = new System.Drawing.Size(266, 436);
    this.detailTable.TabIndex = 0;
    

    This all works just fine. You should be aware that there appear to be some problems with disposing controls from a TableLayoutPanel dynamically using the Controls property (at least in some versions of the framework). If you need to remove controls, I suggest disposing the entire TableLayoutPanel and creating a new one.

    What is the best java image processing library/approach?

    I know this question is quite old, but as new software comes out it does help to get some new links to projects that might be interesting for folks.

    imgscalr is pure-Java image resizing (and simple ops like padding, cropping, rotating, brighten/dimming, etc.) library that is painfully simple to use - a single class consists of a set of simple graphics operations all defined as static methods that you pass an image and get back a result.

    The most basic example of using the library would look like this:

    BufferedImage thumbnail = Scalr.resize(image, 150);
    

    And a more typical usage to generate image thumbnails using a few quality tweaks and the like might look like this:

    import static org.imgscalr.Scalr.*;
    
    public static BufferedImage createThumbnail(BufferedImage img) {
        // Create quickly, then smooth and brighten it.
        img = resize(img, Method.SPEED, 125, OP_ANTIALIAS, OP_BRIGHTER);
    
        // Let's add a little border before we return result.
        return pad(img, 4);
    }
    

    All image-processing operations use the raw Java2D pipeline (which is hardware accelerated on major platforms) and won't introduce the pain of calling out via JNI like library contention in your code.

    imgscalr has also been deployed in large-scale productions in quite a few places - the inclusion of the AsyncScalr class makes it a perfect drop-in for any server-side image processing.

    There are numerous tweaks to image-quality you can use to trade off between speed and quality with the highest ULTRA_QUALITY mode providing a scaled result that looks better than GIMP's Lancoz3 implementation.

    Simple and clean way to convert JSON string to Object in Swift

    For Swift 4

    I used @Passkit's logic but i had to update as per Swift 4


    Step.1 Created extension for String Class

    import UIKit
    
    
    extension String
        {
            var parseJSONString: AnyObject?
            {
                let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
    
                if let jsonData = data
                {
                    // Will return an object or nil if JSON decoding fails
                    do
                    {
                        let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers)
                        if let jsonResult = message as? NSMutableArray
                        {
                            print(jsonResult)
    
                            return jsonResult //Will return the json array output
                        }
                        else
                        {
                            return nil
                        }
                    }
                    catch let error as NSError
                    {
                        print("An error occurred: \(error)")
                        return nil
                    }
                }
                else
                {
                    // Lossless conversion of the string was not possible
                    return nil
                }
            }
        }
    

    Step.2 This is how I used in my view controller

    var jsonString = "[\n" +
        "{\n" +
        "\"id\":72,\n" +
        "\"name\":\"Batata Cremosa\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":183,\n" +
        "\"name\":\"Caldeirada de Peixes\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":76,\n" +
        "\"name\":\"Batata com Cebola e Ervas\",\n" +            
        "},\n" +
        "{\n" +
        "\"id\":56,\n" +
        "\"name\":\"Arroz de forma\",\n" +            
    "}]"
    
     //Convert jsonString to jsonArray
    
    let json: AnyObject? = jsonString.parseJSONString
    print("Parsed JSON: \(json!)")
    print("json[2]: \(json![2])")
    

    All credit goes to original user, I just updated for latest swift version

    Javascript onload not working

    You are missing the ()

    <body onload="imageRefreshBig();">
    

    How to automatically indent source code?

    I have tried both ways, and from the Edit|Advanced menu, and they are not doing anything to my source code. Other options like line indent are working. What could be wrong? – Chucky Jul 12 '13 at 11:06

    Sometimes if it doesnt work, try to select a couple lines above and below or the whole block of code (whole function, whole cycle, whole switch, etc.), so that it knows how to indent.

    Like for example if you copy/paste something into a case statement of a switch and it has wrong indentation, you need to select the text + the line with the case statement above to get it to work.

    How to use a BackgroundWorker?

    You can update progress bar only from ProgressChanged or RunWorkerCompleted event handlers as these are synchronized with the UI thread.

    The basic idea is. Thread.Sleep just simulates some work here. Replace it with your real routing call.

    public Form1()
    {
        InitializeComponent();
    
        backgroundWorker1.DoWork += backgroundWorker1_DoWork;
        backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
        backgroundWorker1.WorkerReportsProgress = true;
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }
    
    private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        for (int i = 0; i < 100; i++)
        {
            Thread.Sleep(1000);
            backgroundWorker1.ReportProgress(i);
        }
    }
    
    private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
    }
    

    How to display div after click the button in Javascript?

    <div  style="display:none;" class="answer_list" > WELCOME</div>
    <input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">
    

    extract date only from given timestamp in oracle sql

    This format worked for me, for the mentioned date format i.e. MM/DD/YYYY

    SELECT to_char(query_date,'MM/DD/YYYY') as query_date 
    FROM QMS_INVOICE_TABLE;
    

    dotnet ef not found in .NET Core 3

    I had the same problem. I resolved, uninstalling all de the versions in my pc and then reinstall dotnet.

    Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

    Another way of doing it. This approach can be useful for changing the text to 2 different colors, just by adding 2 spans.

    Label1.Text = "String with original color" + "<b><span style=""color:red;"">" + "Your String Here" + "</span></b>";
    

    How do I determine if a checkbox is checked?

    <!DOCTYPE html>
    <html>
    <body>
        <input type="checkbox" id="isSelected"/>
        <div id="myDiv" style="display:none">Is Checked</div>
    </body>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            $('#isSelected').click(function() {
                $("#myDiv").toggle(this.checked);
            });
        </script>
    </html>
    

    Count the number of occurrences of each letter in string

    int charset[256] = {0};
    int charcount[256] = {0};
    
    for (i = 0; i < 20; i++)
    {
        for(int c = 0; c < 256; c++)
        {
            if(string[i] == charset[c])
            {
               charcount[c]++;
            }
        }
    }
    

    charcount will store the occurence of any character in the string.

    Remove all special characters, punctuation and spaces from string

    string.punctuation contains following characters:

    '!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'

    You can use translate and maketrans functions to map punctuations to empty values (replace)

    import string
    
    'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))
    

    Output:

    'This is A test'
    

    How to convert time milliseconds to hours, min, sec format in JavaScript?

    Sorry, late to the party. The accepted answer did not cut it for me, so I wrote it myself.

    Output:

    2h 59s
    1h 59m
    1h
    1h 59s
    59m 59s
    59s
    

    Code (Typescript):

    function timeConversion(duration: number) {
      const portions: string[] = [];
    
      const msInHour = 1000 * 60 * 60;
      const hours = Math.trunc(duration / msInHour);
      if (hours > 0) {
        portions.push(hours + 'h');
        duration = duration - (hours * msInHour);
      }
    
      const msInMinute = 1000 * 60;
      const minutes = Math.trunc(duration / msInMinute);
      if (minutes > 0) {
        portions.push(minutes + 'm');
        duration = duration - (minutes * msInMinute);
      }
    
      const seconds = Math.trunc(duration / 1000);
      if (seconds > 0) {
        portions.push(seconds + 's');
      }
    
      return portions.join(' ');
    }
    
    console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
    console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000)              ));
    console.log(timeConversion((60 * 60 * 1000)                                 ));
    console.log(timeConversion((60 * 60 * 1000)                    + (59 * 1000)));
    console.log(timeConversion(                   (59 * 60 * 1000) + (59 * 1000)));
    console.log(timeConversion(                                      (59 * 1000)));
    

    Float a div above page content

    Yes, the higher the z-index, the better. It will position your content element on top of every other element on the page. Say you have z-index to some elements on your page. Look for the highest and then give a higher z-index to your popup element. This way it will flow even over the other elements with z-index. If you don't have a z-index in any element on your page, you should give like z-index:2; or something higher.

    Specify path to node_modules in package.json

    I'm not sure if this is what you had in mind, but I ended up on this question because I was unable to install node_modules inside my project dir as it was mounted on a filesystem that did not support symlinks (a VM "shared" folder).

    I found the following workaround:

    1. Copy the package.json file to a temp folder on a different filesystem
    2. Run npm install there
    3. Copy the resulting node_modules directory back into the project dir, using cp -r --dereference to expand symlinks into copies.

    I hope this helps someone else who ends up on this question when looking for a way to move node_modules to a different filesystem.

    Other options

    There is another workaround, which I found on the github issue that @Charminbear linked to, but this doesn't work with grunt because it does not support NODE_PATH as per https://github.com/browserify/resolve/issues/136:

    lets say you have /media/sf_shared and you can't install symlinks in there, which means you can't actually npm install from /media/sf_shared/myproject because some modules use symlinks.

    • $ mkdir /home/dan/myproject && cd /home/dan/myproject
    • $ ln -s /media/sf_shared/myproject/package.json (you can symlink in this direction, just can't create one inside of /media/sf_shared)
    • $ npm install
    • $ cd /media/sf_shared/myproject
    • $ NODE_PATH=/home/dan/myproject/node_modules node index.js

    How to open standard Google Map application from my application?

    Using String format will help but you must be care full with the locale. In germany float will be separates with in comma instead an point.

    Using String.format("geo:%f,%f",5.1,2.1); on locale english the result will be "geo:5.1,2.1" but with locale german you will get "geo:5,1,2,1"

    You should use the English locale to prevent this behavior.

    String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    context.startActivity(intent);
    

    To set an label to the geo point you can extend your geo uri by using:

    !!! but be carefull with this the geo-uri is still under develoment http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00

    String uri = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f (%s)", 
                               latitude, longitude, zoom, latitude, longitude, label);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    context.startActivity(intent);
    

    Android - how to replace part of a string by another string?

    It is working, but it wont modify the caller object, but returning a new String.
    So you just need to assign it to a new String variable, or to itself:

    string = string.replace("to", "xyz");
    

    or

    String newString = string.replace("to", "xyz");
    

    API Docs

    public String replace (CharSequence target, CharSequence replacement) 
    

    Since: API Level 1

    Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.

    Parameters

    • target the sequence to replace.
    • replacement the replacement sequence.

    Returns the resulting string.
    Throws NullPointerException if target or replacement is null.

    Convert int to char in java

    Make sure the integer value is ASCII value of an alphabet/character.

    If not then make it.

    for e.g. if int i=1
    

    then add 64 to it so that it becomes 65 = ASCII value of 'A' Then use

    char x = (char)i;
    
    print x
    
    // 'A' will be printed 
    

    How to make inline functions in C#

    The answer to your question is yes and no, depending on what you mean by "inline function". If you're using the term like it's used in C++ development then the answer is no, you can't do that - even a lambda expression is a function call. While it's true that you can define inline lambda expressions to replace function declarations in C#, the compiler still ends up creating an anonymous function.

    Here's some really simple code I used to test this (VS2015):

        static void Main(string[] args)
        {
            Func<int, int> incr = a => a + 1;
            Console.WriteLine($"P1 = {incr(5)}");
        }
    

    What does the compiler generate? I used a nifty tool called ILSpy that shows the actual IL assembly generated. Have a look (I've omitted a lot of class setup stuff)

    This is the Main function:

            IL_001f: stloc.0
            IL_0020: ldstr "P1 = {0}"
            IL_0025: ldloc.0
            IL_0026: ldc.i4.5
            IL_0027: callvirt instance !1 class [mscorlib]System.Func`2<int32, int32>::Invoke(!0)
            IL_002c: box [mscorlib]System.Int32
            IL_0031: call string [mscorlib]System.String::Format(string, object)
            IL_0036: call void [mscorlib]System.Console::WriteLine(string)
            IL_003b: ret
    

    See those lines IL_0026 and IL_0027? Those two instructions load the number 5 and call a function. Then IL_0031 and IL_0036 format and print the result.

    And here's the function called:

            .method assembly hidebysig 
                instance int32 '<Main>b__0_0' (
                    int32 a
                ) cil managed 
            {
                // Method begins at RVA 0x20ac
                // Code size 4 (0x4)
                .maxstack 8
    
                IL_0000: ldarg.1
                IL_0001: ldc.i4.1
                IL_0002: add
                IL_0003: ret
            } // end of method '<>c'::'<Main>b__0_0'
    

    It's a really short function, but it is a function.

    Is this worth any effort to optimize? Nah. Maybe if you're calling it thousands of times a second, but if performance is that important then you should consider calling native code written in C/C++ to do the work.

    In my experience readability and maintainability are almost always more important than optimizing for a few microseconds gain in speed. Use functions to make your code readable and to control variable scoping and don't worry about performance.

    "Premature optimization is the root of all evil (or at least most of it) in programming." -- Donald Knuth

    "A program that doesn't run correctly doesn't need to run fast" -- Me

    Passing an array by reference in C?

    Arrays are effectively passed by reference by default. Actually the value of the pointer to the first element is passed. Therefore the function or method receiving this can modify the values in the array.

    void SomeMethod(Coordinate Coordinates[]){Coordinates[0].x++;};
    int main(){
      Coordinate tenCoordinates[10];
      tenCoordinates[0].x=0;
      SomeMethod(tenCoordinates[]);
      SomeMethod(&tenCoordinates[0]);
      if(0==tenCoordinates[0].x - 2;){
        exit(0);
      }
      exit(-1);
    }
    

    The two calls are equivalent, and the exit value should be 0;

    Error 330 (net::ERR_CONTENT_DECODING_FAILED):

    If you are to use the Codeigniter framework then just make this into config file:

    $config['compress_output'] = FALSE;
    

    And in php.ini configuration file, use:

    zlib.output_compression=On
    

    The I/O operation has been aborted because of either a thread exit or an application request

    I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).

    To fix it, I had to check if the IAsyncResult.IsCompleted==true. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()

    Like this :

    Stream s = this.GetStream();
    IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
    if (!ar.IsCompleted)
        ar.AsyncWaitHandle.WaitOne();
    

    Most of the time, ar.IsCompleted will be true.

    Full Screen DialogFragment in Android

    This is the solution how I figured out this issue:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);    
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);   
    
        return dialog;
    }
    
    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
                dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
    }
    

    String's Maximum length in Java - calling length() method

    apparently it's bound to an int, which is 0x7FFFFFFF (2147483647).

    don't fail jenkins build if execute shell fails

    Another one answer with some tips, can be helpful for somebody:

    remember to separate your commands with the following rule:

    command1 && command2 - means, that command2 will be executed, only if command1 success

    command1 ; command2 - means, that command 2 will be executed despite on result of command1

    for example:

    String run_tests = sh(script: "set +e && cd ~/development/tests/ && gmake test ;set -e;echo 0 ", returnStdout: true).trim()
    println run_tests 
    

    will be executed successfully with set -e and echo 0 commands if gmake test failed (your tests failed), while the following code snipped:

    String run_tests = sh(script: "set +e && cd ~/development/tests/ && gmake test && set -e && echo 0 ", returnStdout: true).trim()
    println run_tests 
    

    a bit wrong and commands set -e and echo 0 in&& gmake test && set -e && echo 0 will be skipped, with the println run_tests statement, because failed gmake test will abort the jenkins build. As workaround you can switch to returnStatus:true, but then you will miss the output from your command.

    Defining a variable with or without export

    export makes the variable available to sub-processes.

    That is,

    export name=value
    

    means that the variable name is available to any process you run from that shell process. If you want a process to make use of this variable, use export, and run the process from that shell.

    name=value
    

    means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc.

    It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.

    How to return PDF to browser in MVC?

    Return a FileContentResult. The last line in your controller action would be something like:

    return File("Chap0101.pdf", "application/pdf");
    

    If you are generating this PDF dynamically, it may be better to use a MemoryStream, and create the document in memory instead of saving to file. The code would be something like:

    Document document = new Document();
    
    MemoryStream stream = new MemoryStream();
    
    try
    {
        PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream);
        pdfWriter.CloseStream = false;
    
        document.Open();
        document.Add(new Paragraph("Hello World"));
    }
    catch (DocumentException de)
    {
        Console.Error.WriteLine(de.Message);
    }
    catch (IOException ioe)
    {
        Console.Error.WriteLine(ioe.Message);
    }
    
    document.Close();
    
    stream.Flush(); //Always catches me out
    stream.Position = 0; //Not sure if this is required
    
    return File(stream, "application/pdf", "DownloadName.pdf");
    

    Clear and reset form input fields

    Why not use HTML-controlled items such as <input type="reset">

    SELECT max(x) is returning null; how can I make it return 0?

    In SQL 2005 / 2008:

    SELECT ISNULL(MAX(X), 0) AS MaxX
    FROM tbl WHERE XID = 1
    

    Change the background color of a row in a JTable

    The other answers given here work well since you use the same renderer in every column.

    However, I tend to believe that generally when using a JTable you will have different types of data in each columm and therefore you won't be using the same renderer for each column. In these cases you may find the Table Row Rendering approach helpfull.

    How to compile a 64-bit application using Visual C++ 2010 Express?

    64-bit tools are not available on Visual C++ Express by default. To enable 64-bit tools on Visual C++ Express, install the Windows Software Development Kit (SDK) in addition to Visual C++ Express. Otherwise, an error occurs when you attempt to configure a project to target a 64-bit platform using Visual C++ Express.

    How to: Configure Visual C++ Projects to Target 64-Bit Platforms

    Ref: http://msdn.microsoft.com/en-us/library/9yb4317s.aspx

    Freemarker iterating over hashmap keys

    If using a BeansWrapper with an exposure level of Expose.SAFE or Expose.ALL, then the standard Java approach of iterating the entry set can be employed:

    For example, the following will work in Freemarker (since at least version 2.3.19):

    <#list map.entrySet() as entry>  
      <input type="hidden" name="${entry.key}" value="${entry.value}" />
    </#list>
    

    In Struts2, for instance, an extension of the BeanWrapper is used with the exposure level defaulted to allow this manner of iteration.

    Java better way to delete file if exists

    This is my solution:

    File f = new File("file.txt");
    if(f.exists() && !f.isDirectory()) { 
        f.delete();
    }
    

    How to run specific test cases in GoogleTest

    Finally I got some answer, ::test::GTEST_FLAG(list_tests) = true; //From your program, not w.r.t console.

    If you would like to use --gtest_filter =*; /* =*, =xyz*... etc*/ // You need to use them in Console.

    So, my requirement is to use them from the program not from the console.

    Updated:-

    Finally I got the answer for updating the same in from the program.

     ::testing::GTEST_FLAG(filter) = "*Counter*:*IsPrime*:*ListenersTest.DoesNotLeak*";//":-:*Counter*";
          InitGoogleTest(&argc, argv);
    RUN_ALL_TEST();
    

    So, Thanks for all the answers.

    You people are great.

    TypeError: unhashable type: 'list' when using built-in set function

    Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.

    mylist = [[1,2,3,4],[4,5,6,7]]
    mylist2 = []
    for thing in mylist:
        thing = tuple(thing)
        mylist2.append(thing)
    set(mylist2)
    

    UPDATE and REPLACE part of a string

    CREATE TABLE tbl_PersonalDetail
    (ID INT IDENTITY ,[Date] nvarchar(20), Name nvarchar(20), GenderID int);
    
    INSERT INTO Tbl_PersonalDetail VALUES(N'18-4-2015', N'Monay', 2),
                                         (N'31-3-2015', N'Monay', 2),
                                         (N'28-12-2015', N'Monay', 2),
                                         (N'19-4-2015', N'Monay', 2)
    
    DECLARE @Date Nvarchar(200)
    
    SET @Date = (SELECT [Date] FROM Tbl_PersonalDetail WHERE ID = 2)
    
    Update Tbl_PersonalDetail SET [Date] = (REPLACE(@Date , '-','/')) WHERE ID = 2 
    

    The 'json' native gem requires installed build tools

    My solution is simplier and checked on Ruby 2.0. It also enable download Json. (run CMD.exe as administrator)

        C:\RubyDev>devkitvars.bat
        Adding the DevKit to PATH...
    

    And then write again gem command.

    How to send an email from JavaScript

    There seems to be a new solution at the horizon. It's called EmailJS. They claim that no server code is needed. You can request an invitation.

    Update August 2016: EmailJS seems to be live already. You can send up to 200 emails per month for free and it offers subscriptions for higher volumes.

    create multiple tag docker image

    How not to do it:

    When building an image, you could also tag it this way.

    docker build -t ubuntu:14.04 .
    

    Then you build it again with another tag:

    docker build -t ubuntu:latest .
    

    If your Dockerfile makes good use of the cache, the same image should come out, and it effectively does the same as retagging the same image. If you do docker images then you will see that they have the same ID.

    There's probably a case where this goes wrong though... But like @david-braun said, you can't create tags with Dockerfiles themselves, just with the docker command.

    forward declaration of a struct in C?

    A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

    struct A;                      // forward declaration
    void function( struct A *a );  // using the 'incomplete' type only as pointer
    

    If you typedef your struct you can leave out the struct keyword.

    typedef struct A A;          // forward declaration *and* typedef
    void function( A *a );
    

    Note that it is legal to reuse the struct name

    Try changing the forward declaration to this in your code:

    typedef struct context context;
    

    It might be more readable to do add a suffix to indicate struct name and type name:

    typedef struct context_s context_t;
    

    Page redirect after certain time PHP

    The PHP refresh after 5 seconds didn't work for me when opening a Save As dialogue to save a file: (header('Content-type: text/plain'); header("Content-Disposition: attachment; filename=$filename>");)

    After the Save As link was clicked, and file was saved, the timed refresh stopped on the calling page.

    However, thank you very much, ibu's javascript solution just kept on ticking and refreshing my webpage, which is what I needed for my specific application. So thank you ibu for posting javascript solution to php problem here.

    You can use javascript to redirect after some time

    setTimeout(function () {    
        window.location.href = 'http://www.google.com'; 
    },5000); // 5 seconds
    

    Import and insert sql.gz file into database with putty

    If you have scp then:

    To move your file from local to remote:

    $scp /home/user/file.gz user@ipaddress:path/to/file.gz 
    

    To move your file from remote to local:

    $scp user@ipaddress:path/to/file.gz /home/user/file.gz
    

    To export your mysql file without login in to remote system:

    $mysqldump -h ipaddressofremotehost -Pportnumber -u usernameofmysql -p  databasename | gzip -9 > databasename.sql.gz
    

    To import your mysql file withoug login in to remote system:

    $gunzip < databasename.sql.gz | mysql -h ipaddressofremotehost -Pportnumber -u usernameofmysql -p 
    

    Note: Make sure you have network access to the ipaddress of remote host

    To check network access:

    $ping ipaddressofremotehost
    

    Which is best data type for phone number in MySQL and what should Java type mapping for it be?

    My requirement is to display 10 digit phone number in the jsp. So here's the setup for me.
    MySQL: numeric(10)

    Java Side:

    @NumberFormat(pattern = "#")  
    private long mobileNumber;
    

    and it worked!

    Transition of background-color

    As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.

    This should produce a fade effect for you in these browsers:

    _x000D_
    _x000D_
    a {_x000D_
        background-color: #FF0;_x000D_
    }_x000D_
    _x000D_
    a:hover {_x000D_
        background-color: #AD310B;_x000D_
        -webkit-transition: background-color 1000ms linear;_x000D_
        -ms-transition: background-color 1000ms linear;_x000D_
        transition: background-color 1000ms linear;_x000D_
    }
    _x000D_
    <a>Navigation Link</a>
    _x000D_
    _x000D_
    _x000D_

    Note: As pointed out by Gerald in the comments, if you put the transition on the a, instead of on a:hover it will fade back to the original color when your mouse moves away from the link.

    This might come in handy, too: CSS Fundamentals: CSS 3 Transitions

    Make browser window blink in task Bar

    this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab.

    newExcitingAlerts = (function () {
        var oldTitle = document.title;
        var msg = "New!";
        var timeoutId;
        var blink = function() { document.title = document.title == msg ? ' ' : msg; };
        var clear = function() {
            clearInterval(timeoutId);
            document.title = oldTitle;
            window.onmousemove = null;
            timeoutId = null;
        };
        return function () {
            if (!timeoutId) {
                timeoutId = setInterval(blink, 1000);
                window.onmousemove = clear;
            }
        };
    }());
    

    Update: You may want to look at using HTML5 notifications.

    HREF="" automatically adds to current page URL (in PHP). Can't figure it out

    Use this:

    <a href="<?php echo(($_SERVER['HTTPS'] ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]); ?>">Whatever</a>
    

    It will create a HREF using the current URL...

    C# 4.0 optional out/ref arguments

    As already mentioned, this is simply not allowed and I think it makes a very good sense. However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:

    Formal parameters of constructors, methods, indexers and delegate types can be declared optional:

    fixed-parameter:
        attributesopt parameter-modifieropt type identifier default-argumentopt
    default-argument:
        = expression

    • A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
    • A required parameter cannot appear after an optional parameter in a formal-parameter-list.
    • A ref or out parameter cannot have a default-argument.

    Simple DateTime sql query

    This has worked for me in both SQL Server 2005 and 2008:

    SELECT * from TABLE
    WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
      AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
    

    Xcode/Simulator: How to run older iOS version?

    The simulator CANNOT be downloaded from:

    Xcode -> Preferences -> Downloads

    Only the iOS devices symbols. As this option says:

    This package includes information and symbols that Xcode needs for debugging your app on iOS devices running versions of iOS prior to iOS 4.2. If you intend to debug your app on a device running one of these versions of iOS you should install this package.

    That is, you need an iOS 4.2 device to test an iOS 4.2 application

    How to make a simple collection view with Swift

    This project has been tested with Xcode 10 and Swift 4.2.

    Create a new project

    It can be just a Single View App.

    Add the code

    Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell. This class will hold the outlets for the views that you add to your cell in the storyboard.

    import UIKit
    class MyCollectionViewCell: UICollectionViewCell {
        
        @IBOutlet weak var myLabel: UILabel!
    }
    

    We will connect this outlet later.

    Open ViewController.swift and make sure you have the following content:

    import UIKit
    class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
        
        let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
        var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
        
        
        // MARK: - UICollectionViewDataSource protocol
        
        // tell the collection view how many cells to make
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return self.items.count
        }
        
        // make a cell for each cell index path
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            
            // get a reference to our storyboard cell
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
            
            // Use the outlet in our custom class to get a reference to the UILabel in the cell
            cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
            cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
            
            return cell
        }
        
        // MARK: - UICollectionViewDelegate protocol
        
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            // handle tap events
            print("You selected cell #\(indexPath.item)!")
        }
    }
    

    Notes

    • UICollectionViewDataSource and UICollectionViewDelegate are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout protocol to change the size of the views programmatically, but it isn't necessary.
    • We are just putting simple strings in our grid, but you could certainly do images later.

    Set up the storyboard

    Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.

    enter image description here

    Make sure that your defaults in the Attribute Inspector are also

    • Items: 1
    • Layout: Flow

    The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.

    enter image description here

    Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell" in ViewController.swift.

    enter image description here

    And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell, our custom class that we made.

    enter image description here

    Hook up the outlets

    • Hook the Label in the collection cell to myLabel in the MyCollectionViewCell class. (You can Control-drag.)
    • Hook the Collection View delegate and dataSource to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)

    enter image description here

    Finished

    Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.

    enter image description here

    Making Improvements

    The example above works but it is rather ugly. Here are a few things you can play with:

    Background color

    In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.

    Cell spacing

    Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.

    Cell shape

    If you want rounded corners, a border, and the like, you can play around with the cell layer. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyan in code above.

    cell.layer.borderColor = UIColor.black.cgColor
    cell.layer.borderWidth = 1
    cell.layer.cornerRadius = 8
    

    See this answer for other things you can do with the layer (shadow, for example).

    Changing the color when tapped

    It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewController class:

    // change background color when user touches cell
    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.backgroundColor = UIColor.red
    }
    
    // change background color back when user releases touch
    func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.backgroundColor = UIColor.cyan
    }
    

    Here is the updated look:

    enter image description here

    Further study

    UITableView version of this Q&A

    Select and display only duplicate records in MySQL

    This works the fastest for me

    SELECT
        primary_key
    FROM
        table_name
    WHERE
        primary_key NOT IN (
            SELECT
                primary_key
            FROM
                table_name
            GROUP BY
                column_name
            HAVING
                COUNT(*) = 1
        );
    

    How to remove item from array by value?

    Check out this way:

    delete this.arrayName[this.arrayName.indexOf(value)];
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

    Android ADB device offline, can't issue commands

    For me, it turned out that I had two different SDK installations. When I launched the Android SDK Manager and updated the tools from Eclipse, the SDK path pointed to one location, but the PATH environment variable used on the command line pointed to another location, that had an older version of the SDK, which always shows the 4.2.2 device as offline.

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

    You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

    Pick an encoding and stick with it:

    f.write(printinfo.encode('utf8') + '\n')
    

    or use io.open() to create a file object that'll encode for you as you write to the file:

    import io
    
    f = io.open(filename, 'w', encoding='utf8')
    

    You may want to read:

    before continuing.

    Validate a username and password against Active Directory?

    A full .Net solution is to use the classes from the System.DirectoryServices namespace. They allow to query an AD server directly. Here is a small sample that would do this:

    using (DirectoryEntry entry = new DirectoryEntry())
    {
        entry.Username = "here goes the username you want to validate";
        entry.Password = "here goes the password";
    
        DirectorySearcher searcher = new DirectorySearcher(entry);
    
        searcher.Filter = "(objectclass=user)";
    
        try
        {
            searcher.FindOne();
        }
        catch (COMException ex)
        {
            if (ex.ErrorCode == -2147023570)
            {
                // Login or password is incorrect
            }
        }
    }
    
    // FindOne() didn't throw, the credentials are correct
    

    This code directly connects to the AD server, using the credentials provided. If the credentials are invalid, searcher.FindOne() will throw an exception. The ErrorCode is the one corresponding to the "invalid username/password" COM error.

    You don't need to run the code as an AD user. In fact, I succesfully use it to query informations on an AD server, from a client outside the domain !

    How to check edittext's text is email address or not?

    In your case you can use the android.util.Patterns package.

    EditText email = (EditText)findViewById(R.id.user_email);
    
    if(Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches())
        Toast.makeText(this, "Email is VALID.", Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(this, "Email is INVALID.", Toast.LENGTH_SHORT).show();
    

    What are carriage return, linefeed, and form feed?

    Apart from above information, there is still an interesting history of LF (\n) and CR (\r). [Original author : ??? Source : http://www.ruanyifeng.com/blog/2006/04/post_213.html] Before computer came out, there was a type of teleprinter called Teletype Model 33. It can print 10 characters each second. But there is one problem with this, after finishing printing each line, it will take 0.2 second to move to next line, which is time of printing 2 characters. If a new characters is transferred during this 0.2 second, then this new character will be lost.

    So scientists found a way to solve this problem, they add two ending characters after each line, one is 'Carriage return', which is to tell the printer to bring the print head to the left.; the other one is 'Line feed', it tells the printer to move the paper up 1 line.

    Later, computer became popular, these two concepts are used on computers. At that time, the storage device was very expensive, so some scientists said that it was expensive to add two characters at the end of each line, one is enough, so there are some arguments about which one to use.

    In UNIX/Mac and Linux, '\n' is put at the end of each line, in Windows, '\r\n' is put at the end of each line. The consequence of this use is that files in UNIX/Mac will be displayed in one line if opened in Windows. While file in Windows will have one ^M at the end of each line if opened in UNIX or Mac.

    How do I get multiple subplots in matplotlib?

    You might be interested in the fact that as of matplotlib version 2.1 the second code from the question works fine as well.

    From the change log:

    Figure class now has subplots method The Figure class now has a subplots() method which behaves the same as pyplot.subplots() but on an existing figure.

    Example:

    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    axes = fig.subplots(nrows=2, ncols=2)
    
    plt.show()
    

    How to style a JSON block in Github Wiki?

    Some color-syntaxing enrichment can be applied with the following blockcode syntax

    ```json
    Here goes your json object definition
    ```
    

    Note: This won't prettify the json representation. To do so, one can previously rely on an external service such as jsbeautifier.org and paste the prettified result in the wiki.

    How do I get the AM/PM value from a DateTime?

    @Andy's answer is Okay. But if you want to show time without 24 hours format then you may follow like this way

    string dateTime = DateTime.Now.ToString("hh:mm:ss tt", CultureInfo.InvariantCulture);
    

    After that, you should get time like as "10:35:20 PM" or "10:35:20 AM"

    Quickly create large file on a Windows system

    fsutil file createnew <filename> <length>
    

    where <length> is in bytes.

    For example, to create a 1MB (Windows MB or MiB) file named 'test', this code can be used.

    fsutil file createnew test 1048576
    

    fsutil requires administrative privileges though.

    Swift - Remove " character from string

    Let's say you have a string:

    var string = "potatoes + carrots"
    

    And you want to replace the word "potatoes" in that string with "tomatoes"

    string = string.replacingOccurrences(of: "potatoes", with: "tomatoes", options: NSString.CompareOptions.literal, range: nil)
    

    If you print your string, it will now be: "tomatoes + carrots"

    If you want to remove the word potatoes from the sting altogether, you can use:

    string = string.replacingOccurrences(of: "potatoes", with: "", options: NSString.CompareOptions.literal, range: nil)
    

    If you want to use some other characters in your sting, use:

    • Null Character (\0)
    • Backslash (\)
    • Horizontal Tab (\t)
    • Line Feed (\n)
    • Carriage Return (\r)
    • Double Quote (\")
    • Single Quote (\')

    Example:

    string = string.replacingOccurrences(of: "potatoes", with: "dog\'s toys", options: NSString.CompareOptions.literal, range: nil)
    

    Output: "dog's toys + carrots"

    CSS Selector "(A or B) and C"?

    No. Standard CSS does not provide the kind of thing you're looking for.

    However, you might want to look into LESS and SASS.

    These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.

    They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.

    Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.

    Postgres user does not exist?

    psql: Logs me in with my default username

    psql -U postgres: Logs me in as the postgres user

    Sudo doesn't seem to be required for me.

    I use Postgres.app for my OS X postgres database. It removed the headache of making sure the installation was working and the database server was launched properly. Check it out here: http://postgresapp.com

    Edit: Credit to @Erwin Brandstetter for correcting my use of the arguments.

    Find in Files: Search all code in Team Foundation Server

    This is now possible as of TFS 2015 by using the Code Search plugin. https://marketplace.visualstudio.com/items?itemName=ms.vss-code-search

    The search is done via the web interface, and does not require you to download the code to your local machine which is nice.

    Windows batch command(s) to read first line from text file

    uh? imo this is much simpler

      set /p texte=< file.txt  
      echo %texte%
    

    SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

    Change both Project and Package Properties ProtectionLevel to "DontSaveSensitive"

    How many times a substring occurs

    s = input('enter the main string: ')
    p=input('enter the substring: ')
    l=[]
    for i in range(len(s)):
        l.append(s[i:i+len(p)])
    print(l.count(p))
    

    MVC3 EditorFor readOnly

    This code is supported in MVC4 onwards

    @Html.EditorFor(model => model.userName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly" } })
    

    Xcode Debugger: view value of variable

    Your confusion stems from the fact that declared properties are not (necessarily named the same as) (instance) variables.

    The expresion

    indexPath.row
    

    is equivalent to

    [indexPath row]
    

    and the assignment

    delegate.myData = [myData objectAtIndex:indexPath.row];
    

    is equivalent to

    [delegate setMyData:[myData objectAtIndex:[indexPath row]]];
    

    assuming standard naming for synthesised properties.

    Furthermore, delegate is probably declared as being of type id<SomeProtocol>, i.e., the compiler hasn’t been able to provide actual type information for delegate at that point, and the debugger is relying on information provided at compile-time. Since id is a generic type, there’s no compile-time information about the instance variables in delegate.

    Those are the reasons why you don’t see myData or row as variables.

    If you want to inspect the result of sending -row or -myData, you can use commands p or po:

    p (NSInteger)[indexPath row]
    po [delegate myData]
    

    or use the expressions window (for instance, if you know your delegate is of actual type MyClass *, you can add an expression (MyClass *)delegate, or right-click delegate, choose View Value as… and type the actual type of delegate (e.g. MyClass *).

    That being said, I agree that the debugger could be more helpful:

    • There could be an option to tell the debugger window to use run-time type information instead of compile-time information. It'd slow down the debugger, granted, but would provide useful information;

    • Declared properties could be shown up in a group called properties and allow for (optional) inspection directly in the debugger window. This would also slow down the debugger because of the need to send a message/execute a method in order to get information, but would provide useful information, too.

    Better way to find last used row

    I use this routine to find the count of data rows. There is a minimum of overhead required, but by counting using a decreasing scale, even a very large result requires few iterations. For example, a result of 28,395 would only require 2 + 8 + 3 + 9 + 5, or 27 times through the loop, instead of a time-expensive 28,395 times.

    Even were we to multiply that by 10 (283,950), the iteration count is the same 27 times.

    Dim lWorksheetRecordCountScaler as Long
    Dim lWorksheetRecordCount as Long
    
    Const sDataColumn = "A"   '<----Set to column that has data in all rows (Code, ID, etc.)
    
        'Count the data records
        lWorksheetRecordCountScaler = 100000  'Begin by counting in 100,000-record bites
        lWorksheetRecordCount = lWorksheetRecordCountScaler
    
        While lWorksheetRecordCountScaler >= 1
    
            While Sheets("Sheet2").Range(sDataColumn & lWorksheetRecordCount + 2).Formula > " "
                lWorksheetRecordCount = lWorksheetRecordCount + lWorksheetRecordCountScaler
            Wend
    
            'To the beginning of the previous bite, count 1/10th of the scale from there
            lWorksheetRecordCount = lWorksheetRecordCount - lWorksheetRecordCountScaler
            lWorksheetRecordCountScaler = lWorksheetRecordCountScaler / 10
    
        Wend
    
        lWorksheetRecordCount = lWorksheetRecordCount + 1   'Final answer
    

    Can we use JSch for SSH key-based communication?

    It is possible. Have a look at JSch.addIdentity(...)

    This allows you to use key either as byte array or to read it from file.

    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    
    public class UserAuthPubKey {
        public static void main(String[] arg) {
            try {
                JSch jsch = new JSch();
    
                String user = "tjill";
                String host = "192.18.0.246";
                int port = 10022;
                String privateKey = ".ssh/id_rsa";
    
                jsch.addIdentity(privateKey);
                System.out.println("identity added ");
    
                Session session = jsch.getSession(user, host, port);
                System.out.println("session created.");
    
                // disabling StrictHostKeyChecking may help to make connection but makes it insecure
                // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
                // 
                // java.util.Properties config = new java.util.Properties();
                // config.put("StrictHostKeyChecking", "no");
                // session.setConfig(config);
    
                session.connect();
                System.out.println("session connected.....");
    
                Channel channel = session.openChannel("sftp");
                channel.setInputStream(System.in);
                channel.setOutputStream(System.out);
                channel.connect();
                System.out.println("shell channel connected....");
    
                ChannelSftp c = (ChannelSftp) channel;
    
                String fileName = "test.txt";
                c.put(fileName, "./in/");
                c.exit();
                System.out.println("done");
    
            } catch (Exception e) {
                System.err.println(e);
            }
        }
    }
    

    Logging levels - Logback - rule-of-thumb to assign log levels

    I mostly build large scale, high availability type systems, so my answer is biased towards looking at it from a production support standpoint; that said, we assign roughly as follows:

    • error: the system is in distress, customers are probably being affected (or will soon be) and the fix probably requires human intervention. The "2AM rule" applies here- if you're on call, do you want to be woken up at 2AM if this condition happens? If yes, then log it as "error".

    • warn: an unexpected technical or business event happened, customers may be affected, but probably no immediate human intervention is required. On call people won't be called immediately, but support personnel will want to review these issues asap to understand what the impact is. Basically any issue that needs to be tracked but may not require immediate intervention.

    • info: things we want to see at high volume in case we need to forensically analyze an issue. System lifecycle events (system start, stop) go here. "Session" lifecycle events (login, logout, etc.) go here. Significant boundary events should be considered as well (e.g. database calls, remote API calls). Typical business exceptions can go here (e.g. login failed due to bad credentials). Any other event you think you'll need to see in production at high volume goes here.

    • debug: just about everything that doesn't make the "info" cut... any message that is helpful in tracking the flow through the system and isolating issues, especially during the development and QA phases. We use "debug" level logs for entry/exit of most non-trivial methods and marking interesting events and decision points inside methods.

    • trace: we don't use this often, but this would be for extremely detailed and potentially high volume logs that you don't typically want enabled even during normal development. Examples include dumping a full object hierarchy, logging some state during every iteration of a large loop, etc.

    As or more important than choosing the right log levels is ensuring that the logs are meaningful and have the needed context. For example, you'll almost always want to include the thread ID in the logs so you can follow a single thread if needed. You may also want to employ a mechanism to associate business info (e.g. user ID) to the thread so it gets logged as well. In your log message, you'll want to include enough info to ensure the message can be actionable. A log like " FileNotFound exception caught" is not very helpful. A better message is "FileNotFound exception caught while attempting to open config file: /usr/local/app/somefile.txt. userId=12344."

    There are also a number of good logging guides out there... for example, here's an edited snippet from JCL (Jakarta Commons Logging):

    • error - Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
    • warn - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
    • info - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
    • debug - detailed information on the flow through the system. Expect these to be written to logs only.
    • trace - more detailed information. Expect these to be written to logs only.

    Python: Find in list

    Finding the first occurrence

    There's a recipe for that in itertools:

    def first_true(iterable, default=False, pred=None):
        """Returns the first true value in the iterable.
    
        If no true value is found, returns *default*
    
        If *pred* is not None, returns the first item
        for which pred(item) is true.
    
        """
        # first_true([a,b,c], x) --> a or b or c or x
        # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
        return next(filter(pred, iterable), default)
    

    For example, the following code finds the first odd number in a list:

    >>> first_true([2,3,4,5], None, lambda x: x%2==1)
    3  
    

    ssh script returns 255 error

    If there's a problem with authentication or connection, such as not being able to read a password from the terminal, ssh will exit with 255 without being able to run your actual script. Verify to make sure you can run 'true' instead, to see if the ssh connection is established successfully.

    Changing navigation title programmatically

    Swift 5.1

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "What ever you want"
    }
    

    How to change current working directory using a batch file

    A simpler syntax might be

    pushd %root%

    Moving Average Pandas

    A moving average can also be calculated and visualized directly in a line chart by using the following code:

    Example using stock price data:

    import pandas_datareader.data as web
    import matplotlib.pyplot as plt
    import datetime
    plt.style.use('ggplot')
    
    # Input variables
    start = datetime.datetime(2016, 1, 01)
    end = datetime.datetime(2018, 3, 29)
    stock = 'WFC'
    
    # Extrating data
    df = web.DataReader(stock,'morningstar', start, end)
    df = df['Close']
    
    print df 
    
    plt.plot(df['WFC'],label= 'Close')
    plt.plot(df['WFC'].rolling(9).mean(),label= 'MA 9 days')
    plt.plot(df['WFC'].rolling(21).mean(),label= 'MA 21 days')
    plt.legend(loc='best')
    plt.title('Wells Fargo\nClose and Moving Averages')
    plt.show()
    

    Tutorial on how to do this: https://youtu.be/XWAPpyF62Vg

    How to handle a lost KeyStore password in Android?

    Fortunately, I found my lost password along with the keystore path and alias name from my Android studio logs.

    if you are running linux / Unix based machines.

    Navigate to Library Logs directory

    cd ~/Library/Logs/
    

    in there if you remember your android studio version which you used to build the last release APK. Navigate to that Directory

    ex : cd AndroidStudio1.5/

    In there you will find the log files. in any of the log files (idea.log) you will find your keystore credentials

    example

    -Pandroid.injected.signing.store.file=/Users/myuserid/AndroidStudioProjects/keystore/keystore.jks, 
    -Pandroid.injected.signing.store.password=mystorepassword, 
    -Pandroid.injected.signing.key.alias=myandroidkey, 
    -Pandroid.injected.signing.key.password=mykeypassword,
    

    I hope this helps for Android Studio users

    Importing large sql file to MySql via command line

    Importing large sql file to MySql via command line

    1. first download file .
    2. paste file on home.
    3. use following command in your terminals(CMD)
    4. Syntax: mysql -u username -p databsename < file.sql

    Example: mysql -u root -p aanew < aanew.sql

    I need an unordered list without any bullets

    In case you want to keep things simple without resorting to CSS, I just put a &nbsp; in my code lines. I.e., <table></table>.

    Yeah, it leaves a few spaces, but that's not a bad thing.

    Java error: Comparison method violates its general contract

    The exception message is actually pretty descriptive. The contract it mentions is transitivity: if A > B and B > C then for any A, B and C: A > C. I checked it with paper and pencil and your code seems to have few holes:

    if (card1.getRarity() < card2.getRarity()) {
      return 1;
    

    you do not return -1 if card1.getRarity() > card2.getRarity().


    if (card1.getId() == card2.getId()) {
      //...
    }
    return -1;
    

    You return -1 if ids aren't equal. You should return -1 or 1 depending on which id was bigger.


    Take a look at this. Apart from being much more readable, I think it should actually work:

    if (card1.getSet() > card2.getSet()) {
        return 1;
    }
    if (card1.getSet() < card2.getSet()) {
        return -1;
    };
    if (card1.getRarity() < card2.getRarity()) {
        return 1;
    }
    if (card1.getRarity() > card2.getRarity()) {
        return -1;
    }
    if (card1.getId() > card2.getId()) {
        return 1;
    }
    if (card1.getId() < card2.getId()) {
        return -1;
    }
    return cardType - item.getCardType();  //watch out for overflow!
    

    How to create a Rectangle object in Java using g.fillRect method

    Note:drawRect and fillRect are different.

    Draws the outline of the specified rectangle:

    public void drawRect(int x,
            int y,
            int width,
            int height)
    

    Fills the specified rectangle. The rectangle is filled using the graphics context's current color:

    public abstract void fillRect(int x,
            int y,
            int width,
            int height)
    

    How to set min-font-size in CSS

    CSS has a clamp() function that holds the value between the upper and lower bound. The clamp() function enables the selection of the middle value in the range of values between the defined minimum and maximum values.

    It simply takes three dimensions:

    1. Minimum value.
    2. List item
    3. Preferred value Maximum allowed value.

    try with the code below, and check the window resize, which will change the font size you see in the console. i set maximum value 150px and minimum value 100px.

    _x000D_
    _x000D_
    $(window).resize(function(){_x000D_
        console.log($('#element').css('font-size'));_x000D_
    });_x000D_
    console.log($('#element').css('font-size'));
    _x000D_
    h1{_x000D_
        font-size: 10vw; /* Browsers that do not support "MIN () - MAX ()" and "Clamp ()" functions will take this value.*/_x000D_
        font-size: max(100px, min(10vw, 150px)); /* Browsers that do not support the "clamp ()" function will take this value. */_x000D_
        font-size: clamp(100px, 10vw, 150px);_x000D_
    }
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <center>_x000D_
      <h1 id="element">THIS IS TEXT</h1>_x000D_
    </center>
    _x000D_
    _x000D_
    _x000D_

    What is the main difference between Inheritance and Polymorphism?

    inheritance is kind of polymorphism, Exactly in fact inheritance is the dynamic polymorphism. So, when you remove inheritance you can not override anymore.

    How to grep (search) committed code in the Git history

    Okay, twice just today I've seen people wanting a closer equivalent for hg grep, which is like git log -pS but confines its output to just the (annotated) changed lines.

    Which I suppose would be handier than /pattern/ in the pager if you're after a quick overview.

    So here's a diff-hunk scanner that takes git log --pretty=%h -p output and spits annotated change lines. Put it in diffmarkup.l, say e.g. make ~/bin/diffmarkup, and use it like

    git log --pretty=%h -pS pattern | diffmarkup | grep pattern
    
    %option main 8bit nodefault
            // vim: tw=0
    %top{
            #define _GNU_SOURCE 1
    }
    %x commitheader
    %x diffheader
    %x hunk
    %%
            char *afile=0, *bfile=0, *commit=0;
            int aline,aremain,bline,bremain;
            int iline=1;
    
    <hunk>\n        ++iline; if ((aremain+bremain)==0) BEGIN diffheader;
    <*>\n   ++iline;
    
    <INITIAL,commitheader,diffheader>^diff.*        BEGIN diffheader;
    <INITIAL>.*     BEGIN commitheader; if(commit)free(commit); commit=strdup(yytext);
    <commitheader>.*
    
    <diffheader>^(deleted|new|index)" ".*   {}
    <diffheader>^"---".*            if (afile)free(afile); afile=strdup(strchrnul(yytext,'/'));
    <diffheader>^"+++".*            if (bfile)free(bfile); bfile=strdup(strchrnul(yytext,'/'));
    <diffheader,hunk>^"@@ ".*       {
            BEGIN hunk; char *next=yytext+3;
            #define checkread(format,number) { int span; if ( !sscanf(next,format"%n",&number,&span) ) goto lostinhunkheader; next+=span; }
            checkread(" -%d",aline); if ( *next == ',' ) checkread(",%d",aremain) else aremain=1;
            checkread(" +%d",bline); if ( *next == ',' ) checkread(",%d",bremain) else bremain=1;
            break;
            lostinhunkheader: fprintf(stderr,"Lost at line %d, can't parse hunk header '%s'.\n",iline,yytext), exit(1);
            }
    <diffheader>. yyless(0); BEGIN INITIAL;
    
    <hunk>^"+".*    printf("%s:%s:%d:%c:%s\n",commit,bfile+1,bline++,*yytext,yytext+1); --bremain;
    <hunk>^"-".*    printf("%s:%s:%d:%c:%s\n",commit,afile+1,aline++,*yytext,yytext+1); --aremain;
    <hunk>^" ".*    ++aline, ++bline; --aremain; --bremain;
    <hunk>. fprintf(stderr,"Lost at line %d, Can't parse hunk.\n",iline), exit(1);
    

    getResourceAsStream() vs FileInputStream

    getResourceAsStream is the right way to do it for web apps (as you already learned).

    The reason is that reading from the file system cannot work if you package your web app in a WAR. This is the proper way to package a web app. It's portable that way, because you aren't dependent on an absolute file path or the location where your app server is installed.

    How can I get the current user's username in Bash?

    Get the current task's user_struct

    #define get_current_user()              \
    ({                                      \
        struct user_struct *__u;            \
        const struct cred *__cred;          \
        __cred = current_cred();            \
        __u = get_uid(__cred->user);        \
        __u;                                \
    })
    

    Static link of shared library function in gcc

    A bit late but ... I found a link that I saved a couple of years ago and I thought it might be useful for you guys:

    CDE: Automatically create portable Linux applications

    http://www.pgbovine.net/cde.html

    • Just download the program
    • Execute the binary passing as a argument the name of the binary you want make portable, for example: nmap

      ./cde_2011-08-15_64bit nmap

    The program will read all of libs linked to nmap and its dependencias and it will save all of them in a folder called cde-package/ (in the same directory that you are).

    • Finally, you can compress the folder and deploy the portable binary in whatever system.

    Remember, to launch the portable program you have to exec the binary located in cde-package/nmap.cde

    Best regards

    Convert UIImage to NSData and convert back to UIImage in Swift?

    To save as data:

    From StoryBoard, if you want to save "image" data on the imageView of MainStoryBoard, following codes will work.

    let image = UIImagePNGRepresentation(imageView.image!) as NSData?
    

    To load "image" to imageView: Look at exclamation point "!", "?" closely whether that is quite same as this one.

    imageView.image = UIImage(data: image as! Data)
    

    "NSData" type is converted into "Data" type automatically during this process.

    Declare an array in TypeScript

    Here are the different ways in which you can create an array of booleans in typescript:

    let arr1: boolean[] = [];
    let arr2: boolean[] = new Array();
    let arr3: boolean[] = Array();
    
    let arr4: Array<boolean> = [];
    let arr5: Array<boolean> = new Array();
    let arr6: Array<boolean> = Array();
    
    let arr7 = [] as boolean[];
    let arr8 = new Array() as Array<boolean>;
    let arr9 = Array() as boolean[];
    
    let arr10 = <boolean[]> [];
    let arr11 = <Array<boolean>> new Array();
    let arr12 = <boolean[]> Array();
    
    let arr13 = new Array<boolean>();
    let arr14 = Array<boolean>();
    

    You can access them using the index:

    console.log(arr[5]);
    

    and you add elements using push:

    arr.push(true);
    

    When creating the array you can supply the initial values:

    let arr1: boolean[] = [true, false];
    let arr2: boolean[] = new Array(true, false);
    

    More Pythonic Way to Run a Process X Times

    If you are after the side effects that happen within the loop, I'd personally go for the range() approach.

    If you care about the result of whatever functions you call within the loop, I'd go for a list comprehension or map approach. Something like this:

    def f(n):
        return n * n
    
    results = [f(i) for i in range(50)]
    # or using map:
    results = map(f, range(50))
    

    Using "&times" word in html changes to ×

    I suspect you did not know that there are different & escapes in HTML. The W3C you can see the codes. &times means × in HTML code. Use &amp;times instead.

    How can I submit a form using JavaScript?

    Set the name attribute of your form to "theForm" and your code will work.

    Regex for parsing directory and filename

    What language? and why use regex for this simple task?

    If you must:

    ^(.*)/([^/]*)$
    

    gives you the two parts you wanted. You might need to quote the parentheses:

    ^\(.*\)/\([^/]*\)$
    

    depending on your preferred language syntax.

    But I suggest you just use your language's string search function that finds the last "/" character, and split the string on that index.

    How do you rebase the current branch's changes on top of changes being merged in?

    You've got what rebase does backwards. git rebase master does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master on top of the current branch.

    What is the 'realtime' process priority setting for?

    Real-time is the highest priority class available to a process. Therefore, it is different from 'High' in that it's one step greater, and 'Above Normal' in that it's two steps greater.

    Similarly, real-time is also a thread priority level.

    The process priority class raises or lowers all effective thread priorities in the process and is therefore considered the 'base priority'.

    So, a process has a:

    1. Base process priority class.
    2. Individual thread priorities, offsets of the base priority class.

    Since real-time is supposed to be reserved for applications that absolutely must pre-empt other running processes, there is a special security privilege to protect against haphazard use of it. This is defined by the security policy.

    In NT6+ (Vista+), use of the Vista Multimedia Class Scheduler is the proper way to achieve real-time operations in what is not a real-time OS. It works, for the most part, though is not perfect since the OS isn't designed for real-time operations.

    Microsoft considers this priority very dangerous, rightly so. No application should use it except in very specialized circumstances, and even then try to limit its use to temporary needs.

    Combine two or more columns in a dataframe into a new column with a new name

    Using dplyr::mutate:

    library(dplyr)
    df <- mutate(df, x = paste(n, s)) 
    
    df 
    > df
      n  s     b    x
    1 2 aa  TRUE 2 aa
    2 3 bb FALSE 3 bb
    3 5 cc  TRUE 5 cc
    

    biggest integer that can be stored in a double

    The largest integer that can be represented in IEEE 754 double (64-bit) is the same as the largest value that the type can represent, since that value is itself an integer.

    This is represented as 0x7FEFFFFFFFFFFFFF, which is made up of:

    • The sign bit 0 (positive) rather than 1 (negative)
    • The maximum exponent 0x7FE (2046 which represents 1023 after the bias is subtracted) rather than 0x7FF (2047 which indicates a NaN or infinity).
    • The maximum mantissa 0xFFFFFFFFFFFFF which is 52 bits all 1.

    In binary, the value is the implicit 1 followed by another 52 ones from the mantissa, then 971 zeros (1023 - 52 = 971) from the exponent.

    The exact decimal value is:

    179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368

    This is approximately 1.8 x 10308.

    jQuery: how to get which button was clicked upon form submission?

    You want to use window.event.srcElement.id like this:

    function clickTheButton() {
    
    var Sender = window.event.srcElement;
    alert("the item clicked was " + Sender.id)
    
    }
    

    for a button that looks like:

    <input type="button" id="myButton" onclick="clickTheButton();" value="Click Me"/>
    

    you will get an alert that reads: "the item clicked was myButton.

    In your improved example you can add window.event.srcElement to process_form_submission and you will have a reference to whichever element invoked the process.

    Proper way to rename solution (and directories) in Visual Studio

    To rename a website:

    http://www.c-sharpcorner.com/Blogs/46334/rename-website-project-in-visual-studio-2013.aspx

    locate and edit IISExpress's applicationhost.config, found here: C:\Users{username}\Documents\IISExpress\config

    Show values from a MySQL database table inside a HTML table on a webpage

    <?php
    $mysql_hostname = "localhost";
    $mysql_user     = "ram";
    $mysql_password = "ram";
    $mysql_database = "mydb";
    $bd             = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Oops some thing went wrong");
    mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");// we are now connected to database
    
    $result = mysql_query("SELECT * FROM users"); // selecting data through mysql_query()
    
    echo '<table border=1px>';  // opening table tag
    echo'<th>No</th><th>Username</th><th>Password</th><th>Email</th>'; //table headers
    
    while($data = mysql_fetch_array($result))
    {
    // we are running a while loop to print all the rows in a table
    echo'<tr>'; // printing table row
    echo '<td>'.$data['id'].'</td><td>'.$data['username'].'</td><td>'.$data['password'].'</td><td>'.$data['email'].'</td>'; // we are looping all data to be printed till last row in the table
    echo'</tr>'; // closing table row
    }
    
    echo '</table>';  //closing table tag
    ?>
    

    it would print the table like this just read line by line so that you can understand it easily..

    MongoDB "root" user

    I noticed a lot of these answers, use this command:

    use admin
    

    which switches to the admin database. At least in Mongo v4.0.6, creating a user in the context of the admin database will create a user with "_id" : "admin.administrator":

    > use admin
    > db.getUsers()
    [ ]
    > db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' }  ] })
    > db.getUsers()
    [
        {
            "_id" : "admin.administrator",
            "user" : "administrator",
            "db" : "admin",
            "roles" : [
                {
                    "role" : "root",
                    "db" : "admin"
                }
            ],
            "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
            ]
        }
    ]
    

    I emphasize "admin.administrator", for I have a Mongoid (mongodb ruby adapter) application with a different database than admin and I use the URI to reference the database in my mongoid.yml configuration:

    development:
      clients:
        default:
          uri: <%= ENV['MONGODB_URI'] %>
          options:
            connect_timeout: 15
            retry_writes: false
    

    This references the following environment variable:

    export MONGODB_URI='mongodb://administrator:[email protected]/mysite_development?retryWrites=true&w=majority'
    

    Notice the database is mysite_development, not admin. When I try to run the application, I get an error "User administrator (mechanism: scram256) is not authorized to access mysite_development".

    So I return to the Mongo shell delete the user, switch to the specified database and recreate the user:

    $ mongo
    > db.dropUser('administrator')
    > db.getUsers()
    []
    > use mysite_development
    > db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' }  ] })
    > db.getUsers()
    [
        {
            "_id" : "mysite_development.administrator",
            "user" : "administrator",
            "db" : "mysite_development",
            "roles" : [
                {
                    "role" : "root",
                    "db" : "admin"
                }
            ],
            "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
            ]
        }
    ]
    

    Notice that the _id and db changed to reference the specific database my application depends on:

    "_id" : "mysite_development.administrator",
    "db" : "mysite_development",
    

    After making this change, the error went away and I was able to connect to MongoDB fine inside my application.

    Extra Notes:

    In my example above, I deleted the user and recreated the user in the right database context. Had you already created the user in the right database context but given it the wrong roles, you could assign a mongodb built-in role to the user:

    db.grantRolesToUser('administrator', [{ role: 'root', db: 'admin' }])
    

    There is also a db.updateUser command, albiet typically used to update the user password.

    Forcing to download a file using PHP

    Configure your server to send the file with the media type application/octet-stream.

    Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

    Not an answer, but an addendum: I got because running groovysh (Groovy 2.4.13) if JAVA_HOME points to a Java 9 installation (java version "9.0.1" to be precise) fails abysmally:

    java.lang.reflect.InvocationTargetException
            at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.base/java.lang.reflect.Method.invoke(Method.java:564)
            at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:107)
            at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:129)
    Caused by: java.lang.NoClassDefFoundError: Unable to load class groovy.xml.jaxb.JaxbGroovyMethods due to missing dependency javax/xml/bind/JAXBContext
            at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:400)
            at org.codehaus.groovy.ast.ClassNode.lazyClassInit(ClassNode.java:277)
            at org.codehaus.groovy.ast.ClassNode.getMethods(ClassNode.java:397)
            ...
            ..
            .
            ..
            ...
            at org.codehaus.groovy.tools.shell.Groovysh.<init>(Groovysh.groovy:135)
            at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:232)
            at org.codehaus.groovy.tools.shell.Main.<init>(Main.groovy:66)
            at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:232)
            at org.codehaus.groovy.tools.shell.Main.main(Main.groovy:163)
    ... 6 more
    

    The solution was to:

    • Go to the JAXB Project at github.io ("JAXB is licensed under a dual license - CDDL 1.1 and GPL 2.0 with Class-path Exception")

    • Download jaxb-ri-2.3.0.zip

    • Unzip wherever you put your java infrastructure files (in my case, /usr/local/java/jaxb-ri/). Other solution may exist (maybe via SDKMAN, I dunno)

    • Make sure the jars in the lib subdirectory are on the CLASSPATH. I do it via a script started on bash startup, called /etc/profile.d/java.sh, where I added (among many other lines) the following loop:

    Packed into a function...

    function extend_qzminynshg {
       local BASE="/usr/local/java"
       for LIB in jaxb-api.jar  jaxb-core.jar  jaxb-impl.jar  jaxb-jxc.jar  jaxb-xjc.jar; do
          local FQLIB="$BASE/jaxb-ri/lib/$LIB"
          if [[ -f $FQLIB ]]; then
             export CLASSPATH=$FQLIB:$CLASSPATH
          fi
        done
    }
    
    extend_qzminynshg; unset extend_qzminynshg
    

    And it works!

    Better way to cast object to int

    Use Int32.TryParse as follows.

      int test;
      bool result = Int32.TryParse(value, out test);
      if (result)
      {
         Console.WriteLine("Sucess");         
      }
      else
      {
         if (value == null) value = ""; 
         Console.WriteLine("Failure");
      }
    

    Java code To convert byte to Hexadecimal

    I couldn't figure out what exactly you meant by byte String, but here are some conversions from byte to String and vice versa, of course there is a lot more on the official documentations

    Integer intValue = 149;
    

    The corresponding byte value is:

    Byte byteValue = intValue.byteValue(); // this will convert the rightmost byte of the intValue to byte, because Byte is an 8 bit object and Integer is at least 16 bit, and it will give you a signed number in this case -107
    

    get the integer value back from a Byte variable:

    Integer anInt = byteValue.intValue(); // This will convert the byteValue variable to a signed Integer
    

    From Byte and Integer to hex String:
    This is the way I do it:

    Integer anInt = 149
    Byte aByte = anInt.byteValue();
    
    String hexFromInt = "".format("0x%x", anInt); // This will output 0x95
    String hexFromByte = "".format("0x%x", aByte); // This will output 0x95
    

    Converting an array of bytes to a hex string:
    As far as I know there is no simple function to convert all the elements inside an array of some Object to elements of another Object, So you have to do it yourself. You can use the following functions:

    From byte[] to String:

        public static String byteArrayToHexString(byte[] byteArray){
            String hexString = "";
    
            for(int i = 0; i < byteArray.length; i++){
                String thisByte = "".format("%x", byteArray[i]);
                hexString += thisByte;
            }
    
            return hexString;
        }
    

    And from hex string to byte[]:

    public static byte[] hexStringToByteArray(String hexString){
        byte[] bytes = new byte[hexString.length() / 2];
    
        for(int i = 0; i < hexString.length(); i += 2){
            String sub = hexString.substring(i, i + 2);
            Integer intVal = Integer.parseInt(sub, 16);
            bytes[i / 2] = intVal.byteValue();
            String hex = "".format("0x%x", bytes[i / 2]);
        }
    
        return bytes;
    }  
    

    It is too late but I hope this could help some others ;)

    How to get the first non-null value in Java?

    This situation calls for some preprocessor. Because if you write a function (static method) which picks the first not null value, it evaluates all items. It is problem if some items are method calls (may be time expensive method calls). And this methods are called even if any item before them is not null.

    Some function like this

    public static <T> T coalesce(T ...items) …
    

    should be used but before compiling into byte code there should be a preprocessor which find usages of this „coalesce function“ and replaces it with construction like

    a != null ? a : (b != null ? b : c)
    

    Update 2014-09-02:

    Thanks to Java 8 and Lambdas there is possibility to have true coalesce in Java! Including the crucial feature: particular expressions are evaluated only when needed – if earlier one is not null, then following ones are not evaluated (methods are not called, computation or disk/network operations are not done).

    I wrote an article about it Java 8: coalesce – hledáme neNULLové hodnoty – (written in Czech, but I hope that code examples are understandable for everyone).

    LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

    In Visual Studio: Properties -> Advanced -> Entry Point -> write just the name of the function you want the program to begin running from, case sensitive, without any brackets and command line arguments.

    How to update Identity Column in SQL Server?

    ALTER TABLE tablename add newcolumn int
    update tablename set newcolumn=existingcolumnname
    ALTER TABLE tablename DROP COLUMN existingcolumnname;
    EXEC sp_RENAME 'tablename.oldcolumn' , 'newcolumnname', 'COLUMN'
    update tablename set newcolumnname=value where condition
    

    However above code works only if there is no primary-foreign key relation

    Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

    If you want to force Keras to use CPU

    Way 1

    import os
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"   # see issue #152
    os.environ["CUDA_VISIBLE_DEVICES"] = ""
    

    before Keras / Tensorflow is imported.

    Way 2

    Run your script as

    $ CUDA_VISIBLE_DEVICES="" ./your_keras_code.py
    

    See also

    1. https://github.com/keras-team/keras/issues/152
    2. https://github.com/fchollet/keras/issues/4613

    Type Checking: typeof, GetType, or is?

    It depends on what I'm doing. If I need a bool value (say, to determine if I'll cast to an int), I'll use is. If I actually need the type for some reason (say, to pass to some other method) I'll use GetType().

    htaccess <Directory> deny from all

    You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result

    #place this in /system/.htaccess as you had before
    deny from all
    

    Combine two arrays

    This works:

    $output = $array1 + $array2;
    

    Is it possible to log all HTTP request headers with Apache?

    Here is a list of all http-headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

    And here is a list of all apache-logformats: http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#formats

    As you did write correctly, the code for logging a specific header is %{foobar}i where foobar is the name of the header. So, the only solution is to create a specific format string. When you expect a non-standard header like x-my-nonstandard-header, then use %{x-my-nonstandard-header}i. If your server is going to ignore this non-standard-header, why should you want to write it to your logfile? An unknown header has absolutely no effect to your system.

    How do I connect to a specific Wi-Fi network in Android programmatically?

    Before connecting WIFI network you need to check security type of the WIFI network ScanResult class has a capabilities. This field gives you type of network

    Refer: https://developer.android.com/reference/android/net/wifi/ScanResult.html#capabilities

    There are three types of WIFI networks.

    First, instantiate a WifiConfiguration object and fill in the network’s SSID (note that it has to be enclosed in double quotes), set the initial state to disabled, and specify the network’s priority (numbers around 40 seem to work well).

    WifiConfiguration wfc = new WifiConfiguration();
    
    wfc.SSID = "\"".concat(ssid).concat("\"");
    wfc.status = WifiConfiguration.Status.DISABLED;
    wfc.priority = 40;
    

    Now for the more complicated part: we need to fill several members of WifiConfiguration to specify the network’s security mode. For open networks.

    wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    wfc.allowedAuthAlgorithms.clear();
    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    

    For networks using WEP; note that the WEP key is also enclosed in double quotes.

    wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    
    if (isHexString(password)) wfc.wepKeys[0] = password;
    else wfc.wepKeys[0] = "\"".concat(password).concat("\"");
    wfc.wepTxKeyIndex = 0;
    

    For networks using WPA and WPA2, we can set the same values for either.

    wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    
    wfc.preSharedKey = "\"".concat(password).concat("\"");
    

    Finally, we can add the network to the WifiManager’s known list

    WifiManager wfMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int networkId = wfMgr.addNetwork(wfc);
    if (networkId != -1) {
     // success, can call wfMgr.enableNetwork(networkId, true) to connect
    } 
    

    JSON and escaping characters

    This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.

    So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader instance. Any time you are creating a Reader from an InputStream, you need to specify the character encoding, or java.nio.charset.Charset instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8). If you don't specify a Charset, Java will use your platform default encoding, which on Windows is usually CP-1252.

    iOS start Background Thread

    Enable NSZombieEnabled to know which object is being released and then accessed. Then check if the getResultSetFromDB: has anything to do with that. Also check if docids has anything inside and if it is being retained.

    This way you can be sure there is nothing wrong.

    Keyboard shortcut to clear cell output in Jupyter notebook

    Add following at start of cell and run it:

    from IPython.display import clear_output
    clear_output(wait=True)
    

    jQuery validation plugin: accept only alphabetical characters?

    to allow letters ans spaces

    jQuery.validator.addMethod("lettersonly", function(value, element) {
    return this.optional(element) || /^[a-z\s]+$/i.test(value);
    }, "Only alphabetical characters");
    
    $('#yourform').validate({
            rules: {
                name_field: {
                    lettersonly: true
                }
            }
        });
    

    How to include NA in ifelse?

    You can't really compare NA with another value, so using == would not work. Consider the following:

    NA == NA
    # [1] NA
    

    You can just change your comparison from == to %in%:

    ifelse(is.na(test$time) | test$type %in% "A", NA, "1")
    # [1] NA  "1" NA  "1"
    

    Regarding your other question,

    I could get this to work with my existing code if I could somehow change the result of is.na(test$type) to return FALSE instead of TRUE, but I'm not sure how to do that.

    just use ! to negate the results:

    !is.na(test$time)
    # [1]  TRUE  TRUE FALSE  TRUE
    

    Google Maps API: open url by clicking on marker

        function loadMarkers(){
              {% for location in object_list %}
                  var point = new google.maps.LatLng({{location.latitude}},{{location.longitude}});
                  var marker = new google.maps.Marker({
                  position: point,
                  map: map,
                  url: {{location.id}},
              });
    
              google.maps.event.addDomListener(marker, 'click', function() {
                  window.location.href = this.url; });
    
              {% endfor %}
    

    Spring profiles and testing

    @EnableConfigurationProperties needs to be there (you also can annotate your test class), the application-localtest.yml from test/resources will be loaded. A sample with jUnit5

    @ExtendWith(SpringExtension.class)
    @EnableConfigurationProperties
    @ContextConfiguration(classes = {YourClasses}, initializers = ConfigFileApplicationContextInitializer.class)
    @ActiveProfiles(profiles = "localtest")
    class TestActiveProfile {
    
        @Test
        void testActiveProfile(){
    
        }
    }
    

    Remove special symbols and extra spaces and replace with underscore using the replace method

    Remove the \s from your new regex and it should work - whitespace is already included in "anything but alphanumerics".

    Note that you may want to add a + after the ] so you don't get sequences of more than one underscore. You can also chain onto .replace(/^_+|_+$/g,'') to trim off underscores at the start or end of the string.

    How to go back last page

    Actually you can take advantage of the built-in Location service, which owns a "Back" API.

    Here (in TypeScript):

    import {Component} from '@angular/core';
    import {Location} from '@angular/common';
    
    @Component({
      // component's declarations here
    })
    class SomeComponent {
    
      constructor(private _location: Location) 
      {}
    
      backClicked() {
        this._location.back();
      }
    }
    

    Edit: As mentioned by @charith.arumapperuma Location should be imported from @angular/common so the import {Location} from '@angular/common'; line is important.

    Keyboard shortcut to comment lines in Sublime Text 3

    You can add the following lines to Preferences / Key Bindings - User:

    { "keys": ["control+keypad_divide"],"command": "toggle_comment", "args": {"block": false} }, 
    { "keys": ["shift+control+keypad_divide"],"command": "toggle_comment", "args": {"block": true}}
    

    This is how I sorted the problem out - replacing "ctrl" with "control" and "/" with "keypad_divide".

    Angular-cli from css to scss

    A brute force change can be applied. This will work to change, but it's a longer process.

    Go to the app folder src/app

    1. Open this file: app.component.ts

    2. Change this code styleUrls: ['./app.component.css'] to styleUrls: ['./app.component.scss']

    3. Save and close.

    In the same folder src/app

    1. Rename the extension for the app.component.css file to (app.component.scss)

    2. Follow this change for all the other components. (ex. home, about, contact, etc...)

    The angular.json configuration file is next. It's located at the project root.

    1. Search and Replace the css change it to (scss).

    2. Save and close.

    Lastly, Restart your ng serve -o.

    If the compiler complains at you, go over the steps again.

    Make sure to follow the steps in app/src closely.

    Steps to send a https request to a rest service in Node js

    Note if you are using https.request do not directly use the body from res.on('data',... This will fail if you have a large data coming in chunks. So you need to concatenate all the data and then process the response in res.on('end'. Example -

      var options = {
        hostname: "www.google.com",
        port: 443,
        path: "/upload",
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(post_data)
        }
      };
    
      //change to http for local testing
      var req = https.request(options, function (res) {
        res.setEncoding('utf8');
    
        var body = '';
    
        res.on('data', function (chunk) {
          body = body + chunk;
        });
    
        res.on('end',function(){
          console.log("Body :" + body);
          if (res.statusCode != 200) {
            callback("Api call failed with response code " + res.statusCode);
          } else {
            callback(null);
          }
        });
    
      });
    
      req.on('error', function (e) {
        console.log("Error : " + e.message);
        callback(e);
      });
    
      // write data to request body
      req.write(post_data);
      req.end();
    

    What is the difference between a field and a property?

    The difference is clearly explained here.However, just to summarize and highlight :

    The fields are encapsulated inside class for its internal operation whereas properties can be used for exposing the class to outside world in addition to other internal operations shown in the link shared.Additionally, if you want to load certain methods or user controls based on the value of a particular field, then the property will do it for you :

    For example:

    You can function below user control inside your asp.net page by simply assigning a value to the Id preperty of control in your aspx page as given below :

    useMeId.Id=5 ---call the property of user control "UseMe.ascx"
    

    UseMe.ascx

    <%@ Register Src=~/"UseMe.ascx" TagPrefix="uc" TagName="UseMe" %>
    <uc:UseMe runat="Server" id="useMeId" />
    
    UseMe.ascx.cs
    
    private int currentId;
    
    public int Id
       {
          get
          {
             return currentId;
          }
          set
          {
             currentId = value;
           LoadInitialData(currentId);
          }
       }
    Private void LoadinitialData(int currentIdParam)
    {
    //your action
    
    }
    

    Core Data: Quickest way to delete all instances of an entity

    the OOP way without any strings as entities names Swift 3+, Xcode 10+

    func batchDelete<T>(in context: NSManagedObjectContext, fetchRequest: NSFetchRequest<T>) throws {
        guard let request = fetchRequest as? NSFetchRequest<NSFetchRequestResult> else {
            throw ErrorService.defaultError
        }
        let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: request)
        do {
            try context.execute(batchDeleteRequest)
        } catch {
            throw error
        }
    }
    

    then just call in do/catch block

        let fetchRequest: NSFetchRequest<YourEntity> = YourEntity.fetchRequest()
        do {
            let data = try context.fetch(fetchRequest)
            if data.count > 0 {
                try self.batchDelete(in: context, fetchRequest: fetchRequest)
            }
        } catch {
            // throw error
        }
    

    CSS: Position text in the middle of the page

    Try this CSS:

    h1 {
        left: 0;
        line-height: 200px;
        margin-top: -100px;
        position: absolute;
        text-align: center;
        top: 50%;
        width: 100%;
    }
    

    jsFiddle: http://jsfiddle.net/wprw3/

    Regex Explanation ^.*$

    "^.*$"
    

    literally just means select everything

    "^"  // anchors to the beginning of the line
    ".*" // zero or more of any character
    "$"  // anchors to end of line
    

    Proper indentation for Python multiline strings

    It depends on how you want the text to display. If you want it all to be left-aligned then either format it as in the first snippet or iterate through the lines left-trimming all the space.

    How to Call Controller Actions using JQuery in ASP.NET MVC

    the previous response is ASP.NET only

    you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

    and then a similar block of code but simpler...

    $.ajax({ url: '/Controller/Action/Id',
             success: function(data) { alert(data); }, 
             statusCode : {
                 404: function(content) { alert('cannot find resource'); },
                 500: function(content) { alert('internal server error'); }
             }, 
             error: function(req, status, errorObj) {
                   // handle status === "timeout"
                   // handle other errors
             }
    });
    

    I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

    ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

    How to check if a value exists in an array in Ruby

    Several answers suggest Array#include?, but there is one important caveat: Looking at the source, even Array#include? does perform looping:

    rb_ary_includes(VALUE ary, VALUE item)
    {
        long i;
    
        for (i=0; i<RARRAY_LEN(ary); i++) {
            if (rb_equal(RARRAY_AREF(ary, i), item)) {
                return Qtrue;
            }
        }
        return Qfalse;
    }
    

    The way to test the word presence without looping is by constructing a trie for your array. There are many trie implementations out there (google "ruby trie"). I will use rambling-trie in this example:

    a = %w/cat dog bird/
    
    require 'rambling-trie' # if necessary, gem install rambling-trie
    trie = Rambling::Trie.create { |trie| a.each do |e| trie << e end }
    

    And now we are ready to test the presence of various words in your array without looping over it, in O(log n) time, with same syntactic simplicity as Array#include?, using sublinear Trie#include?:

    trie.include? 'bird' #=> true
    trie.include? 'duck' #=> false
    

    php $_GET and undefined index

    Another option would be to suppress the PHP undefined index notice with the @ symbol in front of the GET variable like so:

    $s = @$_GET['s'];
    

    This will disable the notice. It is better to check if the variable has been set and act accordingly.

    But this also works.

    How to copy java.util.list Collection

    You may create a new list with an input of a previous list like so:

    List one = new ArrayList()
    //... add data, sort, etc
    List two = new ArrayList(one);
    

    This will allow you to modify the order or what elemtents are contained independent of the first list.

    Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

    example:

    MyObject value1 = one.get(0);
    MyObject value2 = two.get(0);
    value1 == value2 //true
    value1.setName("hello");
    value2.getName(); //returns "hello"
    

    Edit

    To avoid this you need a deep copy of each element in the list like so:

    List<Torero> one = new ArrayList<Torero>();
    //add elements
    
    List<Torero> two = new Arraylist<Torero>();
    for(Torero t : one){
        Torero copy = deepCopy(t);
        two.add(copy);
    }
    

    with copy like the following:

    public Torero deepCopy(Torero input){
        Torero copy = new Torero();
        copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
    
        return copy;
    }
    

    How do I turn off the mysql password validation?

    Uninstall:

    mysql> uninstall plugin validate_password;
    

    An uninstalled plugin is not displayed by show plugins;

    Install:

    mysql> install plugin validate_password SONAME 'validate_password.so';
    

    Disabled by configuration:

    [mysqld]
    validate_password = OFF
    

    A plugin can be disabled by configuration only if installed.

    How to push object into an array using AngularJS

    Please check this - http://plnkr.co/edit/5Sx4k8tbWaO1qsdMEWYI?p=preview

    Controller-

    var app= angular.module('app', []);
    
    app.controller('TestController', function($scope) {
        this.arrayText = [{text:'Hello',},{text: 'world'}];
    
        this.addText = function(text) {
    
          if(text) {
            var obj = {
              text: text
            };
              this.arrayText.push(obj);
              this.myText = '';
              console.log(this.arrayText);
            }
          } 
     });
    

    HTML

    <form ng-controller="TestController as testCtrl" ng-submit="testCtrl.addText(testCtrl.myText)">
            <input type="text" ng-model="testCtrl.myText" value="Lets go">
            <button type="submit">Add</button>
            <div ng-repeat="item in testCtrl.arrayText">
                <span>{{item}}</span>
            </div>
    </form>
    

    In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

    At the very core, the file extension you use makes no difference as to how perl interprets those files.

    However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

    The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

    If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

    All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

    For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

    C:\Temp> cat t.pl
    package Example::Plot::FourD;
    
    use strict; use warnings;
    
    sub new { bless {} => shift }
    
    sub something { print "something\n" }
    
    "Example::Plot::FourD"
    
    C:\Temp> cat s.pl
    #!/usr/bin/perl
    use strict; use warnings;
    
    BEGIN {
        require 't.pl';
    }
    
    my $p = Example::Plot::FourD->new;
    $p->something;
    
    
    C:\Temp> s
    something
    

    This example shows that module files do not have to end in 1, any true value will do.

    Using StringWriter for XML Serialization

    First of all, beware of finding old examples. You've found one that uses XmlTextWriter, which is deprecated as of .NET 2.0. XmlWriter.Create should be used instead.

    Here's an example of serializing an object into an XML column:

    public void SerializeToXmlColumn(object obj)
    {
        using (var outputStream = new MemoryStream())
        {
            using (var writer = XmlWriter.Create(outputStream))
            {
                var serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(writer, obj);
            }
    
            outputStream.Position = 0;
            using (var conn = new SqlConnection(Settings.Default.ConnectionString))
            {
                conn.Open();
    
                const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
                using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
                {
                    using (var reader = XmlReader.Create(outputStream))
                    {
                        var xml = new SqlXml(reader);
    
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("@Data", xml);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }
    }
    

    WCF service maxReceivedMessageSize basicHttpBinding issue

    When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

        <binding name="MyServiceBinding">
          <security defaultAlgorithmSuite="Basic256Rsa15" 
                    authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                    securityHeaderLayout="Lax" includeTimestamp="true" 
                    messageProtectionOrder="SignBeforeEncrypt" 
                    messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                    requireSignatureConfirmation="false">
            <localClientSettings detectReplays="true" />
            <localServiceSettings detectReplays="true" />
            <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
          </security>
          <textMessageEncoding messageVersion="Soap11WSAddressing10">
            <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                          maxArrayLength="2147483647" maxBytesPerRead="4096" 
                          maxNameTableCharCount="16384"/>
          </textMessageEncoding>
          <httpsTransport maxReceivedMessageSize="2147483647" 
                          maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                          requireClientCertificate="false" />
        </binding>
    

    Specify sudo password for Ansible

    Probably the best way to do this - assuming that you can't use the NOPASSWD solution provided by scottod is to use Mircea Vutcovici's solution in combination with Ansible vault.

    For example, you might have a playbook something like this:

    - hosts: all
    
      vars_files:
        - secret
    
      tasks:
        - name: Do something as sudo
          service: name=nginx state=restarted
          sudo: yes
    

    Here we are including a file called secret which will contain our sudo password.

    We will use ansible-vault to create an encrypted version of this file:

    ansible-vault create secret
    

    This will ask you for a password, then open your default editor to edit the file. You can put your ansible_sudo_pass in here.

    e.g.: secret:

    ansible_sudo_pass: mysudopassword
    

    Save and exit, now you have an encrypted secret file which Ansible is able to decrypt when you run your playbook. Note: you can edit the file with ansible-vault edit secret (and enter the password that you used when creating the file)

    The final piece of the puzzle is to provide Ansible with a --vault-password-file which it will use to decrypt your secret file.

    Create a file called vault.txt and in that put the password that you used when creating your secret file. The password should be a string stored as a single line in the file.

    From the Ansible Docs:

    .. ensure permissions on the file are such that no one else can access your key and do not add your key to source control

    Finally: you can now run your playbook with something like

    ansible-playbook playbook.yml -u someuser -i hosts --sudo --vault-password-file=vault.txt 
    

    The above is assuming the following directory layout:

    .
    |_ playbook.yml
    |_ secret
    |_ hosts
    |_ vault.txt
    

    You can read more about Ansible Vault here: https://docs.ansible.com/playbooks_vault.html

    svn: E155004: ..(path of resource).. is already locked

    Inside the folder

    TortoiseSVN -> Clean up...

    Regular expression search replace in Sublime Text 2

    Here is a visual presentation of the approved answer.

    enter image description here

    How to make a text box have rounded corners?

    You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    

    Decorators with parameters?

    Edit : for an in-depth understanding of the mental model of decorators, take a look at this awesome Pycon Talk. well worth the 30 minutes.

    One way of thinking about decorators with arguments is

    @decorator
    def foo(*args, **kwargs):
        pass
    

    translates to

    foo = decorator(foo)
    

    So if the decorator had arguments,

    @decorator_with_args(arg)
    def foo(*args, **kwargs):
        pass
    

    translates to

    foo = decorator_with_args(arg)(foo)
    

    decorator_with_args is a function which accepts a custom argument and which returns the actual decorator (that will be applied to the decorated function).

    I use a simple trick with partials to make my decorators easy

    from functools import partial
    
    def _pseudo_decor(fun, argument):
        def ret_fun(*args, **kwargs):
            #do stuff here, for eg.
            print ("decorator arg is %s" % str(argument))
            return fun(*args, **kwargs)
        return ret_fun
    
    real_decorator = partial(_pseudo_decor, argument=arg)
    
    @real_decorator
    def foo(*args, **kwargs):
        pass
    

    Update:

    Above, foo becomes real_decorator(foo)

    One effect of decorating a function is that the name foo is overridden upon decorator declaration. foo is "overridden" by whatever is returned by real_decorator. In this case, a new function object.

    All of foo's metadata is overridden, notably docstring and function name.

    >>> print(foo)
    <function _pseudo_decor.<locals>.ret_fun at 0x10666a2f0>
    

    functools.wraps gives us a convenient method to "lift" the docstring and name to the returned function.

    from functools import partial, wraps
    
    def _pseudo_decor(fun, argument):
        # magic sauce to lift the name and doc of the function
        @wraps(fun)
        def ret_fun(*args, **kwargs):
            # pre function execution stuff here, for eg.
            print("decorator argument is %s" % str(argument))
            returned_value =  fun(*args, **kwargs)
            # post execution stuff here, for eg.
            print("returned value is %s" % returned_value)
            return returned_value
    
        return ret_fun
    
    real_decorator1 = partial(_pseudo_decor, argument="some_arg")
    real_decorator2 = partial(_pseudo_decor, argument="some_other_arg")
    
    @real_decorator1
    def bar(*args, **kwargs):
        pass
    
    >>> print(bar)
    <function __main__.bar(*args, **kwargs)>
    
    >>> bar(1,2,3, k="v", x="z")
    decorator argument is some_arg
    returned value is None
    

    How can I get the content of CKEditor using JQuery?

    I was having issues with the getData() not working every time especially when dealing with live ajax.

    Was able to get around it by running:

    for(var instanceName in CKEDITOR.instances){
        CKEDITOR.instances[instanceName].updateElement();
    }
    

    Then use jquery to get the value from the textarea.

    Why use HttpClient for Synchronous Connection

    If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.

    You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.

    If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.

    The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.

    using batch echo with special characters

    Why not use single quote?

    echo '<?xml version="1.0" encoding="utf-8" ?>'
    

    output

    <?xml version="1.0" encoding="utf-8" ?>
    

    private constructor

    private constructor are useful when you don't want your class to be instantiated by user. To instantiate such classes, you need to declare a static method, which does the 'new' and returns the pointer.

    A class with private ctors can not be put in the STL containers, as they require a copy ctor.

    How to find all the dependencies of a table in sql server

    You can use free tool called Advanced SQL Server Dependencies http://advancedsqlserverdependencies.codeplex.com/

    It supports all database objects (tables, views, etc.) and can find dependencies across multiple databases (in case of synonyms).

    Multi-dimensional arrays in Bash

    I've got a pretty simple yet smart workaround: Just define the array with variables in its name. For example:

    for (( i=0 ; i<$(($maxvalue + 1)) ; i++ ))
      do
      for (( j=0 ; j<$(($maxargument + 1)) ; j++ ))
        do
        declare -a array$i[$j]=((Your rule))
      done
    done
    

    Don't know whether this helps since it's not exactly what you asked for, but it works for me. (The same could be achieved just with variables without the array)

    Validate that a string is a positive integer

    Solution 1

    If we consider a JavaScript integer to be a value of maximum 4294967295 (i.e. Math.pow(2,32)-1), then the following short solution will perfectly work:

    function isPositiveInteger(n) {
        return n >>> 0 === parseFloat(n);
    }
    

    DESCRIPTION:

    1. Zero-fill right shift operator does three important things:
      • truncates decimal part
        • 123.45 >>> 0 === 123
      • does the shift for negative numbers
        • -1 >>> 0 === 4294967295
      • "works" in range of MAX_INT
        • 1e10 >>> 0 === 1410065408
        • 1e7 >>> 0 === 10000000
    2. parseFloat does correct parsing of string numbers (setting NaN for non numeric strings)

    TESTS:

    "0"                     : true
    "23"                    : true
    "-10"                   : false
    "10.30"                 : false
    "-40.1"                 : false
    "string"                : false
    "1234567890"            : true
    "129000098131766699.1"  : false
    "-1e7"                  : false
    "1e7"                   : true
    "1e10"                  : false
    "1edf"                  : false
    " "                     : false
    ""                      : false
    

    DEMO: http://jsfiddle.net/5UCy4/37/


    Solution 2

    Another way is good for all numeric values which are valid up to Number.MAX_VALUE, i.e. to about 1.7976931348623157e+308:

    function isPositiveInteger(n) {
        return 0 === n % (!isNaN(parseFloat(n)) && 0 <= ~~n);
    }
    

    DESCRIPTION:

    1. !isNaN(parseFloat(n)) is used to filter pure string values, e.g. "", " ", "string";
    2. 0 <= ~~n filters negative and large non-integer values, e.g. "-40.1", "129000098131766699";
    3. (!isNaN(parseFloat(n)) && 0 <= ~~n) returns true if value is both numeric and positive;
    4. 0 === n % (...) checks if value is non-float -- here (...) (see 3) is evaluated as 0 in case of false, and as 1 in case of true.

    TESTS:

    "0"                     : true
    "23"                    : true
    "-10"                   : false
    "10.30"                 : false
    "-40.1"                 : false
    "string"                : false
    "1234567890"            : true
    "129000098131766699.1"  : false
    "-1e10"                 : false
    "1e10"                  : true
    "1edf"                  : false
    " "                     : false
    ""                      : false
    

    DEMO: http://jsfiddle.net/5UCy4/14/


    The previous version:

    function isPositiveInteger(n) {
        return n == "0" || ((n | 0) > 0 && n % 1 == 0);
    }
    

    DEMO: http://jsfiddle.net/5UCy4/2/

    if variable contains

    If you have a lot of these to check you might want to store a list of the mappings and just loop over that, instead of having a bunch of if/else statements. Something like:

    var CODE_TO_LOCATION = {
      'ST1': 'stoke central',
      'ST2': 'stoke north',
      // ...
    };
    
    function getLocation(text) {
      for (var code in CODE_TO_LOCATION) {
        if (text.indexOf(code) != -1) {
          return CODE_TO_LOCATION[code];
        }
      }
      return null;
    }
    

    This way you can easily add more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.

    What is the symbol for whitespace in C?

    #include <stdio.h>
    main()
    {
    int c,sp,tb,nl;
    sp = 0;
    tb = 0;
    nl = 0;
    while((c = getchar()) != EOF)
    {
       switch( c )
    {
       case ' ':
            ++sp;
         printf("space:%d\n", sp);
         break;
       case  '\t':
            ++tb;
         printf("tab:%d\n", tb);
         break;
       case '\n':
            ++nl;
         printf("new line:%d\n", nl);
         break;
      }
     }
    }
    

    What's the use of session.flush() in Hibernate

    As rightly said in above answers, by calling flush() we force hibernate to execute the SQL commands on Database. But do understand that changes are not "committed" yet. So after doing flush and before doing commit, if you access DB directly (say from SQL prompt) and check the modified rows, you will NOT see the changes.

    This is same as opening 2 SQL command sessions. And changes done in 1 session are not visible to others until committed.

    How can I save a screenshot directly to a file in Windows?

    As far as I know in XP, yes you must use some other app to actually save it.

    Vista comes with the Snipping tool, that simplifies the process a bit!

    HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

    Both answers given worked for the problem I stated -- Thanks!

    In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.

    Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.

    Initializing a two dimensional std::vector

    Suppose you want to initialize a two dimensional integer vector with n rows and m column each having value 'VAL'

    Write it as

    std::vector<vector<int>> arr(n, vector<int>(m,VAL));

    This VAL can be a integer type variable or constant such as 100

    What is the correct syntax of ng-include?

    For those who are looking for the shortest possible "item renderer" solution from a partial, so a combo of ng-repeat and ng-include:

    <div ng-repeat="item in items" ng-include src="'views/partials/item.html'" />

    Actually, if you use it like this for one repeater, it will work, but won't for 2 of them! Angular (v1.2.16) will freak out for some reason if you have 2 of these one after another, so it is safer to close the div the pre-xhtml way:

    <div ng-repeat="item in items" ng-include src="'views/partials/item.html'"></div>

    reducing number of plot ticks

    If somebody still gets this page in search results:

    fig, ax = plt.subplots()
    
    plt.plot(...)
    
    every_nth = 4
    for n, label in enumerate(ax.xaxis.get_ticklabels()):
        if n % every_nth != 0:
            label.set_visible(False)
    

    What is event bubbling and capturing?

    Description:

    quirksmode.org has a nice description of this. In a nutshell (copied from quirksmode):

    Event capturing

    When you use event capturing

                   | |
    ---------------| |-----------------
    | element1     | |                |
    |   -----------| |-----------     |
    |   |element2  \ /          |     |
    |   -------------------------     |
    |        Event CAPTURING          |
    -----------------------------------
    

    the event handler of element1 fires first, the event handler of element2 fires last.

    Event bubbling

    When you use event bubbling

                   / \
    ---------------| |-----------------
    | element1     | |                |
    |   -----------| |-----------     |
    |   |element2  | |          |     |
    |   -------------------------     |
    |        Event BUBBLING           |
    -----------------------------------
    

    the event handler of element2 fires first, the event handler of element1 fires last.


    What to use?

    It depends on what you want to do. There is no better. The difference is the order of the execution of the event handlers. Most of the time it will be fine to fire event handlers in the bubbling phase but it can also be necessary to fire them earlier.

    python: after installing anaconda, how to import pandas

    1. Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.

    2. For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.

    3. Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.

    Launch programs whose path contains spaces

    What you're trying to achieve is simple, and the way you're going about it isn't. Try this (Works fine for me) and save the file as a batch from your text editor. Trust me, it's easier.

    start firefox.exe
    

    Throw HttpResponseException or return Request.CreateErrorResponse?

    Another case for when to use HttpResponseException instead of Response.CreateResponse(HttpStatusCode.NotFound), or other error status code, is if you have transactions in action filters and you want the transactions to be rolled back when returning an error response to the client.

    Using Response.CreateResponse will not roll the transaction back, whereas throwing an exception will.

    PHP function to build query string from array

    As this question is quite old and for PHP, here is a way to do it in the (currently) very popular PHP framework Laravel.

    To encode the query string for a path in your application, give your routes names and then use the route() helper function like so:

    route('documents.list.', ['foo' => 'bar']);
    

    The result will look something like:

    http://localhost/documents/list?foo=bar
    

    Also be aware that if your route has any path segment parameters e.g. /documents/{id}, then make sure you pass an id argument to the route() parameters too, otherwise it will default to using the value of the first parameter.

    Change the maximum upload file size

    You can change it via an .htaccess file.

    .htaccess files are stored in the same directory as your .php files are. They modify configuration for that folder and all sub-folders. You simply use them by creating an .htaccess file in the directory of your choice (or modify it if present).

    The following should enable you to increase your upload limit (if the server provider allows PHP config changes via .htaccess).

    php_value upload_max_filesize 40M
    php_value post_max_size 42M
    

    How do I clone a generic List in Java?

    To clone a generic interface like java.util.List you will just need to cast it. here you are an example:

    List list = new ArrayList();
    List list2 = ((List) ( (ArrayList) list).clone());
    

    It is a bit tricky, but it works, if you are limited to return a List interface, so anyone after you can implement your list whenever he wants.

    I know this answer is close to the final answer, but my answer answers how to do all of that while you are working with List -the generic parent- not ArrayList

    Avoiding NullPointerException in Java

    If null-values are not allowed

    If your method is called externally, start with something like this:

    public void method(Object object) {
      if (object == null) {
        throw new IllegalArgumentException("...");
      }
    

    Then, in the rest of that method, you'll know that object is not null.

    If it is an internal method (not part of an API), just document that it cannot be null, and that's it.

    Example:

    public String getFirst3Chars(String text) {
      return text.subString(0, 3);
    }
    

    However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.

    If null is allowed

    This really depends. If find that I often do something like this:

    if (object == null) {
      // something
    } else {
      // something else
    }
    

    So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?


    It's actually rare for me to use the idiom "if (object != null && ...".

    It may be easier to give you examples, if you show examples of where you typically use the idiom.

    Eclipse DDMS error "Can't bind to local 8600 for debugger"

    I had a similar problem on OSX. It just so happens I had opened two instances of Eclipse so I could refer to some code in another workspace. Eventually I realized the two instances might be interfering with each other so I closed one. After that, I'm no longer seeing the "Can't bind..." error.

    How to access html form input from asp.net code behind

    Since you're using asp.net code-behind, add an id to the element and runat=server.

    You can then reference the objects in the code behind.