Programs & Examples On #Updown

Where is the WPF Numeric UpDown control?

Apologize for keep answering 9 years questions.

I have follow @Michael's answer and it works.

I do it as UserControl where I can drag and drop like a Controls elements. I use MaterialDesign Theme from Nuget to get the Chevron icon and button ripple effect.

The running NumericUpDown from Micheal with modification will be as below:-

enter image description here

The code for user control:-

TemplateNumericUpDown.xaml

<UserControl x:Class="UserControlTemplate.TemplateNumericUpDown"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:UserControlTemplate"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             mc:Ignorable="d" MinHeight="48">
    <Grid Background="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="60"/>
        </Grid.ColumnDefinitions>
        <TextBox x:Name="txtNum" x:FieldModifier="private" Text="{Binding Path=NumValue}" TextChanged="TxtNum_TextChanged" FontSize="36" BorderThickness="0" VerticalAlignment="Center" Padding="5,0"/>
        <Grid Grid.Column="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="30*"/>
                <RowDefinition Height="30*"/>
            </Grid.RowDefinitions>
            <Grid Background="#FF673AB7">
                <Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto" Width="Auto">
                    <materialDesign:PackIcon Kind="ChevronUp" Foreground="White" Height="32.941" Width="32"/>
                </Viewbox>
                <Button x:Name="cmdUp" x:FieldModifier="private" Click="CmdUp_Click" Height="Auto" BorderBrush="{x:Null}" Background="{x:Null}"/>
            </Grid>
            <Grid Grid.Row="1" Background="#FF673AB7">
                <Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto" Width="Auto">
                    <materialDesign:PackIcon Kind="ChevronDown" Foreground="White" Height="32.942" Width="32"/>
                </Viewbox>
                <Button x:Name="cmdDown" x:FieldModifier="private" Click="CmdDown_Click" Height="Auto" BorderBrush="{x:Null}" Background="{x:Null}"/>
            </Grid>
        </Grid>
    </Grid>
</UserControl>

TemplateNumericUpDown.cs

using System.Windows;
using System.Windows.Controls;

namespace UserControlTemplate
{
    /// <summary>
    /// Interaction logic for TemplateNumericUpDown.xaml
    /// </summary>
    public partial class TemplateNumericUpDown : UserControl
    {
        private int _numValue = 0;
        public TemplateNumericUpDown()
        {
            InitializeComponent();
            txtNum.Text = _numValue.ToString();
        }
        public int NumValue
        {
            get { return _numValue; }
            set
            {
                if (value >= 0)
                {
                    _numValue = value;
                    txtNum.Text = value.ToString();
                }
            }
        }

        private void CmdUp_Click(object sender, RoutedEventArgs e)
        {
            NumValue++;
        }

        private void CmdDown_Click(object sender, RoutedEventArgs e)
        {
            NumValue--;
        }

        private void TxtNum_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtNum == null)
            {
                return;
            }

            if (!int.TryParse(txtNum.Text, out _numValue))
                txtNum.Text = _numValue.ToString();
        }
    }
}

On MyPageDesign.xaml, drag and drop created usercontrol will having <UserControlTemplate:TemplateNumericUpDown HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100"/>

enter image description here

To get the value from the template, I use

string Value1 = JournalNumStart.NumValue;
string Value2 = JournalNumEnd.NumValue;

I'm not in good skill yet to binding the Height of the control based from FontSize element, so I set the from my page fontsize manually in usercontrol.

** Note:- I have change the "Archieve" name to Archive on my program =)

Undefined Reference to

  1. Usually headers guards are for header files (i.e., .h ) not for source files ( i.e., .cpp ).
  2. Include the necessary standard headers and namespaces in source files.

LinearNode.h:

#ifndef LINEARNODE_H
#define LINEARNODE_H

class LinearNode
{
    // .....
};

#endif

LinearNode.cpp:

#include "LinearNode.h"
#include <iostream>
using namespace std;
// And now the definitions

LinkedList.h:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

class LinearNode; // Forward Declaration
class LinkedList
{
    // ...
};

#endif

LinkedList.cpp

#include "LinearNode.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;

// Definitions

test.cpp is source file is fine. Note that header files are never compiled. Assuming all the files are in a single folder -

g++ LinearNode.cpp LinkedList.cpp test.cpp -o exe.out

Fatal error: Call to a member function query() on null

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

Reading Datetime value From Excel sheet

i had a similar situation and i used the below code for getting this worked..

Aspose.Cells.LoadOptions loadOptions = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.CSV);

Workbook workbook = new Workbook(fstream, loadOptions);

Worksheet worksheet = workbook.Worksheets[0];

dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDisplayRange.RowCount, worksheet.Cells.MaxDisplayRange.ColumnCount, true);

DataTable dtCloned = dt.Clone();
ArrayList myAL = new ArrayList();

foreach (DataColumn column in dtCloned.Columns)
{
    if (column.DataType == Type.GetType("System.DateTime"))
    {
        column.DataType = typeof(String);
        myAL.Add(column.ColumnName);
    }
}


foreach (DataRow row in dt.Rows)
{
    dtCloned.ImportRow(row);
}



foreach (string colName in myAL)
{
    dtCloned.Columns[colName].Convert(val => DateTime.Parse(Convert.ToString(val)).ToString("MMMM dd, yyyy"));
}


/*******************************/

public static class MyExtension
{
    public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
    {
        foreach (DataRow row in column.Table.Rows)
        {
            row[column] = conversion(row[column]);
        }
    }
}

Hope this helps some1 thx_joxin

Using multiple .cpp files in c++ program?

You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.

Like this-

Second.h:

void second();
int third();
double fourth();

main.cpp:

#include <iostream>
#include "second.h"
int main()
{
    //.....
    return 0;
}

second.cpp:

void second()
{
    //...
}

int third()
{ 
    //...
    return foo;
}

double fourth()
{ 
    //...
    return f;
}

Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

Add space between HTML elements only using CSS

Just use margin or padding.

In your specific case, you could use margin:0 10px only on the 2nd <span>.

UPDATE

Here's a nice CSS3 solution (jsFiddle):

span {
    margin: 0 10px;
}

span:first-of-type {
    margin-left: 0;
}

span:last-of-type {
    margin-right: 0;
}

Advanced element selection using selectors like :nth-child(), :last-child, :first-of-type, etc. is supported since Internet Explorer 9.

javascript - replace dash (hyphen) with a space

In addition to the answers already given you probably want to replace all the occurrences. To do this you will need a regular expression as follows :

str = str.replace(/-/g, ' ');  // Replace all '-'  with ' '

Save range to variable

To save a range and then call it later, you were just missing the "Set"

Set Remember_Range = Selection    or    Range("A3")
Remember_Range.Activate

But for copying and pasting, this quicker. Cuts out the middle man and its one line

Sheets("Copy").Range("A3").Value = Sheets("Paste").Range("A3").Value

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

How to get request URL in Spring Boot RestController

If you don't want any dependency on Spring's HATEOAS or javax.* namespace, use ServletUriComponentsBuilder to get URI of current request:

import org.springframework.web.util.UriComponentsBuilder;

ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();

typedef struct vs struct definitions

struct and typedef are two very different things.

The struct keyword is used to define, or to refer to, a structure type. For example, this:

struct foo {
    int n;
};

creates a new type called struct foo. The name foo is a tag; it's meaningful only when it's immediately preceded by the struct keyword, because tags and other identifiers are in distinct name spaces. (This is similar to, but much more restricted than, the C++ concept of namespaces.)

A typedef, in spite of the name, does not define a new type; it merely creates a new name for an existing type. For example, given:

typedef int my_int;

my_int is a new name for int; my_int and int are exactly the same type. Similarly, given the struct definition above, you can write:

typedef struct foo foo;

The type already has a name, struct foo. The typedef declaration gives the same type a new name, foo.

The syntax allows you to combine a struct and typedef into a single declaration:

typedef struct bar {
    int n;
} bar;

This is a common idiom. Now you can refer to this structure type either as struct bar or just as bar.

Note that the typedef name doesn't become visible until the end of the declaration. If the structure contains a pointer to itself, you have use the struct version to refer to it:

typedef struct node {
    int data;
    struct node *next; /* can't use just "node *next" here */
} node;

Some programmers will use distinct identifiers for the struct tag and for the typedef name. In my opinion, there's no good reason for that; using the same name is perfectly legal and makes it clearer that they're the same type. If you must use different identifiers, at least use a consistent convention:

typedef struct node_s {
    /* ... */
} node;

(Personally, I prefer to omit the typedef and refer to the type as struct bar. The typedef save a little typing, but it hides the fact that it's a structure type. If you want the type to be opaque, this can be a good thing. If client code is going to be referring to the member n by name, then it's not opaque; it's visibly a structure, and in my opinion it makes sense to refer to it as a structure. But plenty of smart programmers disagree with me on this point. Be prepared to read and understand code written either way.)

(C++ has different rules. Given a declaration of struct blah, you can refer to the type as just blah, even without a typedef. Using a typedef might make your C code a little more C++-like -- if you think that's a good thing.)

SQL Server : Arithmetic overflow error converting expression to data type int

SELECT                          
    DATEPART(YEAR, dateTimeStamp) AS [Year]                         
    , DATEPART(MONTH, dateTimeStamp) AS [Month]                         
    , COUNT(*) AS NumStreams                        
    , [platform] AS [Platform]                      
    , deliverableName AS [Deliverable Name]                     
    , SUM(billableDuration) AS NumSecondsDelivered

Assuming that your quoted text is the exact text, one of these columns can't do the mathematical calculations that you want. Double click on the error and it will highlight the line that's causing the problems (if it's different than what's posted, it may not be up there); I tested your code with the variables and there was no problem, meaning that one of these columns (which we don't know more specific information about) is creating this error.

One of your expressions needs to be casted/converted to an int in order for this to go through, which is the meaning of Arithmetic overflow error converting expression to data type int.

Text overflow ellipsis on two lines

Use this if above is not working

 display: -webkit-box;
 max-width: 100%;
 margin: 0 auto;
 -webkit-line-clamp: 2;
 /* autoprefixer: off */
 -webkit-box-orient: vertical;
 /* autoprefixer: on */
 overflow: hidden;
 text-overflow: ellipsis;

ERROR 1064 (42000) in MySQL

I had this error because of using mysql/mariadb reserved words:

INSERT INTO tablename (precision) VALUE (2)

should be

INSERT INTO tablename (`precision`) VALUE (2)

How to parse a JSON file in swift?

Codable

In Swift 4+ is strongly recommended to use Codable instead of JSONSerialization.

This Codable includes two protocols: Decodable and Encodable. This Decodable protocol allows you to decode Data in JSON format to custom struct/class conforming to this protocol.

For example imagine situation that we have this simple Data (array of two objects)

let data = Data("""
[
    {"name":"Steve","age":56}, 
    {"name":"iPhone","age":11}
]
""".utf8)

then have following struct and implement protocol Decodable

struct Person: Decodable {
    let name: String
    let age: Int
}

now you can decode your Data to your array of Person using JSONDecoder where first parameter is type conforming to Decodable and to this type should Data be decoded

do {
    let people = try JSONDecoder().decode([Person].self, from: data)
} catch { print(error) }

... note that decoding has to be marked with try keyword since you could for example make some mistake with naming and then your model can't be decoded correctly ... so you should put it inside do-try-catch block


Cases that key in json is different from name of property:

  • If key is in named using snake_case, you can set decoder's keyDecodingStrategy to convertFromSnakeCase which changes key from property_name to camelCase propertyName

    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let people = try decoder.decode([Person].self, from: data)
    
  • If you need unique name you can use coding keys inside struct/class where you declare name of key

    let data = Data(""" 
    { "userName":"Codable", "age": 1 } 
    """.utf8)
    
    struct Person: Decodable {
    
        let name: String
        let age: Int
    
        enum CodingKeys: String, CodingKey {
            case name = "userName"
            case age
        }
    }
    

How to change options of <select> with jQuery?

For some odd reason this part

$el.empty(); // remove old options

from CMS solution didn't work for me, so instead of that I've simply used this

el.html(' ');

And it's works. So my working code now looks like that:

var newOptions = {
    "Option 1":"option-1",
    "Option 2":"option-2"
};

var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
    $el.append($("<option></option>")
    .attr("value", value).text(key));
});

Is there any simple way to convert .xls file to .csv file? (Excel)

I need to do the same thing. I ended up with something similar to Kman

       static void ExcelToCSVCoversion(string sourceFile,  string targetFile)
    {
        Application rawData = new Application();

        try
        {
            Workbook workbook = rawData.Workbooks.Open(sourceFile);
            Worksheet ws = (Worksheet) workbook.Sheets[1];
            ws.SaveAs(targetFile, XlFileFormat.xlCSV);
            Marshal.ReleaseComObject(ws);
        }

        finally
        {
            rawData.DisplayAlerts = false;
            rawData.Quit();
            Marshal.ReleaseComObject(rawData);
        }


        Console.WriteLine();
        Console.WriteLine($"The excel file {sourceFile} has been converted into {targetFile} (CSV format).");
        Console.WriteLine();
    }

If there are multiple sheets this is lost in the conversion but you could loop over the number of sheets and save each one as csv.

MySQL my.ini location

Open your run console type: services.msc look for: mysql right click properties where is written "path to executable", click and move the cursor to the right until you see the directory of my.ini, it's written "defaults-file-". to reach it manually on your explore folders you have to enable the visualization of hidden elements (explore folder>top menu>visualize>visualize hidden elements)

as explained by this video

https://www.youtube.com/watch?v=SvCAa2XuQhg

Call a Class From another class

First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1

class2 obj= new class2();
obj.thefunctioname(args);

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

Importing text file into excel sheet

I think my answer to my own question here is the simplest solution to what you are trying to do:

  1. Select the cell where the first line of text from the file should be.

  2. Use the Data/Get External Data/From File dialog to select the text file to import.

  3. Format the imported text as required.

  4. In the Import Data dialog that opens, click on Properties...

  5. Uncheck the Prompt for file name on refresh box.

  6. Whenever the external file changes, click the Data/Get External Data/Refresh All button.

Note: in your case, you should probably want to skip step #5.

Create a OpenSSL certificate on Windows

If you're on windows and using apache, maybe via WAMP or the Drupal stack installer, you can additionally download the git for windows package, which includes many useful linux command line tools, one of which is openssl.

The following command creates the self signed certificate and key needed for apache and works fine in windows:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

Recording video feed from an IP camera over a network

I haven't used it yet but I would take a look at http://www.zoneminder.com/ The documentation explains you can install it on a modest machine with linux and use IP cameras for remote recording.

Andrew

Latex - Change margins of only a few pages

\par\vfill\break % Break Last Page

\advance\vsize by 8cm % Advance page height
\advance\voffset by -4cm % Shift top margin
% Start big page
Some pictures
% End big page
\par\vfill\break % Break the page with different margins

\advance\vsize by -8cm % Return old margings and page height
\advance\voffset by 4cm % Return old margings and page height

Difference between BYTE and CHAR in column datatypes

Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.

If you define the field as VARCHAR2(11 BYTE), Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.

By defining the field as VARCHAR2(11 CHAR) you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.

How to sort by dates excel?

The hashes are just because your column width is not enough to display the "number".

About the sorting, you should review how you system region and language is configured. For the US region, Excel date input should be "5/17/2012" not "17/05/2012" (this 17-may-12).

Regards

Deserialize JSON into C# dynamic object?

With Cinchoo ETL - an open source library available to parse JSON into a dynamic object:

string json = @"{
    ""key1"": [
        {
            ""action"": ""open"",
            ""timestamp"": ""2018-09-05 20:46:00"",
            ""url"": null,
            ""ip"": ""66.102.6.98""
        }
    ]
}";
using (var p = ChoJSONReader.LoadText(json)
    .WithJSONPath("$.*")
    )
{
    foreach (var rec in p)
    {
        Console.WriteLine("Action: " + rec.action);
        Console.WriteLine("Timestamp: " + rec.timestamp);
        Console.WriteLine("URL: " + rec.url);
        Console.WriteLine("IP address: " + rec.ip);
    }
}

Output:

Action: open
Timestamp: 2018-09-05 20:46:00
URL: http://www.google.com
IP address: 66.102.6.98

Disclaimer: I'm the author of this library.

What's the difference between SoftReference and WeakReference in Java?

SoftReference is designed for caches. When it is found that a WeakReference references an otherwise unreachable object, then it will get cleared immediately. SoftReference may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx). SoftReferences will be cleared before OutOfMemoryError is thrown, unless otherwise reachable.

plain count up timer in javascript

Note: Always include jQuery before writing jQuery scripts

Step1: setInterval function is called every 1000ms (1s)

Stpe2: In that function. Increment the seconds

Step3: Check the Conditions

_x000D_
_x000D_
<span id="count-up">0:00</span>_x000D_
<script>_x000D_
   var min    = 0;_x000D_
      var second = 00;_x000D_
      var zeroPlaceholder = 0;_x000D_
      var counterId = setInterval(function(){_x000D_
                        countUp();_x000D_
                      }, 1000);_x000D_
_x000D_
      function countUp () {_x000D_
          second++;_x000D_
          if(second == 59){_x000D_
            second = 00;_x000D_
            min = min + 1;_x000D_
          }_x000D_
          if(second == 10){_x000D_
              zeroPlaceholder = '';_x000D_
          }else_x000D_
          if(second == 00){_x000D_
              zeroPlaceholder = 0;_x000D_
          }_x000D_
_x000D_
          document.getElementById("count-up").innerText = min+':'+zeroPlaceholder+second;_x000D_
      }_x000D_
</script>
_x000D_
_x000D_
_x000D_

How can I get the full/absolute URL (with domain) in Django?

This worked for me in my template:

{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% url 'equipos:marca_filter' %}

I needed the full url to pass it to a js fetch function. I hope this help you.

When should a class be Comparable and/or Comparator?

Difference between Comparator and Comparable interfaces

Comparable is used to compare itself by using with another object.

Comparator is used to compare two datatypes are objects.

How can I scan barcodes on iOS?

You can find another native iOS solution using Swift 4 and Xcode 9 at below. Native AVFoundation framework used with in this solution.

First part is the a subclass of UIViewController which have related setup and handler functions for AVCaptureSession.

import UIKit
import AVFoundation

class BarCodeScannerViewController: UIViewController {

    let captureSession = AVCaptureSession()
    var videoPreviewLayer: AVCaptureVideoPreviewLayer!
    var initialized = false

    let barCodeTypes = [AVMetadataObject.ObjectType.upce,
                        AVMetadataObject.ObjectType.code39,
                        AVMetadataObject.ObjectType.code39Mod43,
                        AVMetadataObject.ObjectType.code93,
                        AVMetadataObject.ObjectType.code128,
                        AVMetadataObject.ObjectType.ean8,
                        AVMetadataObject.ObjectType.ean13,
                        AVMetadataObject.ObjectType.aztec,
                        AVMetadataObject.ObjectType.pdf417,
                        AVMetadataObject.ObjectType.itf14,
                        AVMetadataObject.ObjectType.dataMatrix,
                        AVMetadataObject.ObjectType.interleaved2of5,
                        AVMetadataObject.ObjectType.qr]

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setupCapture()
        // set observer for UIApplicationWillEnterForeground, so we know when to start the capture session again
        NotificationCenter.default.addObserver(self,
                                           selector: #selector(willEnterForeground),
                                           name: .UIApplicationWillEnterForeground,
                                           object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // this view is no longer topmost in the app, so we don't need a callback if we return to the app.
        NotificationCenter.default.removeObserver(self,
                                              name: .UIApplicationWillEnterForeground,
                                              object: nil)
    }

    // This is called when we return from another app to the scanner view
    @objc func willEnterForeground() {
        setupCapture()
    }

    func setupCapture() {
        var success = false
        var accessDenied = false
        var accessRequested = false

        let authorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if authorizationStatus == .notDetermined {
            // permission dialog not yet presented, request authorization
            accessRequested = true
            AVCaptureDevice.requestAccess(for: .video,
                                      completionHandler: { (granted:Bool) -> Void in
                                          self.setupCapture();
            })
            return
        }
        if authorizationStatus == .restricted || authorizationStatus == .denied {
            accessDenied = true
        }
        if initialized {
            success = true
        } else {
            let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera,
                                                                                        .builtInTelephotoCamera,
                                                                                        .builtInDualCamera],
                                                                          mediaType: .video,
                                                                          position: .unspecified)

            if let captureDevice = deviceDiscoverySession.devices.first {
                do {
                    let videoInput = try AVCaptureDeviceInput(device: captureDevice)
                    captureSession.addInput(videoInput)
                    success = true
                } catch {
                    NSLog("Cannot construct capture device input")
                }
            } else {
                NSLog("Cannot get capture device")
            }
        }
        if success {
            DispatchQueue.global().async {
                self.captureSession.startRunning()
                DispatchQueue.main.async {
                    let captureMetadataOutput = AVCaptureMetadataOutput()
                    self.captureSession.addOutput(captureMetadataOutput)
                    let newSerialQueue = DispatchQueue(label: "barCodeScannerQueue") // in iOS 11 you can use main queue
                    captureMetadataOutput.setMetadataObjectsDelegate(self, queue: newSerialQueue)
                    captureMetadataOutput.metadataObjectTypes = self.barCodeTypes
                    self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
                    self.videoPreviewLayer.videoGravity = .resizeAspectFill
                    self.videoPreviewLayer.frame = self.view.layer.bounds
                    self.view.layer.addSublayer(self.videoPreviewLayer)
                } 
            }
            initialized = true
        } else {
            // Only show a dialog if we have not just asked the user for permission to use the camera.  Asking permission
            // sends its own dialog to th user
            if !accessRequested {
                // Generic message if we cannot figure out why we cannot establish a camera session
                var message = "Cannot access camera to scan bar codes"
                #if (arch(i386) || arch(x86_64)) && (!os(macOS))
                    message = "You are running on the simulator, which does not hae a camera device.  Try this on a real iOS device."
                #endif
                if accessDenied {
                    message = "You have denied this app permission to access to the camera.  Please go to settings and enable camera access permission to be able to scan bar codes"
                }
                let alertPrompt = UIAlertController(title: "Cannot access camera", message: message, preferredStyle: .alert)
                let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                    self.navigationController?.popViewController(animated: true)
                })
                alertPrompt.addAction(confirmAction)
                self.present(alertPrompt, animated: true, completion: nil)
            }
        }
    }

    func handleCapturedOutput(metadataObjects: [AVMetadataObject]) {
        if metadataObjects.count == 0 {
            return
        }

        guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject else {
            return
        }

        if barCodeTypes.contains(metadataObject.type) {
            if let metaDataString = metadataObject.stringValue {
                captureSession.stopRunning()
                displayResult(code: metaDataString)
                return
            }
        }
    }

    func displayResult(code: String) {
        let alertPrompt = UIAlertController(title: "Bar code detected", message: code, preferredStyle: .alert)
        if let url = URL(string: code) {
            let confirmAction = UIAlertAction(title: "Launch URL", style: .default, handler: { (action) -> Void in
                UIApplication.shared.open(url, options: [:], completionHandler: { (result) in
                    if result {
                        NSLog("opened url")
                    } else {
                        let alertPrompt = UIAlertController(title: "Cannot open url", message: nil, preferredStyle: .alert)
                        let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                        })
                        alertPrompt.addAction(confirmAction)
                        self.present(alertPrompt, animated: true, completion: {
                            self.setupCapture()
                        })
                    }
                })        
            })
            alertPrompt.addAction(confirmAction)
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
            self.setupCapture()
        })
        alertPrompt.addAction(cancelAction)
        present(alertPrompt, animated: true, completion: nil)
    }

}

Second part is the extension of our UIViewController subclass for AVCaptureMetadataOutputObjectsDelegate where we catch the captured outputs.

extension BarCodeScannerViewController: AVCaptureMetadataOutputObjectsDelegate {

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        handleCapturedOutput(metadataObjects: metadataObjects)
    }

}

Update for Swift 4.2

.UIApplicationWillEnterForegroundchanges as UIApplication.willEnterForegroundNotification.

Custom Cell Row Height setting in storyboard is not responding

I have recently been wrestling with this. My issue was the solutions posted above using the heightForRowAtIndexPath: method would work for iOS 7.1 in the Simulator but then have completely screwed up results by simply switching to iOS 8.1.

I began reading more about self-sizing cells (introduced in iOS 8, read here). It was apparent that the use of UITableViewAutomaticDimension would help in iOS 8. I tried using that technique and deleted the use of heightForRowAtIndexPath: and voila, it was working perfect in iOS 8 now. But then iOS 7 wasn't. What was I to do? I needed heightForRowAtIndexPath: for iOS 7 and not for iOS 8.

Here is my solution (trimmed up for brevity's sake) which borrow's from the answer @JosephH posted above:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 50.;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    // ...
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        return UITableViewAutomaticDimension;

    } else {
        NSString *cellIdentifier = [self reuseIdentifierForCellAtIndexPath:indexPath];
        static NSMutableDictionary *heightCache;
        if (!heightCache)
            heightCache = [[NSMutableDictionary alloc] init];
        NSNumber *cachedHeight = heightCache[cellIdentifier];
        if (cachedHeight)
            return cachedHeight.floatValue;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    CGFloat height = cell.bounds.size.height;
    heightCache[cellIdentifier] = @(height);
    return height;
    }
}

- (NSString *)reuseIdentifierForCellAtIndexPath:(NSIndexPath *)indexPath {
    NSString * reuseIdentifier;
    switch (indexPath.row) {
        case 0:
            reuseIdentifier = EventTitleCellIdentifier;
            break;
        case 2:
            reuseIdentifier = EventDateTimeCellIdentifier;
            break;
        case 4:
            reuseIdentifier = EventContactsCellIdentifier;
            break;
        case 6:
            reuseIdentifier = EventLocationCellIdentifier;
            break;
        case 8:
            reuseIdentifier = NotesCellIdentifier;
            break;
        default:
            reuseIdentifier = SeparatorCellIdentifier;
            break;
    }

    return reuseIdentifier;
}

SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0") is actually from a set of macro definitions I am using which I found somewhere (very helpful). They are defined as:

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

What do the terms "CPU bound" and "I/O bound" mean?

It's pretty intuitive:

A program is CPU bound if it would go faster if the CPU were faster, i.e. it spends the majority of its time simply using the CPU (doing calculations). A program that computes new digits of π will typically be CPU-bound, it's just crunching numbers.

A program is I/O bound if it would go faster if the I/O subsystem was faster. Which exact I/O system is meant can vary; I typically associate it with disk, but of course networking or communication in general is common too. A program that looks through a huge file for some data might become I/O bound, since the bottleneck is then the reading of the data from disk (actually, this example is perhaps kind of old-fashioned these days with hundreds of MB/s coming in from SSDs).

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

Spring Boot JPA - configuring auto reconnect

For those who want to do it from YAML with multiple data sources, there is a great blog post about it: https://springframework.guru/how-to-configure-multiple-data-sources-in-a-spring-boot-application/

It basically says you both need to configure data source properties and datasource like this:

@Bean
@Primary
@ConfigurationProperties("app.datasource.member")
public DataSourceProperties memberDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.member.hikari")
public DataSource memberDataSource() {
    return memberDataSourceProperties().initializeDataSourceBuilder()
            .type(HikariDataSource.class).build();
}

Do not forget to remove @Primary from other datasources.

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

Comparing floating point number to zero

You can use std::nextafter with a fixed factor of the epsilon of a value like the following:

bool isNearlyEqual(double a, double b)
{
  int factor = /* a fixed factor of epsilon */;

  double min_a = a - (a - std::nextafter(a, std::numeric_limits<double>::lowest())) * factor;
  double max_a = a + (std::nextafter(a, std::numeric_limits<double>::max()) - a) * factor;

  return min_a <= b && max_a >= b;
}

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

Java: Simplest way to get last word in a string

You can do that with StringUtils (from Apache Commons Lang). It avoids index-magic, so it's easier to understand. Unfortunately substringAfterLast returns empty string when there is no separator in the input string so we need the if statement for that case.

public static String getLastWord(String input) {
    String wordSeparator = " ";
    boolean inputIsOnlyOneWord = !StringUtils.contains(input, wordSeparator);
    if (inputIsOnlyOneWord) {
        return input;
    }
    return StringUtils.substringAfterLast(input, wordSeparator);
}

How to remove responsive features in Twitter Bootstrap 3?

To inactivate the non-desktop styles you just have to change 4 lines of code in the variables.less file. Set the screen width breakpoints in the variables.less file like this:

// Media queries breakpoints
// --------------------------------------------------

// Extra small screen / phone
// Note: Deprecated @screen-xs and @screen-phone as of v3.0.1
@screen-xs:                  1px;
@screen-xs-min:              @screen-xs;
@screen-phone:               @screen-xs-min;

// Small screen / tablet
// Note: Deprecated @screen-sm and @screen-tablet as of v3.0.1
@screen-sm:                  2px;
@screen-sm-min:              @screen-sm;
@screen-tablet:              @screen-sm-min;

// Medium screen / desktop
// Note: Deprecated @screen-md and @screen-desktop as of v3.0.1
@screen-md:                  3px;
@screen-md-min:              @screen-md;
@screen-desktop:             @screen-md-min;

// Large screen / wide desktop
// Note: Deprecated @screen-lg and @screen-lg-desktop as of v3.0.1
@screen-lg:                  9999px;
@screen-lg-min:              @screen-lg;
@screen-lg-desktop:          @screen-lg-min;

This sets the min-width on the desktop style media query lower so that it applies to all screen widths. Thanks to 2calledchaos for the improvement! Some base styles are defined in the mobile styles, so we need to be sure to include them.

Edit: chris notes that you can set these variables in the online less compiler on the bootstrap site

Setting a divs background image to fit its size?

Wanted to add a solution for IE8 and below (as low as IE5.5 I think), which cannot use background-size

div{
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=
'/path/to/img.jpg', sizingMethod='scale');
}

Origin <origin> is not allowed by Access-Control-Allow-Origin

You have to enable CORS to solve this

if your app is created with simple node.js

set it in your response headers like

var http = require('http');

http.createServer(function (request, response) {
response.writeHead(200, {
    'Content-Type': 'text/plain',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
});
response.end('Hello World\n');
}).listen(3000);

if your app is created with express framework

use a CORS middleware like

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

and apply via

app.configure(function() {
    app.use(allowCrossDomain);
    //some other code
});    

Here are two reference links

  1. how-to-allow-cors-in-express-nodejs
  2. diving-into-node-js-very-first-app #see the Ajax section

PHP - Check if the page run on Mobile or Desktop browser

There are many great open source projects that make detection a lot easier. To name two:

  1. PHP mobile detect
  2. WURFL

regex.test V.S. string.match to know if a string matches a regular expression

This is my benchmark results benchmark results

test 4,267,740 ops/sec ±1.32% (60 runs sampled)

exec 3,649,719 ops/sec ±2.51% (60 runs sampled)

match 3,623,125 ops/sec ±1.85% (62 runs sampled)

indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)

test method is faster than the match method, but the fastest method is the indexOf

Visual Studio 2015 installer hangs during install?

During the installation if you think it has hung (notably during the "Android SDK Setup"), browse to your %temp% directory and order by "Date modified" (descending), there should be a bunch of log files created by the installer.

The one for the "Android SDK Setup" will be named "AndroidSDK_SI.log" (or similar).

Open the file and got to the end of it (Ctrl+End), this should indicate the progress of the current file that is being downloaded.

i.e: "(80%, 349 KiB/s, 99 seconds left)"

Reopening the file, again going to the end, you should see further indication that the download has progressed (or you could just track the modified timestamp of the file [in minutes]).

i.e: "(99%, 351 KiB/s, 1 seconds left)"

Unfortunately, the installer doesn't indicate this progress (it's running in a separate "Java.exe" process, used by the Android SDK).

This seems like a rather long-winded way to check what's happening but does give an indication that the installer hasn't hung and is doing something, albeit very slowly.

Grab a segment of an array in Java without creating a new array on heap

Arrays.asList(myArray) delegates to new ArrayList(myArray), which doesn't copy the array but just stores the reference. Using List.subList(start, end) after that makes a SubList which just references the original list (which still just references the array). No copying of the array or its contents, just wrapper creation, and all lists involved are backed by the original array. (I thought it'd be heavier.)

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

JNDI stands for Java Naming and Directory Interface. It comes standard with J2EE.

What is its basic use?

With this API, you can access many types of data, like objects, devices, files of naming and directory services, eg. it is used by EJB to find remote objects. JNDI is designed to provide a common interface to access existing services like DNS, NDS, LDAP, CORBA and RMI.

When it is used?

You can use the JNDI to perform naming operations, including read operations and operations for updating the namespace. The following operations are described here.

How to get a list of current open windows/process with Java?

There is no platform-neutral way of doing this. In the 1.6 release of Java, a "Desktop" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.

If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

you can try something like this, or just copy and past below piece.

boolean exception = true;
Charset charset = Charset.defaultCharset(); //Try the default one first.        
int index = 0;

while(exception) {
    try {
        lines = Files.readAllLines(f.toPath(),charset);
          for (String line: lines) {
              line= line.trim();
              if(line.contains(keyword))
                  values.add(line);
              }           
        //No exception, just returns
        exception = false; 
    } catch (IOException e) {
        exception = true;
        //Try the next charset
        if(index<Charset.availableCharsets().values().size())
            charset = (Charset) Charset.availableCharsets().values().toArray()[index];
        index ++;
    }
}

Generate random string/characters in JavaScript

Expanding on Doubletap's elegant example by answering the issues Gertas and Dragon brought up. Simply add in a while loop to test for those rare null circumstances, and limit the characters to five.

function rndStr() {
    x=Math.random().toString(36).substring(7).substr(0,5);
    while (x.length!=5){
        x=Math.random().toString(36).substring(7).substr(0,5);
    }
    return x;
}

Here's a jsfiddle alerting you with a result: http://jsfiddle.net/pLJJ7/

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

Dump all tables in CSV format using 'mysqldump'

It looks like others had this problem also, and there is a simple Python script now, for converting output of mysqldump into CSV files.

wget https://raw.githubusercontent.com/jamesmishra/mysqldump-to-csv/master/mysqldump_to_csv.py
mysqldump -u username -p --host=rdshostname database table | python mysqldump_to_csv.py > table.csv

Postgres: clear entire database before re-creating / re-populating from bash script

To dump:

pg_dump -Fc mydb > db.dump

To restore:

pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d my_db db/latest.dump

Get The Current Domain Name With Javascript (Not the path, etc.)

If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.

The following code does this:

var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;

if (isSubdomain) {
    domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
  domain = window.location.hostname;
}

http://jsfiddle.net/5U366/4/

Excel VBA Automation Error: The object invoked has disconnected from its clients

I have had this problem on multiple projects converting Excel 2000 to 2010. Here is what I found which seems to be working. I made two changes, but not sure which caused the success:

1) I changed how I closed and saved the file (from close & save = true to save as the same file name and close the file:

...
    Dim oFile           As Object       ' File being processed
...
[Where the error happens - where aArray(i) is just the name of an Excel.xlsb file]
   Set oFile = GetObject(aArray(i))
...
'oFile.Close SaveChanges:=True    - OLD CODE WHICH ERROR'D
'New Code
oFile.SaveAs Filename:=oFile.Name
oFile.Close SaveChanges:=False

2) I went back and looked for all of the .range in the code and made sure it was the full construct..

Application.Workbooks("workbook name").Worksheets("worksheet name").Range("G19").Value

or (not 100% sure if this is correct syntax, but this is the 'effort' i made)

ActiveSheet.Range("A1").Select

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Truncate with condition

No, TRUNCATE is all or nothing. You can do a DELETE FROM <table> WHERE <conditions> but this loses the speed advantages of TRUNCATE.

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

Properties file with a list as the value for an individual key

There's probably a another way or better. But this is how I do this in Spring Boot.

My property file contains the following lines. "," is the delimiter in each line.

mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;

My server config

@Configuration
public class ServerConfig {

    @Inject
    private Environment env;

    @Bean
    public MMLProperties mmlProperties() {
        MMLProperties properties = new MMLProperties();
        properties.setMmmlPots(env.getProperty("mml.pots"));
        properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
        properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
        return properties;
    }
}

MMLProperties class.

public class MMLProperties {
    private String mmlPots;
    private String mmlIsdnGrunntengingar;
    private String mmlIsdnStofntengingar;

    public MMLProperties() {
        super();
    }

    public void setMmmlPots(String mmlPots) {
        this.mmlPots = mmlPots;
    }

    public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
        this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
    }

    public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
        this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
    }

    // These three public getXXX functions then take care of spliting the properties into List
    public List<String> getMmmlCommandForPotsAsList() {
        return getPropertieAsList(mmlPots);
    }

    public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
        return getPropertieAsList(mmlIsdnGrunntengingar);
    }

    public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
        return getPropertieAsList(mmlIsdnStofntengingar);
    }

    private List<String> getPropertieAsList(String propertie) {
        return ((propertie != null) || (propertie.length() > 0))
        ? Arrays.asList(propertie.split("\\s*,\\s*"))
        : Collections.emptyList();
    }
}

Then in my Runner class I Autowire MMLProperties

@Component
public class Runner implements CommandLineRunner {

    @Autowired
    MMLProperties mmlProperties;

    @Override
    public void run(String... arg0) throws Exception {
        // Now I can call my getXXX function to retrieve the properties as List
        for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
            System.out.println(command);
        }
    }
}

Hope this helps

"Strict Standards: Only variables should be passed by reference" error

array_shift the only parameter is an array passed by reference. The return value of explode(".", $value) does not have any reference. Hence the error.

You should store the return value to a variable first.

    $arr = explode(".", $value);
    $extension = strtolower(array_pop($arr));   
    $fileName = array_shift($arr);

From PHP.net

The following things can be passed by reference:

- Variables, i.e. foo($a)
- New statements, i.e. foo(new foobar())
- [References returned from functions][2]

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

how to convert .java file to a .class file

A .java file is the code file. A .class file is the compiled file.

It's not exactly "conversion" - it's compilation. Suppose your file was called "herb.java", you would write (in the command prompt):

 javac herb.java

It will create a herb.class file in the current folder.

It is "executable" only if it contains a static void main(String[]) method inside it. If it does, you can execute it by running (again, command prompt:)

 java herb

Send mail via Gmail with PowerShell V2's Send-MailMessage

On a Windows 8.1 machine I got Send-MailMessage to send an email with an attachment through Gmail using the following script:

$EmFrom = "[email protected]"
$username = "[email protected]"
$pwd = "YOURPASSWORD"
$EmTo = "[email protected]"
$Server = "smtp.gmail.com"
$port = 587
$Subj = "Test"
$Bod = "Test 123"
$Att = "c:\Filename.FileType"
$securepwd = ConvertTo-SecureString $pwd -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $securepwd
Send-MailMessage -To $EmTo -From $EmFrom -Body $Bod -Subject $Subj -Attachments $Att -SmtpServer $Server -port $port -UseSsl  -Credential $cred

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

This is how I do. I have added explanation to understand what the heck is going on.

Initialize Local Repository

  • first initialize Git with

    git init

  • Add all Files for version control with

    git add .

  • Create a commit with message of your choice

    git commit -m 'AddingBaseCode'

Initialize Remote Repository

  • Create a project on GitHub and copy the URL of your project . as shown below:

    enter image description here

Link Remote repo with Local repo

  • Now use copied URL to link your local repo with remote GitHub repo. When you clone a repository with git clone, it automatically creates a remote connection called origin pointing back to the cloned repository. The command remote is used to manage set of tracked repositories.

    git remote add origin https://github.com/hiteshsahu/Hassium-Word.git

Synchronize

  • Now we need to merge local code with remote code. This step is critical otherwise we won't be able to push code on GitHub. You must call 'git pull' before pushing your code.

    git pull origin master --allow-unrelated-histories

Commit your code

  • Finally push all changes on GitHub

    git push -u origin master

relative path to CSS file

Background

Absolute: The browser will always interpret / as the root of the hostname. For example, if my site was http://google.com/ and I specified /css/images.css then it would search for that at http://google.com/css/images.css. If your project root was actually at /myproject/ it would not find the css file. Therefore, you need to determine where your project folder root is relative to the hostname, and specify that in your href notation.

Relative: If you want to reference something you know is in the same path on the url - that is, if it is in the same folder, for example http://mysite.com/myUrlPath/index.html and http://mysite.com/myUrlPath/css/style.css, and you know that it will always be this way, you can go against convention and specify a relative path by not putting a leading / in front of your path, for example, css/style.css.

Filesystem Notations: Additionally, you can use standard filesystem notations like ... If you do http://google.com/images/../images/../images/myImage.png it would be the same as http://google.com/images/myImage.png. If you want to reference something that is one directory up from your file, use ../myFile.css.


Your Specific Case

In your case, you have two options:

  • <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  • <link rel="stylesheet" type="text/css" href="css/styles.css"/>

The first will be more concrete and compatible if you move things around, however if you are planning to keep the file in the same location, and you are planning to remove the /ServletApp/ part of the URL, then the second solution is better.

Python Pandas replicate rows in dataframe

This is an old question, but since it still comes up at the top of my results in Google, here's another way.

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

Say you want to replicate the rows where col1="b".

reps = [3 if val=="b" else 1 for val in df.col1]
df.loc[np.repeat(df.index.values, reps)]

You could replace the 3 if val=="b" else 1 in the list interpretation with another function that could return 3 if val=="b" or 4 if val=="c" and so on, so it's pretty flexible.

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Object.entries() returns an array whose elements are arrays corresponding to the enumerable property [key, value] pairs found directly upon object. The ordering of the properties is the same as that given by looping over the property values of the object manually.

- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Description

The Object.entries function returns almost the exact output you're asking for, except the keys are strings instead of numbers.

_x000D_
_x000D_
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
console.log(Object.entries(obj));
_x000D_
_x000D_
_x000D_

If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.

_x000D_
_x000D_
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
const toNumericPairs = input => {_x000D_
    const entries = Object.entries(input);_x000D_
    return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));_x000D_
}_x000D_
_x000D_
console.log(toNumericPairs(obj));
_x000D_
_x000D_
_x000D_

I use an arrow function and Object.assign for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.

This is equivalent to:

entry => {
    entry[0] = +entry[0];
    return entry;
}

As mentioned by @TravisClarke in the comments, the map function could be shortened to:

entry => [ +entry[0], entry[1] ]

However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.

Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.

  • Modifying each key-value pair in-place results in a negligible amount of memory growth, but requires typing a few more characters.
  • Creating a new array for each key-value pair results in doubling the amount of memory required, but requires typing a few less characters.

You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:

_x000D_
_x000D_
const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
_x000D_
const toNumericPairs = input => {_x000D_
  const entries = Object.entries(obj);_x000D_
  entries.forEach(entry => entry[0] = +entry[0]);_x000D_
  return entries;_x000D_
}_x000D_
_x000D_
console.log(toNumericPairs(obj));
_x000D_
_x000D_
_x000D_

How to run SQL in shell script

You can use a heredoc. e.g. from a prompt:

$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF

so sqlplus will consume everything up to the EOF marker as stdin.

What does the CSS rule "clear: both" do?

When you want one element placed at the bottom other element you use this code in CSS. It is used for floats.

If you float content you can float left or right... so in a common layout you might have a left nav, a content div and a footer.

To ensure the footer stays below both of these floats (if you have floated left and right) then you put the footer as clear: both.

This way it will stay below both floats.

(If you are only clearing left then you only really need to clear: left;.)

Go through this tutorial:

Spring RestTemplate timeout

Here are my 2 cents. Nothing new, but some explanations, improvements and newer code.

By default, RestTemplate has infinite timeout. There are two kinds of timeouts: connection timeout and read time out. For instance, I could connect to the server but I could not read data. The application was hanging and you have no clue what's going on.

I am going to use annotations, which these days are preferred over XML.

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {

        var factory = new SimpleClientHttpRequestFactory();

        factory.setConnectTimeout(3000);
        factory.setReadTimeout(3000);

        return new RestTemplate(factory);
    }
}

Here we use SimpleClientHttpRequestFactory to set the connection and read time outs. It is then passed to the constructor of RestTemplate.

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {

        return builder
                .setConnectTimeout(Duration.ofMillis(3000))
                .setReadTimeout(Duration.ofMillis(3000))
                .build();
    }
}

In the second solution, we use the RestTemplateBuilder. Also notice the parameters of the two methods: they take Duration. The overloaded methods that take directly milliseconds are now deprecated.

Edit Tested with Spring Boot 2.1.0 and Java 11.

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

How to ignore a particular directory or file for tslint?

In addition to Michael's answer, consider a second way: adding linterOptions.exclude to tslint.json

For example, you may have tslint.json with following lines:

{
  "linterOptions": {
    "exclude": [
      "someDirectory/*.d.ts"
    ]
  }
}

Create Test Class in IntelliJ

With the cursor on the class name declaration I do ALT + Return and my Intellij 14.1.4 offers me a popup with the option to 'Create Test'.

Jackson enum Serializing and DeSerializer

Here is another example that uses string values instead of a map.

public enum Operator {
    EQUAL(new String[]{"=","==","==="}),
    NOT_EQUAL(new String[]{"!=","<>"}),
    LESS_THAN(new String[]{"<"}),
    LESS_THAN_EQUAL(new String[]{"<="}),
    GREATER_THAN(new String[]{">"}),
    GREATER_THAN_EQUAL(new String[]{">="}),
    EXISTS(new String[]{"not null", "exists"}),
    NOT_EXISTS(new String[]{"is null", "not exists"}),
    MATCH(new String[]{"match"});

    private String[] value;

    Operator(String[] value) {
        this.value = value;
    }

    @JsonValue
    public String toStringOperator(){
        return value[0];
    }

    @JsonCreator
    public static Operator fromStringOperator(String stringOperator) {
        if(stringOperator != null) {
            for(Operator operator : Operator.values()) {
                for(String operatorString : operator.value) {
                    if (stringOperator.equalsIgnoreCase(operatorString)) {
                        return operator;
                    }
                }
            }
        }
        return null;
    }
}

Java JDBC connection status

Your best chance is to just perform a simple query against one table, e.g.:

select 1 from SOME_TABLE;

Oh, I just saw there is a new method available since 1.6:

java.sql.Connection.isValid(int timeoutSeconds):

Returns true if the connection has not been closed and is still valid. The driver shall submit a query on the connection or use some other mechanism that positively verifies the connection is still valid when this method is called. The query submitted by the driver to validate the connection shall be executed in the context of the current transaction.

How do you input command line arguments in IntelliJ IDEA?

On a MacBook Air with "OSX 10.11.3":

  1. ctrl + alt + r
  2. e
  3. Enter
  4. Program arguments: Write your command line parameters (space between each item if you have more than one argument)
  5. Enter

How to monitor network calls made from iOS Simulator

A good solution if you are used to the chrome inspector tools is Pony debugger: https://github.com/square/PonyDebugger

It is a bit of a pain to setup, but once you do it work well. Be sure to use Safari instead of Chrome to use it though.

What does an exclamation mark mean in the Swift language?

If you've come from a C-family language, you will be thinking "pointer to object of type X which might be the memory address 0 (NULL)", and if you're coming from a dynamically typed language you'll be thinking "Object which is probably of type X but might be of type undefined". Neither of these is actually correct, although in a roundabout way the first one is close.

The way you should be thinking of it is as if it's an object like:

struct Optional<T> {
   var isNil:Boolean
   var realObject:T
}

When you're testing your optional value with foo == nil it's really returning foo.isNil, and when you say foo! it's returning foo.realObject with an assertion that foo.isNil == false. It's important to note this because if foo actually is nil when you do foo!, that's a runtime error, so typically you'd want to use a conditional let instead unless you are very sure that the value will not be nil. This kind of trickery means that the language can be strongly typed without forcing you to test if values are nil everywhere.

In practice, it doesn't truly behave like that because the work is done by the compiler. At a high level there is a type Foo? which is separate to Foo, and that prevents funcs which accept type Foo from receiving a nil value, but at a low level an optional value isn't a true object because it has no properties or methods; it's likely that in fact it is a pointer which may by NULL(0) with the appropriate test when force-unwrapping.

There other situation in which you'd see an exclamation mark is on a type, as in:

func foo(bar: String!) {
    print(bar)
}

This is roughly equivalent to accepting an optional with a forced unwrap, i.e.:

func foo(bar: String?) {
    print(bar!)
}

You can use this to have a method which technically accepts an optional value but will have a runtime error if it is nil. In the current version of Swift this apparently bypasses the is-not-nil assertion so you'll have a low-level error instead. Generally not a good idea, but it can be useful when converting code from another language.

Passing multiple values to a single PowerShell script parameter

The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.

param([String[]] $Hosts, [String] $VLAN)

Instead of

foreach ($i in $args)

you can use

foreach ($hostName in $Hosts)

If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:

myScript.ps1 -Hosts host1,host2,host3 -VLAN 2

...or something similar.

Change DIV content using ajax, php and jQuery

jQuery.load()

$('#summary').load('ajax.php', function() {
  alert('Loaded.');
});

How to import keras from tf.keras in Tensorflow?

I had the same problem with Tensorflow 2.0.0 in PyCharm. PyCharm did not recognize tensorflow.keras; I updated my PyCharm and the problem was resolved!

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

How do ports work with IPv6?

The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.

Edit: Port 0 is a reserved port in TCP but it does exist. See RFC793

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:

  1. it exports just the hardcoded sheet named "Sheet1";
  2. it always exports to the same temp file, overwriting it;
  3. it ignores the locale separation char.

To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.

Option Explicit
Sub ExportAsCSV()
 
    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook
     
    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy
 
    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
      .PasteSpecial xlPasteValues
      .PasteSpecial xlPasteFormats
    End With        

    Dim Change below to "- 4"  to become compatible with .xls files
    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
     
    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

There are still some small thing with the code above that you should notice:

  1. .Close and DisplayAlerts=True should be in a finally clause, but I don't know how to do it in VBA
  2. It works just if the current filename has 4 letters, like .xlsm. Wouldn't work in .xls excel old files. For file extensions of 3 chars, you must change the - 5 to - 4 when setting MyFileName.
  3. As a collateral effect, your clipboard will be substituted with current sheet contents.

Edit: put Local:=True to save with my locale CSV delimiter.

google chrome extension :: console.log() from background page?

It's an old post, with already good answers, but I add my two bits. I don't like to use console.log, I'd rather use a logger that logs to the console, or wherever I want, so I have a module defining a log function a bit like this one

function log(...args) {
  console.log(...args);
  chrome.extension.getBackgroundPage().console.log(...args);
}

When I call log("this is my log") it will write the message both in the popup console and the background console.

The advantage is to be able to change the behaviour of the logs without having to change the code (like disabling logs for production, etc...)

How to embed images in html email

Here is a way to get a string variable without having to worry about the coding.

If you have Mozilla Thunderbird, you can use it to fetch the html image code for you.

I wrote a little tutorial here, complete with a screenshot (it's for powershell, but that doesn't matter for this):

powershell email with html picture showing red x

And again:

How to embed images in email

What does \u003C mean?

It is a unicode char \u003C = <

Laravel 4: how to run a raw SQL?

In the Laravel 4 manual - it talks about doing raw commands like this:

DB::select(DB::raw('RENAME TABLE photos TO images'));

edit: I just found this in the Laravel 4 documentation which is probably better:

DB::statement('drop table users');

Update: In Laravel 4.1 (maybe 4.0 - I'm not sure) - you can also do this for a raw Where query:

$users = User::whereRaw('age > ? and votes = 100', array(25))->get();

Further Update If you are specifically looking to do a table rename - there is a schema command for that - see Mike's answer below for that.

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

SwiftUI - How do I change the background color of a View?

Fill the entire screen

var body : some View{
    Color.green.edgesIgnoringSafeArea(.all)
}

enter image description here

enter image description here

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

Just rename the command or file name ln -s /usr/bin/nodejs /usr/bin/node by this command

An unhandled exception was generated during the execution of the current web request

You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.

Try to remove that tag:

<form id="formID" runat="server">

and of course closing tag:

</form>

Hashing a file in Python

I have programmed a module wich is able to hash big files with different algorithms.

pip3 install py_essentials

Use the module like this:

from py_essentials import hashing as hs
hash = hs.fileChecksum("path/to/the/file.txt", "sha256")

Laravel 5 call a model function in a blade view

want to use model in view as:

{{ Product::find($id) }}

you can use in view:

<?php
$tmp = \App\Product::find($id);
?>
{{ $tmp->name }}

Hope this will help you

How do I display images from Google Drive on a website?

I have found a way to do it without using external sites.

<img src="https://drive.google.com/uc?export=view&id=XXX">

https://gist.github.com/evansims/f23e2f49e3d4be793038

<a href="https://drive.google.com/uc?export=view&id=XXX">
    <img src="https://drive.google.com/uc?export=view&id=XXX"
    style="width: 500px; max-width: 100%; height: auto"
    title="Click for the larger version." />
</a>

You'll need to grab the ID of the image: Click on “Open in new window” and get the ID from the URL.

Click on “Open in new window”

$(document).on("click"... not working?

You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".

It's probably not working due to one of:

  • Not using recent version of jQuery
  • Not wrapping your code inside of DOM ready
  • or you are doing something which causes the event not to bubble up to the listener on the document.

To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.

For example:

$(document).ready(function() {
    // This WILL work because we are listening on the 'document', 
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });

    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });

    // Create the dynamic element '#test-element'
    $('body').append('<div id="test-element">Click mee</div>');
});

In this example, only the "bound to document" alert will fire.

JSFiddle with jQuery 1.9.1

How to remove newlines from beginning and end of a string?

Try this

function replaceNewLine(str) { 
  return str.replace(/[\n\r]/g, "");
}

How can I combine multiple nested Substitute functions in Excel?

  • nesting SUBSTITUTE() in a string can be nasty, however, it's always possible to arrange it:

Screenshot formula bar

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

sometimes when data grow bigger mysql WHERE IN's could be pretty slow because of query optimization. Try using STRAIGHT_JOIN to tell mysql to execute query as is, e.g.

SELECT STRAIGHT_JOIN table.field FROM table WHERE table.id IN (...)

but beware: in most cases mysql optimizer works pretty well, so I would recommend to use it only when you have this kind of problem

How can strings be concatenated?

The easiest way would be

Section = 'Sec_' + Section

But for efficiency, see: https://waymoot.org/home/python_string/

Check whether a path is valid in Python without creating a file at the path's target

tl;dr

Call the is_path_exists_or_creatable() function defined below.

Strictly Python 3. That's just how we roll.

A Tale of Two Questions

The question of "How do I test pathname validity and, for valid pathnames, the existence or writability of those paths?" is clearly two separate questions. Both are interesting, and neither have received a genuinely satisfactory answer here... or, well, anywhere that I could grep.

vikki's answer probably hews the closest, but has the remarkable disadvantages of:

  • Needlessly opening (...and then failing to reliably close) file handles.
  • Needlessly writing (...and then failing to reliable close or delete) 0-byte files.
  • Ignoring OS-specific errors differentiating between non-ignorable invalid pathnames and ignorable filesystem issues. Unsurprisingly, this is critical under Windows. (See below.)
  • Ignoring race conditions resulting from external processes concurrently (re)moving parent directories of the pathname to be tested. (See below.)
  • Ignoring connection timeouts resulting from this pathname residing on stale, slow, or otherwise temporarily inaccessible filesystems. This could expose public-facing services to potential DoS-driven attacks. (See below.)

We're gonna fix all that.

Question #0: What's Pathname Validity Again?

Before hurling our fragile meat suits into the python-riddled moshpits of pain, we should probably define what we mean by "pathname validity." What defines validity, exactly?

By "pathname validity," we mean the syntactic correctness of a pathname with respect to the root filesystem of the current system – regardless of whether that path or parent directories thereof physically exist. A pathname is syntactically correct under this definition if it complies with all syntactic requirements of the root filesystem.

By "root filesystem," we mean:

  • On POSIX-compatible systems, the filesystem mounted to the root directory (/).
  • On Windows, the filesystem mounted to %HOMEDRIVE%, the colon-suffixed drive letter containing the current Windows installation (typically but not necessarily C:).

The meaning of "syntactic correctness," in turn, depends on the type of root filesystem. For ext4 (and most but not all POSIX-compatible) filesystems, a pathname is syntactically correct if and only if that pathname:

  • Contains no null bytes (i.e., \x00 in Python). This is a hard requirement for all POSIX-compatible filesystems.
  • Contains no path components longer than 255 bytes (e.g., 'a'*256 in Python). A path component is a longest substring of a pathname containing no / character (e.g., bergtatt, ind, i, and fjeldkamrene in the pathname /bergtatt/ind/i/fjeldkamrene).

Syntactic correctness. Root filesystem. That's it.

Question #1: How Now Shall We Do Pathname Validity?

Validating pathnames in Python is surprisingly non-intuitive. I'm in firm agreement with Fake Name here: the official os.path package should provide an out-of-the-box solution for this. For unknown (and probably uncompelling) reasons, it doesn't. Fortunately, unrolling your own ad-hoc solution isn't that gut-wrenching...

O.K., it actually is. It's hairy; it's nasty; it probably chortles as it burbles and giggles as it glows. But what you gonna do? Nuthin'.

We'll soon descend into the radioactive abyss of low-level code. But first, let's talk high-level shop. The standard os.stat() and os.lstat() functions raise the following exceptions when passed invalid pathnames:

  • For pathnames residing in non-existing directories, instances of FileNotFoundError.
  • For pathnames residing in existing directories:
    • Under Windows, instances of WindowsError whose winerror attribute is 123 (i.e., ERROR_INVALID_NAME).
    • Under all other OSes:
    • For pathnames containing null bytes (i.e., '\x00'), instances of TypeError.
    • For pathnames containing path components longer than 255 bytes, instances of OSError whose errcode attribute is:
      • Under SunOS and the *BSD family of OSes, errno.ERANGE. (This appears to be an OS-level bug, otherwise referred to as "selective interpretation" of the POSIX standard.)
      • Under all other OSes, errno.ENAMETOOLONG.

Crucially, this implies that only pathnames residing in existing directories are validatable. The os.stat() and os.lstat() functions raise generic FileNotFoundError exceptions when passed pathnames residing in non-existing directories, regardless of whether those pathnames are invalid or not. Directory existence takes precedence over pathname invalidity.

Does this mean that pathnames residing in non-existing directories are not validatable? Yes – unless we modify those pathnames to reside in existing directories. Is that even safely feasible, however? Shouldn't modifying a pathname prevent us from validating the original pathname?

To answer this question, recall from above that syntactically correct pathnames on the ext4 filesystem contain no path components (A) containing null bytes or (B) over 255 bytes in length. Hence, an ext4 pathname is valid if and only if all path components in that pathname are valid. This is true of most real-world filesystems of interest.

Does that pedantic insight actually help us? Yes. It reduces the larger problem of validating the full pathname in one fell swoop to the smaller problem of only validating all path components in that pathname. Any arbitrary pathname is validatable (regardless of whether that pathname resides in an existing directory or not) in a cross-platform manner by following the following algorithm:

  1. Split that pathname into path components (e.g., the pathname /troldskog/faren/vild into the list ['', 'troldskog', 'faren', 'vild']).
  2. For each such component:
    1. Join the pathname of a directory guaranteed to exist with that component into a new temporary pathname (e.g., /troldskog) .
    2. Pass that pathname to os.stat() or os.lstat(). If that pathname and hence that component is invalid, this call is guaranteed to raise an exception exposing the type of invalidity rather than a generic FileNotFoundError exception. Why? Because that pathname resides in an existing directory. (Circular logic is circular.)

Is there a directory guaranteed to exist? Yes, but typically only one: the topmost directory of the root filesystem (as defined above).

Passing pathnames residing in any other directory (and hence not guaranteed to exist) to os.stat() or os.lstat() invites race conditions, even if that directory was previously tested to exist. Why? Because external processes cannot be prevented from concurrently removing that directory after that test has been performed but before that pathname is passed to os.stat() or os.lstat(). Unleash the dogs of mind-fellating insanity!

There exists a substantial side benefit to the above approach as well: security. (Isn't that nice?) Specifically:

Front-facing applications validating arbitrary pathnames from untrusted sources by simply passing such pathnames to os.stat() or os.lstat() are susceptible to Denial of Service (DoS) attacks and other black-hat shenanigans. Malicious users may attempt to repeatedly validate pathnames residing on filesystems known to be stale or otherwise slow (e.g., NFS Samba shares); in that case, blindly statting incoming pathnames is liable to either eventually fail with connection timeouts or consume more time and resources than your feeble capacity to withstand unemployment.

The above approach obviates this by only validating the path components of a pathname against the root directory of the root filesystem. (If even that's stale, slow, or inaccessible, you've got larger problems than pathname validation.)

Lost? Great. Let's begin. (Python 3 assumed. See "What Is Fragile Hope for 300, leycec?")

import errno, os

# Sadly, Python fails to provide the following magic number for us.
ERROR_INVALID_NAME = 123
'''
Windows-specific error code indicating an invalid pathname.

See Also
----------
https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
    Official listing of all such codes.
'''

def is_pathname_valid(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname for the current OS;
    `False` otherwise.
    '''
    # If this pathname is either not a string or is but is empty, this pathname
    # is invalid.
    try:
        if not isinstance(pathname, str) or not pathname:
            return False

        # Strip this pathname's Windows-specific drive specifier (e.g., `C:\`)
        # if any. Since Windows prohibits path components from containing `:`
        # characters, failing to strip this `:`-suffixed prefix would
        # erroneously invalidate all valid absolute Windows pathnames.
        _, pathname = os.path.splitdrive(pathname)

        # Directory guaranteed to exist. If the current OS is Windows, this is
        # the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
        # environment variable); else, the typical root directory.
        root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
            if sys.platform == 'win32' else os.path.sep
        assert os.path.isdir(root_dirname)   # ...Murphy and her ironclad Law

        # Append a path separator to this directory if needed.
        root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep

        # Test whether each path component split from this pathname is valid or
        # not, ignoring non-existent and non-readable path components.
        for pathname_part in pathname.split(os.path.sep):
            try:
                os.lstat(root_dirname + pathname_part)
            # If an OS-specific exception is raised, its error code
            # indicates whether this pathname is valid or not. Unless this
            # is the case, this exception implies an ignorable kernel or
            # filesystem complaint (e.g., path not found or inaccessible).
            #
            # Only the following exceptions indicate invalid pathnames:
            #
            # * Instances of the Windows-specific "WindowsError" class
            #   defining the "winerror" attribute whose value is
            #   "ERROR_INVALID_NAME". Under Windows, "winerror" is more
            #   fine-grained and hence useful than the generic "errno"
            #   attribute. When a too-long pathname is passed, for example,
            #   "errno" is "ENOENT" (i.e., no such file or directory) rather
            #   than "ENAMETOOLONG" (i.e., file name too long).
            # * Instances of the cross-platform "OSError" class defining the
            #   generic "errno" attribute whose value is either:
            #   * Under most POSIX-compatible OSes, "ENAMETOOLONG".
            #   * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE".
            except OSError as exc:
                if hasattr(exc, 'winerror'):
                    if exc.winerror == ERROR_INVALID_NAME:
                        return False
                elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
                    return False
    # If a "TypeError" exception was raised, it almost certainly has the
    # error message "embedded NUL character" indicating an invalid pathname.
    except TypeError as exc:
        return False
    # If no exception was raised, all path components and hence this
    # pathname itself are valid. (Praise be to the curmudgeonly python.)
    else:
        return True
    # If any other exception was raised, this is an unrelated fatal issue
    # (e.g., a bug). Permit this exception to unwind the call stack.
    #
    # Did we mention this should be shipped with Python already?

Done. Don't squint at that code. (It bites.)

Question #2: Possibly Invalid Pathname Existence or Creatability, Eh?

Testing the existence or creatability of possibly invalid pathnames is, given the above solution, mostly trivial. The little key here is to call the previously defined function before testing the passed path:

def is_path_creatable(pathname: str) -> bool:
    '''
    `True` if the current user has sufficient permissions to create the passed
    pathname; `False` otherwise.
    '''
    # Parent directory of the passed path. If empty, we substitute the current
    # working directory (CWD) instead.
    dirname = os.path.dirname(pathname) or os.getcwd()
    return os.access(dirname, os.W_OK)

def is_path_exists_or_creatable(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname for the current OS _and_
    either currently exists or is hypothetically creatable; `False` otherwise.

    This function is guaranteed to _never_ raise exceptions.
    '''
    try:
        # To prevent "os" module calls from raising undesirable exceptions on
        # invalid pathnames, is_pathname_valid() is explicitly called first.
        return is_pathname_valid(pathname) and (
            os.path.exists(pathname) or is_path_creatable(pathname))
    # Report failure on non-fatal filesystem complaints (e.g., connection
    # timeouts, permissions issues) implying this path to be inaccessible. All
    # other exceptions are unrelated fatal issues and should not be caught here.
    except OSError:
        return False

Done and done. Except not quite.

Question #3: Possibly Invalid Pathname Existence or Writability on Windows

There exists a caveat. Of course there does.

As the official os.access() documentation admits:

Note: I/O operations may fail even when os.access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.

To no one's surprise, Windows is the usual suspect here. Thanks to extensive use of Access Control Lists (ACL) on NTFS filesystems, the simplistic POSIX permission-bit model maps poorly to the underlying Windows reality. While this (arguably) isn't Python's fault, it might nonetheless be of concern for Windows-compatible applications.

If this is you, a more robust alternative is wanted. If the passed path does not exist, we instead attempt to create a temporary file guaranteed to be immediately deleted in the parent directory of that path – a more portable (if expensive) test of creatability:

import os, tempfile

def is_path_sibling_creatable(pathname: str) -> bool:
    '''
    `True` if the current user has sufficient permissions to create **siblings**
    (i.e., arbitrary files in the parent directory) of the passed pathname;
    `False` otherwise.
    '''
    # Parent directory of the passed path. If empty, we substitute the current
    # working directory (CWD) instead.
    dirname = os.path.dirname(pathname) or os.getcwd()

    try:
        # For safety, explicitly close and hence delete this temporary file
        # immediately after creating it in the passed path's parent directory.
        with tempfile.TemporaryFile(dir=dirname): pass
        return True
    # While the exact type of exception raised by the above function depends on
    # the current version of the Python interpreter, all such types subclass the
    # following exception superclass.
    except EnvironmentError:
        return False

def is_path_exists_or_creatable_portable(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname on the current OS _and_
    either currently exists or is hypothetically creatable in a cross-platform
    manner optimized for POSIX-unfriendly filesystems; `False` otherwise.

    This function is guaranteed to _never_ raise exceptions.
    '''
    try:
        # To prevent "os" module calls from raising undesirable exceptions on
        # invalid pathnames, is_pathname_valid() is explicitly called first.
        return is_pathname_valid(pathname) and (
            os.path.exists(pathname) or is_path_sibling_creatable(pathname))
    # Report failure on non-fatal filesystem complaints (e.g., connection
    # timeouts, permissions issues) implying this path to be inaccessible. All
    # other exceptions are unrelated fatal issues and should not be caught here.
    except OSError:
        return False

Note, however, that even this may not be enough.

Thanks to User Access Control (UAC), the ever-inimicable Windows Vista and all subsequent iterations thereof blatantly lie about permissions pertaining to system directories. When non-Administrator users attempt to create files in either the canonical C:\Windows or C:\Windows\system32 directories, UAC superficially permits the user to do so while actually isolating all created files into a "Virtual Store" in that user's profile. (Who could have possibly imagined that deceiving users would have harmful long-term consequences?)

This is crazy. This is Windows.

Prove It

Dare we? It's time to test-drive the above tests.

Since NULL is the only character prohibited in pathnames on UNIX-oriented filesystems, let's leverage that to demonstrate the cold, hard truth – ignoring non-ignorable Windows shenanigans, which frankly bore and anger me in equal measure:

>>> print('"foo.bar" valid? ' + str(is_pathname_valid('foo.bar')))
"foo.bar" valid? True
>>> print('Null byte valid? ' + str(is_pathname_valid('\x00')))
Null byte valid? False
>>> print('Long path valid? ' + str(is_pathname_valid('a' * 256)))
Long path valid? False
>>> print('"/dev" exists or creatable? ' + str(is_path_exists_or_creatable('/dev')))
"/dev" exists or creatable? True
>>> print('"/dev/foo.bar" exists or creatable? ' + str(is_path_exists_or_creatable('/dev/foo.bar')))
"/dev/foo.bar" exists or creatable? False
>>> print('Null byte exists or creatable? ' + str(is_path_exists_or_creatable('\x00')))
Null byte exists or creatable? False

Beyond sanity. Beyond pain. You will find Python portability concerns.

Convert double to BigDecimal and set BigDecimal Precision

It prints 47.48000 if you use another MathContext:

BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64);

Just pick the context you need.

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

It's really interesting case. Actually in your setup the following statement is true:

binary_crossentropy = len(class_id_index) * categorical_crossentropy

This means that up to a constant multiplication factor your losses are equivalent. The weird behaviour that you are observing during a training phase might be an example of a following phenomenon:

  1. At the beginning the most frequent class is dominating the loss - so network is learning to predict mostly this class for every example.
  2. After it learnt the most frequent pattern it starts discriminating among less frequent classes. But when you are using adam - the learning rate has a much smaller value than it had at the beginning of training (it's because of the nature of this optimizer). It makes training slower and prevents your network from e.g. leaving a poor local minimum less possible.

That's why this constant factor might help in case of binary_crossentropy. After many epochs - the learning rate value is greater than in categorical_crossentropy case. I usually restart training (and learning phase) a few times when I notice such behaviour or/and adjusting a class weights using the following pattern:

class_weight = 1 / class_frequency

This makes loss from a less frequent classes balancing the influence of a dominant class loss at the beginning of a training and in a further part of an optimization process.

EDIT:

Actually - I checked that even though in case of maths:

binary_crossentropy = len(class_id_index) * categorical_crossentropy

should hold - in case of keras it's not true, because keras is automatically normalizing all outputs to sum up to 1. This is the actual reason behind this weird behaviour as in case of multiclassification such normalization harms a training.

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

How to delete an element from an array in C#

Balabaster's answer is correct if you want to remove all instances of the element. If you want to remove only the first one, you would do something like this:

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int firstFoundIndex = Array.IndexOf(numbers, numToRemove);
if (numbers >= 0)
{
    numbers = numbers.Take(firstFoundIndex).Concat(numbers.Skip(firstFoundIndex + 1)).ToArray();
}

Get data from fs.readFile

sync and async file reading way:

//fs module to read file in sync and async way

var fs = require('fs'),
    filePath = './sample_files/sample_css.css';

// this for async way
/*fs.readFile(filePath, 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);
});*/

//this is sync way
var css = fs.readFileSync(filePath, 'utf8');
console.log(css);

Node Cheat Available at read_file.

What is the recommended way to make a numeric TextField in JavaFX?

In recent updates of JavaFX, you have to set new text in Platform.runLater method just like this:

    private void set_normal_number(TextField textField, String oldValue, String newValue) {
    try {
        int p = textField.getCaretPosition();
        if (!newValue.matches("\\d*")) {
            Platform.runLater(() -> {
                textField.setText(newValue.replaceAll("[^\\d]", ""));
                textField.positionCaret(p);
            });
        }
    } catch (Exception e) {
    }
}

It's a good idea to set caret position too.

Rebase array keys after unsetting elements

Late answer but, after PHP 5.3 could be so;

$array = array(1, 2, 3, 4, 5);
$array = array_values(array_filter($array, function($v) {
    return !($v == 1 || $v == 2);
}));
print_r($array);

How to Access Hive via Python?

The examples above are a bit out of date. One new example is here:

import pyhs2 as hive
import getpass
DEFAULT_DB = 'default'
DEFAULT_SERVER = '10.37.40.1'
DEFAULT_PORT = 10000
DEFAULT_DOMAIN = 'PAM01-PRD01.IBM.COM'

u = raw_input('Enter PAM username: ')
s = getpass.getpass()
connection = hive.connect(host=DEFAULT_SERVER, port= DEFAULT_PORT, authMechanism='LDAP', user=u + '@' + DEFAULT_DOMAIN, password=s)
statement = "select * from user_yuti.Temp_CredCard where pir_post_dt = '2014-05-01' limit 100"
cur = connection.cursor()

cur.execute(statement)
df = cur.fetchall() 

In addition to the standard python program, a few libraries need to be installed to allow Python to build the connection to the Hadoop databae.

1.Pyhs2, Python Hive Server 2 Client Driver

2.Sasl, Cyrus-SASL bindings for Python

3.Thrift, Python bindings for the Apache Thrift RPC system

4.PyHive, Python interface to Hive

Remember to change the permission of the executable

chmod +x test_hive2.py ./test_hive2.py

Wish it helps you. Reference: https://sites.google.com/site/tingyusz/home/blogs/hiveinpython

When should I use a trailing slash in my URL?

Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.

Python "expected an indented block"

The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

src: ##

##https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator

How to capture a list of specific type with mockito

For an earlier version of junit, you can do

Class<Map<String, String>> mapClass = (Class) Map.class;
ArgumentCaptor<Map<String, String>> mapCaptor = ArgumentCaptor.forClass(mapClass);

Efficient evaluation of a function at every cell of a NumPy array

I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.

One can write his own customised ufunc in C, which surely is more efficient, or by invoking np.frompyfunc, which is built-in factory method. After testing, this is more efficient than np.vectorize:

f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)

%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms

I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post

Conversion failed when converting date and/or time from character string while inserting datetime

Whenever possible one should avoid culture specific date/time literals.

There are some secure formats to provide a date/time as literal:

All examples for 2016-09-15 17:30:00

ODBC (my favourite, as it is handled as the real type immediately)

  • {ts'2016-09-15 17:30:00'} --Time Stamp
  • {d'2016-09-15'} --Date only
  • {t'17:30:00'} --Time only

ISO8601 (the best for everywhere)

  • '2016-09-15T17:30:00' --be aware of the T in the middle!

Unseperated (tiny risk to get misinterpreted as number)

  • '20160915' --only for pure date

Good to keep in mind: Invalid dates tend to show up with strange errors

  • There is no 31st of June or 30th of February...

One more reason for strange conversion errors: Order of execution!

SQL-Server is well know to do things in an order of execution one might not have expected. Your written statement looks like the conversion is done before some type related action takes place, but the engine decides - why ever - to do the conversion in a later step.

Here is a great article explaining this with examples: Rusano.com: "t-sql-functions-do-no-imply-a-certain-order-of-execution" and here is the related question.

How to Disable GUI Button in Java

You create the frame with button enable, do some test to see if btn1Cliked is true, and that's all.

Then you have the actionPerformed method that does nothing with your button. So, if you don't have any action related, your button status will never be evaluated again.

How to convert an int to a hex string?

If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.

struct.pack('B', 65)

(And yes, 65 is \x41, not \x65.)

The struct class will also conveniently handle endianness for communication or other uses.

server error:405 - HTTP verb used to access this page is not allowed

It means litraly that, your trying to use the wrong http verb when accessing some http content. A lot of content on webservices you need to use a POST to consume. I suspect your trying to access the facebook API using the wrong http verb.

In Maven how to exclude resources from the generated jar?

Do you mean to property files located in src/main/resources? Then you should exclude them using the maven-resource-plugin. See the following page for details:

http://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html

How to install SimpleJson Package for Python

If you have Python 2.6 installed then you already have simplejson - just import json; it's the same thing.

Laravel Eloquent LEFT JOIN WHERE NULL

You can also specify the columns in a select like so:

$c = Customer::select('*', DB::raw('customers.id AS id, customers.first_name AS first_name, customers.last_name AS last_name'))
->leftJoin('orders', function($join) {
  $join->on('customers.id', '=', 'orders.customer_id') 
})->whereNull('orders.customer_id')->first();

Reflection - get attribute name and value on property

Necromancing.
For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:

public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t)
{
    object[] objs = mi.GetCustomAttributes(t, true);

    if (objs == null || objs.Length < 1)
        return null;

    return objs[0];
}



public static T GetAttribute<T>(System.Reflection.MemberInfo mi)
{
    return (T)GetAttribute(mi, typeof(T));
}


public delegate TResult GetValue_t<in T, out TResult>(T arg1);

public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute
{
    TAttribute[] objAtts = (TAttribute[])mi.GetCustomAttributes(typeof(TAttribute), true);
    TAttribute att = (objAtts == null || objAtts.Length < 1) ? default(TAttribute) : objAtts[0];
    // TAttribute att = (TAttribute)GetAttribute(mi, typeof(TAttribute));

    if (att != null)
    {
        return value(att);
    }
    return default(TValue);
}

Example usage:

System.Reflection.FieldInfo fi = t.GetField("PrintBackground");
wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi);
string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a){ return a.Name;});

or simply

string aname = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, a => a.Name );

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

Exim 4 requires that AUTH command only be sent after the client issued EHLO - attempts to authenticate without EHLO would be rejected. Some mailservers require that EHLO be issued twice. PHPMailer apparently fails to do so. If PHPMailer does not allow you to force EHLO initiation, you really should switch to SwiftMailer 4.

How do I use Notepad++ (or other) with msysgit?

This works for me

git config --global core.editor C:/Progra~1/Notepad++/notepad++.exe

Multiple actions were found that match the request in Web Api

I've stumbled upon this problem while trying to augment my WebAPI controllers with extra actions.

Assume you would have

public IEnumerable<string> Get()
{
    return this.Repository.GetAll();
}

[HttpGet]
public void ReSeed()
{
    // Your custom action here
}

There are now two methods that satisfy the request for /api/controller which triggers the problem described by TS.

I didn't want to add "dummy" parameters to my additional actions so I looked into default actions and came up with:

[ActionName("builtin")]
public IEnumerable<string> Get()
{
    return this.Repository.GetAll();
}

for the first method in combination with the "dual" route binding:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { action = "builtin", id = RouteParameter.Optional },
    constraints: new { id = @"\d+" });

config.Routes.MapHttpRoute(
    name: "CustomActionApi",
    routeTemplate: "api/{controller}/{action}");

Note that even though there is no "action" parameter in the first route template apparently you can still configure a default action allowing us to separate the routing of the "normal" WebAPI calls and the calls to the extra action.

Are strongly-typed functions as parameters possible in TypeScript?

I realize this post is old, but there's a more compact approach that is slightly different than what was asked, but may be a very helpful alternative. You can essentially declare the function in-line when calling the method (Foo's save() in this case). It would look something like this:

class Foo {
    save(callback: (n: number) => any) : void {
        callback(42)
    }

    multipleCallbacks(firstCallback: (s: string) => void, secondCallback: (b: boolean) => boolean): void {
        firstCallback("hello world")

        let result: boolean = secondCallback(true)
        console.log("Resulting boolean: " + result)
    }
}

var foo = new Foo()

// Single callback example.
// Just like with @RyanCavanaugh's approach, ensure the parameter(s) and return
// types match the declared types above in the `save()` method definition.
foo.save((newNumber: number) => {
    console.log("Some number: " + newNumber)

    // This is optional, since "any" is the declared return type.
    return newNumber
})

// Multiple callbacks example.
// Each call is on a separate line for clarity.
// Note that `firstCallback()` has a void return type, while the second is boolean.
foo.multipleCallbacks(
    (s: string) => {
         console.log("Some string: " + s)
    },
    (b: boolean) => {
        console.log("Some boolean: " + b)
        let result = b && false

        return result
    }
)

The multipleCallback() approach is very useful for things like network calls that may succeed or fail. Again assuming a network call example, when multipleCallbacks() is called, behavior for both a success and failure can be defined in one spot, which lends itself to greater clarity for future code readers.

Generally, in my experience, this approach lends itself to being more concise, less clutter, and greater clarity overall.

Good luck all!

Deploying just HTML, CSS webpage to Tomcat

If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:

zip -r <AppName>.war *

I've tested it with Tomcat 8 on the Mac, but it should work anywhere

Printing newlines with print() in R

You can do this:

cat("File not supplied.\nUsage: ./program F=filename\n")

Notice that cat has a return value of NULL.

Convert `List<string>` to comma-separated string

To expand on Jon Skeets answer the code for this in .Net 4 is:

string myCommaSeperatedString = string.Join(",",ls);

Total memory used by Python process?

Even easier to use than /proc/self/status: /proc/self/statm. It's just a space delimited list of several statistics. I haven't been able to tell if both files are always present.

/proc/[pid]/statm

Provides information about memory usage, measured in pages. The columns are:

  • size (1) total program size (same as VmSize in /proc/[pid]/status)
  • resident (2) resident set size (same as VmRSS in /proc/[pid]/status)
  • shared (3) number of resident shared pages (i.e., backed by a file) (same as RssFile+RssShmem in /proc/[pid]/status)
  • text (4) text (code)
  • lib (5) library (unused since Linux 2.6; always 0)
  • data (6) data + stack
  • dt (7) dirty pages (unused since Linux 2.6; always 0)

Here's a simple example:

from pathlib import Path
from resource import getpagesize

PAGESIZE = getpagesize()
PATH = Path('/proc/self/statm')


def get_resident_set_size() -> int:
    """Return the current resident set size in bytes."""
    # statm columns are: size resident shared text lib data dt
    statm = PATH.read_text()
    fields = statm.split()
    return int(fields[1]) * PAGESIZE


data = []
start_memory = get_resident_set_size()
for _ in range(10):
    data.append('X' * 100000)
    print(get_resident_set_size() - start_memory)

That produces a list that looks something like this:

0
0
368640
368640
368640
638976
638976
909312
909312
909312

You can see that it jumps by about 300,000 bytes after roughly 3 allocations of 100,000 bytes.

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

I've struggled a lot with this error. Tried every single answer I found on the internet.

In the end, I've connected my computer to my cell phone's hotspot and everything worked. I turned out that my company's internet was blocking the connection with MySQL.

This is not a complete solution, but maybe someone faces the same problem. It worths to check the connection.

How to get the hostname of the docker host from inside a docker container on that host without env vars

I think the reason that I have the same issue is a bug in the latest Docker for Mac beta, but buried in the comments there I was able to find a solution that worked for me & my team. We're using this for local development, where we need our containerized services to talk to a monolith as we work to replace it. This is probably not a production-viable solution.

On the host machine, alias a known available IP address to the loopback interface:

$ sudo ifconfig lo0 alias 10.200.10.1/24

Then add that IP with a hostname to your docker config. In my case, I'm using docker-compose, so I added this to my docker-compose.yml:

extra_hosts:
# configure your host to alias 10.200.10.1 to the loopback interface:
#       sudo ifconfig lo0 alias 10.200.10.1/24
- "relevant_hostname:10.200.10.1"

I then verified that the desired host service (a web server) was available from inside the container by attaching to a bash session, and using wget to request a page from the host's web server:

$ docker exec -it container_name /bin/bash
$ wget relevant_hostname/index.html
$ cat index.html

Maven: Non-resolvable parent POM

I had similar problem at my work.

Building the parent project without dependency created parent_project.pom file in the .m2 folder.

Then add the child module in the parent POM and run Maven build.

<modules>
    <module>module1</module>
    <module>module2</module>
    <module>module3</module>
    <module>module4</module>
</modules>

Running command line silently with VbScript and getting output?

Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.

Selecting with complex criteria from pandas.DataFrame

Another solution is to use the query method:

import pandas as pd

from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
                   'B': [randint(1, 9) * 10 for x in xrange(10)],
                   'C': [randint(1, 9) * 100 for x in xrange(10)]})
print df

   A   B    C
0  7  20  300
1  7  80  700
2  4  90  100
3  4  30  900
4  7  80  200
5  7  60  800
6  3  80  900
7  9  40  100
8  6  40  100
9  3  10  600

print df.query('B > 50 and C != 900')

   A   B    C
1  7  80  700
2  4  90  100
4  7  80  200
5  7  60  800

Now if you want to change the returned values in column A you can save their index:

my_query_index = df.query('B > 50 & C != 900').index

....and use .iloc to change them i.e:

df.iloc[my_query_index, 0] = 5000

print df

      A   B    C
0     7  20  300
1  5000  80  700
2  5000  90  100
3     4  30  900
4  5000  80  200
5  5000  60  800
6     3  80  900
7     9  40  100
8     6  40  100
9     3  10  600

Is there a CSS selector for the first direct child only?

CSS is called Cascading Style Sheets because the rules are inherited. Using the following selector, will select just the direct child of the parent, but its rules will be inherited by that div's children divs:

div.section > div { color: red }

Now, both that div and its children will be red. You need to cancel out whatever you set on the parent if you don't want it to inherit:

div.section > div { color: red }
div.section > div div { color: black }

Now only that single div that is a direct child of div.section will be red, but its children divs will still be black.

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

Bottom Line

Your code has retrieved data (entities) via entity-framework with lazy-loading enabled and after the DbContext has been disposed, your code is referencing properties (related/relationship/navigation entities) that was not explicitly requested.

More Specifically

The InvalidOperationException with this message always means the same thing: you are requesting data (entities) from entity-framework after the DbContext has been disposed.

A simple case:

(these classes will be used for all examples in this answer, and assume all navigation properties have been configured correctly and have associated tables in the database)

public class Person
{
  public int Id { get; set; }
  public string name { get; set; }
  public int? PetId { get; set; }
  public Pet Pet { get; set; }
}

public class Pet 
{
  public string name { get; set; }
}

using (var db = new dbContext())
{
  var person = db.Persons.FirstOrDefaultAsync(p => p.id == 1);
}

Console.WriteLine(person.Pet.Name);

The last line will throw the InvalidOperationException because the dbContext has not disabled lazy-loading and the code is accessing the Pet navigation property after the Context has been disposed by the using statement.

Debugging

How do you find the source of this exception? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.

If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every location that requests data, and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether your navigation property should have been populated or if the data requested is necessary.

Ways to Avoid

Disable Lazy-Loading

public class MyDbContext : DbContext
{
  public MyDbContext()
  {
    this.Configuration.LazyLoadingEnabled = false;
  }
}

Pros: Instead of throwing the InvalidOperationException the property will be null. Accessing properties of null or attempting to change the properties of this property will throw a NullReferenceException.

How to explicitly request the object when needed:

using (var db = new dbContext())
{
  var person = db.Persons
    .Include(p => p.Pet)
    .FirstOrDefaultAsync(p => p.id == 1);
}
Console.WriteLine(person.Pet.Name);  // No Exception Thrown

In the previous example, Entity Framework will materialize the Pet in addition to the Person. This can be advantageous because it’s a single call the the database. (However, there can also be huge performance problems depending on the number of returned results and the number of navigation properties requested, in this instance, there would be no performance penalty because both instances are only a single record and a single join).

or

using (var db = new dbContext())
{
  var person = db.Persons.FirstOrDefaultAsync(p => p.id == 1);

  var pet = db.Pets.FirstOrDefaultAsync(p => p.id == person.PetId);
}
Console.WriteLine(person.Pet.Name);  // No Exception Thrown

In the previous example, Entity Framework will materialize the Pet independently of the Person by making an additional call to the database. By default, Entity Framework tracks objects it has retrieved from the database and if it finds navigation properties that match it will auto-magically populate these entities. In this instance because the PetId on the Person object matches the Pet.Id, Entity Framework will assign the Person.Pet to the Pet value retrieved, before the value is assigned to the pet variable.

I always recommend this approach as it forces programmers to understand when and how code is request data via Entity Framework. When code throws a null reference exception on a property of an entity, you can almost always be sure you have not explicitly requested that data.

Terminating a script in PowerShell

I realize this is an old post but I find myself coming back to this thread a lot as it is one of the top search results when searching for this topic. However, I always leave more confused then when I came due to the conflicting information. Ultimately I always have to perform my own tests to figure it out. So this time I will post my findings.

TL;DR Most people will want to use Exit to terminate a running scripts. However, if your script is merely declaring functions to later be used in a shell, then you will want to use Return in the definitions of said functions.

Exit vs Return vs Break

  • Exit: This will "exit" the currently running context. If you call this command from a script it will exit the script. If you call this command from the shell it will exit the shell.

    If a function calls the Exit command it will exit what ever context it is running in. So if that function is only called from within a running script it will exit that script. However, if your script merely declares the function so that it can be used from the current shell and you run that function from the shell, it will exit the shell because the shell is the context in which the function contianing the Exit command is running.

    Note: By default if you right click on a script to run it in PowerShell, once the script is done running, PowerShell will close automatically. This has nothing to do with the Exit command or anything else in your script. It is just a default PowerShell behavior for scripts being ran using this specific method of running a script. The same is true for batch files and the Command Line window.

  • Return: This will return to the previous call point. If you call this command from a script (outside any functions) it will return to the shell. If you call this command from the shell it will return to the shell (which is the previous call point for a single command ran from the shell). If you call this command from a function it will return to where ever the function was called from.

    Execution of any commands after the call point that it is returned to will continue from that point. If a script is called from the shell and it contains the Return command outside any functions then when it returns to the shell there are no more commands to run thus making a Return used in this way essentially the same as Exit.

  • Break: This will break out of loops and switch cases. If you call this command while not in a loop or switch case it will break out of the script. If you call Break inside a loop that is nested inside a loop it will only break out of the loop it was called in.

    There is also an interesting feature of Break where you can prefix a loop with a label and then you can break out of that labeled loop even if the Break command is called within several nested groups within that labeled loop.

    While ($true) {
        # Code here will run
    
        :myLabel While ($true) {
            # Code here will run
    
            While ($true) {
                # Code here will run
    
                While ($true) {
                    # Code here will run
                    Break myLabel
                    # Code here will not run
                }
    
                # Code here will not run
            }
    
            # Code here will not run
        }
    
        # Code here will run
    }
    

How does the JPA @SequenceGenerator annotation work

I have MySQL schema with autogen values. I use strategy=GenerationType.IDENTITY tag and seems to work fine in MySQL I guess it should work most db engines as well.

CREATE TABLE user (
    id bigint NOT NULL auto_increment,
    name varchar(64) NOT NULL default '',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

User.java:

// mark this JavaBean to be JPA scoped class
@Entity
@Table(name="user")
public class User {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;    // primary key (autogen surrogate)

    @Column(name="name")
    private String name;

    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

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

Exposing the current state name with ui router

Its just because of the load time angular takes to give you the current state.

If you try to get the current state by using $timeout function then it will give you correct result in $state.current.name

$timeout(function(){
    $rootScope.currState = $state.current.name;
})

How can I break from a try/catch block without throwing an exception in Java

There are several ways to do it:

  1. Move the code into a new method and return from it

  2. Wrap the try/catch in a do{}while(false); loop.

How to show multiline text in a table cell

I use the html code tag after each line (see below) and it works for me.

George Benson </br> 123 Main Street </br> New York, Ny 12344 </br>

Alternative for <blink>

Please try this one and I guarantee that it will work

  <script type="text/javascript">
  function blink() {
  var blinks = document.getElementsByTagName('blink');
  for (var i = blinks.length - 1; i >= 0; i--) {
  var s = blinks[i];
  s.style.visibility = (s.style.visibility === 'visible') ? 'hidden' : 'visible';
}
window.setTimeout(blink, 1000);
}
if (document.addEventListener) document.addEventListener("DOMContentLoaded", blink, false);
else if (window.addEventListener) window.addEventListener("load", blink, false);
else if (window.attachEvent) window.attachEvent("onload", blink);
else window.onload = blink;

Then put this below:

<blink><center> Your text here </blink></div>

How to specify new GCC path for CMake

Export should be specific about which version of GCC/G++ to use, because if user had multiple compiler version, it would not compile successfully.

 export CC=path_of_gcc/gcc-version
 export CXX=path_of_g++/g++-version
 cmake  path_of_project_contain_CMakeList.txt
 make 

In case project use C++11 this can be handled by using -std=C++-11 flag in CMakeList.txt

Call Python function from MATLAB

A little known (and little documented) fact about MATLAB's system() function: On unixoid systems it uses whatever interpreter is given in the environment variable SHELL or MATLAB_SHELL at the time of starting MATLAB. So if you start MATLAB with

SHELL='/usr/bin/python' matlab

any subsequent system() calls will use Python instead of your default shell as an interpreter.

How to change TextField's height and width?

To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

It looks like a common gaps-and-islands problem. The difference between two sequences of row numbers rn1 and rn2 give the "group" number.

Run this query CTE-by-CTE and examine intermediate results to see how it works.

Sample data

I expanded sample data from the question a little.

DECLARE @Source TABLE
(
    EmployeeID int,
    DateStarted date,
    DepartmentID int
)

INSERT INTO @Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001),

(10005,'2013-05-01',001),
(10005,'2013-11-09',001),
(10005,'2013-12-01',002),
(10005,'2014-10-01',001),
(10005,'2016-12-01',001);

Query for SQL Server 2008

There is no LEAD function in SQL Server 2008, so I had to use self-join via OUTER APPLY to get the value of the "next" row for the DateEnd.

WITH
CTE
AS
(
    SELECT
        EmployeeID
        ,DateStarted
        ,DepartmentID
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
    FROM @Source
)
,CTE_Groups
AS
(
    SELECT
        EmployeeID
        ,MIN(DateStarted) AS DateStart
        ,DepartmentID
    FROM CTE
    GROUP BY
        EmployeeID
        ,DepartmentID
        ,rn1 - rn2
)
SELECT
    CTE_Groups.EmployeeID
    ,CTE_Groups.DepartmentID
    ,CTE_Groups.DateStart
    ,A.DateEnd
FROM
    CTE_Groups
    OUTER APPLY
    (
        SELECT TOP(1) G2.DateStart AS DateEnd
        FROM CTE_Groups AS G2
        WHERE
            G2.EmployeeID = CTE_Groups.EmployeeID
            AND G2.DateStart > CTE_Groups.DateStart
        ORDER BY G2.DateStart
    ) AS A
ORDER BY
    EmployeeID
    ,DateStart
;

Query for SQL Server 2012+

Starting with SQL Server 2012 there is a LEAD function that makes this task more efficient.

WITH
CTE
AS
(
    SELECT
        EmployeeID
        ,DateStarted
        ,DepartmentID
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
    FROM @Source
)
,CTE_Groups
AS
(
    SELECT
        EmployeeID
        ,MIN(DateStarted) AS DateStart
        ,DepartmentID
    FROM CTE
    GROUP BY
        EmployeeID
        ,DepartmentID
        ,rn1 - rn2
)
SELECT
    CTE_Groups.EmployeeID
    ,CTE_Groups.DepartmentID
    ,CTE_Groups.DateStart
    ,LEAD(CTE_Groups.DateStart) OVER (PARTITION BY CTE_Groups.EmployeeID ORDER BY CTE_Groups.DateStart) AS DateEnd
FROM
    CTE_Groups
ORDER BY
    EmployeeID
    ,DateStart
;

Result

+------------+--------------+------------+------------+
| EmployeeID | DepartmentID | DateStart  |  DateEnd   |
+------------+--------------+------------+------------+
|      10001 |            1 | 2013-01-01 | 2013-12-01 |
|      10001 |            2 | 2013-12-01 | 2014-10-01 |
|      10001 |            1 | 2014-10-01 | NULL       |
|      10005 |            1 | 2013-05-01 | 2013-12-01 |
|      10005 |            2 | 2013-12-01 | 2014-10-01 |
|      10005 |            1 | 2014-10-01 | NULL       |
+------------+--------------+------------+------------+

Razor View Without Layout

If you are working with apps, try cleaning solution. Fixed for me.

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Short answer

datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")

Long answer

The reason that the "Z" is not included is because datetime.now() and even datetime.utcnow() return timezone naive datetimes, that is to say datetimes with no timezone information associated. To get a timezone aware datetime, you need to pass a timezone as an argument to datetime now. For example:

from datetime import datetime, timezone

datetime.utcnow()
#> datetime.datetime(2020, 9, 3, 20, 58, 49, 22253)
# This is timezone naive

datetime.now(timezone.utc)
#> datetime.datetime(2020, 9, 3, 20, 58, 49, 22253, tzinfo=datetime.timezone.utc)
# This is timezone aware

Once you have a timezone aware timestamp, isoformat will include a timezone designation. Thus, you can then get an ISO 8601 timestamp via:

datetime.now(timezone.utc).isoformat()
#> '2020-09-03T20:53:07.337670+00:00'

"+00:00" is a valid ISO 8601 timezone designation for UTC. If you want to have "Z" instead of "+00:00", you have to do the replacement yourself:

datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
#> '2020-09-03T20:53:07.337670Z'

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

For me it was just a matter of changing the path variable to: 'C:\Program Files\Mozilla Firefox' instead of 'C:\Program Files (x86)\Mozilla Firefox'

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

how to add button click event in android studio

package com.mani.smsdetect;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

    //Declaration Button
    Button btnClickMe;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Intialization Button

        btnClickMe = (Button) findViewById(R.id.btnClickMe);

        btnClickMe.setOnClickListener(MainActivity.this);
        //Here MainActivity.this is a Current Class Reference (context)
    }

    @Override
    public void onClick(View v) {

        //Your Logic
    }
}

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

how do you increase the height of an html textbox

If you want multiple lines consider this:

<textarea rows="2"></textarea>

Specify rows as needed.

Double Iteration in List Comprehension

Gee, I guess I found the anwser: I was not taking care enough about which loop is inner and which is outer. The list comprehension should be like:

[x for b in a for x in b]

to get the desired result, and yes, one current value can be the iterator for the next loop.

Fixing a systemd service 203/EXEC failure (no such file or directory)

To simplify, make sure to add a hash bang to the top of your ExecStart script, i.e.

#!/bin/bash

python -u alwayson.py    

How do I count a JavaScript object's attributes?

Use underscore library, very useful: _.keys(obj).length.

How to access random item in list?

Printing randomly country name from JSON file.
Model:

public class Country
    {
        public string Name { get; set; }
        public string Code { get; set; }
    }

Implementaton:

string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\")) + @"Data\Country.json";
            string _countryJson = File.ReadAllText(filePath);
            var _country = JsonConvert.DeserializeObject<List<Country>>(_countryJson);


            int index = random.Next(_country.Count);
            Console.WriteLine(_country[index].Name);

Use grep to report back only line numbers

If you're open to using AWK:

awk '/textstring/ {print FNR}' textfile

In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.

Default value in Doctrine

The workaround I used was a LifeCycleCallback. Still waiting to see if there is any more "native" method, for instance @Column(type="string", default="hello default value").

/**
 * @Entity @Table(name="posts") @HasLifeCycleCallbacks
 */
class Post implements Node, \Zend_Acl_Resource_Interface {

...

/**
 * @PrePersist
 */
function onPrePersist() {
    // set default date
    $this->dtPosted = date('Y-m-d H:m:s');
}

Finding CN of users in Active Directory

CN refers to class name, so put in your LDAP query CN=Users. Should work.

jQuery - select the associated label element of a input field

As long and your input and label elements are associated by their id and for attributes, you should be able to do something like this:

$('.input').each(function() { 
   $this = $(this);
   $label = $('label[for="'+ $this.attr('id') +'"]');
   if ($label.length > 0 ) {
       //this input has a label associated with it, lets do something!
   }
});

If for is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.

What is the reason for the error message "System cannot find the path specified"?

The following worked for me:

  1. Open the Registry Editor (press windows key, type regedit and hit Enter) .
  2. Navigate to HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun and clear the values.
  3. Also check HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun.

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

Python Database connection Close

You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.

import pyodbc

class MS_DB():
    """ Collection of helper methods to query the MS SQL Server database.
    """

    def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
        self.username = username
        self._password = password
        self.host = host
        self.port = str(port)
        self.db = initial_db
        conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
                    self.host + ';PORT='+ self.port +';DATABASE='+ \
                    self.db +';UID='+ self.username +';PWD='+ \ 
                    self._password +';'
        print('Connected to DB:', conn_str)
        self._connection = pyodbc.connect(conn_str)        
        pyodbc.pooling = False

    def __repr__(self):
        return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"

    def __str__(self):
        return f"MS-SQLServer Module for STP on {self.host}"

    def __del__(self):
        self._connection.close()
        print("Connection closed.")

    @contextmanager
    def cursor(self, commit: bool = False):
        """
        A context manager style of using a DB cursor for database operations. 
        This function should be used for any database queries or operations that 
        need to be done. 

        :param commit:
        A boolean value that says whether to commit any database changes to the database. Defaults to False.
        :type commit: bool
        """
        cursor = self._connection.cursor()
        try:
            yield cursor
        except pyodbc.DatabaseError as err:
            print("DatabaseError {} ".format(err))
            cursor.rollback()
            raise err
        else:
            if commit:
                cursor.commit()
        finally:
            cursor.close()

ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
        cursor.execute("SELECT @@version;")
        print(cur.fetchall())

HTML5 Number Input - Always show 2 decimal places

My preferred approach, which uses data attributes to hold the state of the number:

<input type='number' step='0.01'/>

// react to stepping in UI
el.addEventListener('onchange', ev => ev.target.dataset.val = ev.target.value * 100)

// react to keys
el.addEventListener('onkeyup', ev => {

    // user cleared field
    if (!ev.target.value) ev.target.dataset.val = ''

    // non num input
    if (isNaN(ev.key)) {

        // deleting
        if (ev.keyCode == 8)

            ev.target.dataset.val = ev.target.dataset.val.slice(0, -1)

    // num input
    } else ev.target.dataset.val += ev.key

    ev.target.value = parseFloat(ev.target.dataset.val) / 100

})

How can I use jQuery to move a div across the screen

You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.

Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.

To read up on this, check out this thread (from my very first Stackoverflow post no less)!

Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

How do I include a newline character in a string in Delphi?

Here's an even shorter approach:

my_string := 'Hello,'#13#10' world!';

Check if an array contains any element of another array in JavaScript

Just one more solution

var a1 = [1, 2, 3, 4, 5]
var a2 = [2, 4]

Check if a1 contain all element of a2

var result = a1.filter(e => a2.indexOf(e) !== -1).length === a2.length
console.log(result)

How to draw rounded rectangle in Android UI?

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="4dp" />
</shape>

Execute a large SQL script (with GO commands)

For anyone still having the problem. You could use official Microsoft SMO

https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/overview-smo?view=sql-server-2017

using (var connection = new SqlConnection(connectionString))
{
  var server = new Server(new ServerConnection(connection));
  server.ConnectionContext.ExecuteNonQuery(sql);
}

How to style SVG with external CSS?

  1. For External styles

_x000D_
_x000D_
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">_x000D_
_x000D_
  <style>_x000D_
 @import url(main.css);_x000D_
  </style>_x000D_
_x000D_
  <g>_x000D_
    <path d="M28.44......./>_x000D_
  </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

  1. For Internal Styles

_x000D_
_x000D_
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">_x000D_
_x000D_
  <style>_x000D_
     .socIcon g {fill:red;}_x000D_
  </style>_x000D_
_x000D_
  <g>_x000D_
    <path d="M28.44......./>_x000D_
  </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Note: External Styles will not work if you include SVG inside <img> tag. It will work perfectly inside <div> tag

C# get string from textbox

When using MVC, try using ViewBag. The best way to take input from textbox and displaying in View.

JavaScript closure inside loops – simple practical example

If you're having this sort of problem with a while loop, rather than a for loop, for example:

_x000D_
_x000D_
var i = 0;
while (i < 5) {
  setTimeout(function() {
    console.log(i);
  }, i * 1000);
  i++;
}
_x000D_
_x000D_
_x000D_

The technique to close over the current value is a bit different. Declare a block-scoped variable with const inside the while block, and assign the current i to it. Then, wherever the variable is being used asynchronously, replace i with the new block-scoped variable:

_x000D_
_x000D_
var i = 0;
while (i < 5) {
  const thisIterationI = i;
  setTimeout(function() {
    console.log(thisIterationI);
  }, i * 1000);
  i++;
}
_x000D_
_x000D_
_x000D_

For older browsers that don't support block-scoped variables, you can use an IIFE called with i:

_x000D_
_x000D_
var i = 0;
while (i < 5) {
  (function(innerI) {
    setTimeout(function() {
      console.log(innerI);
    }, innerI * 1000);
  })(i);
  i++;
}
_x000D_
_x000D_
_x000D_

If the asynchronous action to be invoked happens to be setTimeout like the above, you can also call setTimeout with a third parameter to indicate the argument to call the passed function with:

_x000D_
_x000D_
var i = 0;
while (i < 5) {
  setTimeout(
    (thisIterationI) => { // Callback
      console.log(thisIterationI);
    },
    i * 1000, // Delay
    i // Gets passed to the callback; becomes thisIterationI
  );
  i++;
}
_x000D_
_x000D_
_x000D_

What is the .idea folder?

When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea folder.

Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.

Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.

Note: If you are using git or some version control system, you might want to set this folder "ignore". Example - for git, add this directory to .gitignore. This way, the application is not IDE-specific.

ASP.NET MVC passing an ID in an ActionLink to the controller

The ID will work with @ sign in front also, but we have to add one parameter after that. that is null

look like:

@Html.ActionLink("Label Name", "Name_Of_Page_To_Redirect", "Controller", new {@id="Id_Value"}, null)

Pandas: change data type of Series to String

Your problem can easily be solved by converting it to the object first. After it is converted to object, just use "astype" to convert it to str.

obj = lambda x:x[1:]
df['id']=df['id'].apply(obj).astype('str')

How to set java_home on Windows 7?

You need to set it to C:\Sun\SDK\jdk (Assuming that is where the JDK is installed - It is not the default) - Do not put the \bin in C:\Sun\SDK\jdk\bin.

If your app only runs when you are logged in as the current user then put it in the user variables - If it needs to run for all users on your system then put it in System variables.

You might also need to add %JAVA_HOME%\bin to the path also (Also it depends on whether you run it from just the user or from all users, including System)

How to add a named sheet at the end of all Excel sheets?

This will give you the option to:

  1. Overwrite or Preserve a tab that has the same name.
  2. Place the sheet at End of all tabs or Next to the current tab.
  3. Select your New sheet or the Active one.

Call CreateWorksheet("New", False, False, False)


Sub CreateWorksheet(sheetName, preserveOldSheet, isLastSheet, selectActiveSheet)
  activeSheetNumber = Sheets(ActiveSheet.Name).Index

  If (Evaluate("ISREF('" & sheetName & "'!A1)")) Then 'Does sheet exist?
    If (preserveOldSheet) Then
      MsgBox ("Can not create sheet " + sheetName + ". This sheet exist.")
      Exit Sub
    End If
      Application.DisplayAlerts = False
      Worksheets(sheetName).Delete
    End If

    If (isLastSheet) Then
      Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName 'Place sheet at the end.
    Else 'Place sheet after the active sheet.
      Sheets.Add(After:=Sheets(activeSheetNumber)).Name = sheetName
    End If

    If (selectActiveSheet) Then
      Sheets(activeSheetNumber).Activate
    End If

End Sub

Why should Java 8's Optional not be used in arguments

My take is that Optional should be a Monad and these are not conceivable in Java.

In functional programming you deal with pure and higher order functions that take and compose their arguments only based on their "business domain type". Composing functions that feed on, or whose computation should be reported to, the real-world (so called side effects) requires the application of functions that take care of automatically unpacking the values out of the monads representing the outside world (State, Configuration, Futures, Maybe, Either, Writer, etc...); this is called lifting. You can think of it as a kind of separation of concerns.

Mixing these two levels of abstraction doesn't facilitate legibility so you're better off just avoiding it.

If statement for strings in python?

If should be if. Your program should look like this:

answer = raw_input("Is the information correct? Enter Y for yes or N for no")
if answer.upper() == 'Y':
    print("this will do the calculation")
else:
    exit()

Note also that the indentation is important, because it marks a block in Python.

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

I had these SQL behavior settings enabled on options query execution: ANSI SET IMPLICIT_TRANSACTIONS checked. On execution of your query e.g create, alter table or stored procedure, you have to COMMIT it.

Just type COMMIT and execute it F5

Android Firebase, simply get one child object's data

Firebase listeners fire for both the initial data and any changes.

If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.

This is covered in Firebase's quickstart guide for Android. The relevant code and quote:

FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    System.out.println(snapshot.getValue());  //prints "Do you have data? You'll love Firebase."
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {        
  }
});

In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.

Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

Python import csv to list

Pandas is pretty good at dealing with data. Here is one example how to use it:

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

One big advantage is that pandas deals automatically with header rows.

If you haven't heard of Seaborn, I recommend having a look at it.

See also: How do I read and write CSV files with Python?

Pandas #2

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
dicts = df.to_dict('records')

The content of df is:

     country   population population_time    EUR
0    Germany   82521653.0      2016-12-01   True
1     France   66991000.0      2017-01-01   True
2  Indonesia  255461700.0      2017-01-01  False
3    Ireland    4761865.0             NaT   True
4      Spain   46549045.0      2017-06-01   True
5    Vatican          NaN             NaT   True

The content of dicts is

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
 {'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
 {'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
 {'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
 {'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
 {'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

Pandas #3

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]

The content of lists is:

[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
 ['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
 ['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
 ['Ireland', 4761865.0, NaT, True],
 ['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
 ['Vatican', nan, NaT, True]]

How does a Linux/Unix Bash script know its own PID?

In addition to the example given in the Advanced Bash Scripting Guide referenced by Jefromi, these examples show how pipes create subshells:

$ echo $$ $BASHPID | cat -
11656 31528
$ echo $$ $BASHPID
11656 11656
$ echo $$ | while read line; do echo $line $$ $BASHPID; done
11656 11656 31497
$ while read line; do echo $line $$ $BASHPID; done <<< $$
11656 11656 11656

How to get bitmap from a url in android?

This should do the trick:

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
} // Author: silentnuke

Don't forget to add the internet permission in your manifest.

'git status' shows changed files, but 'git diff' doesn't

I had this same problem described in the following way: If I typed

$ git diff

Git simply returned to the prompt with no error.

If I typed

$ git diff <filename>

Git simply returned to the prompt with no error.

Finally, by reading around I noticed that git diff actually calls the mingw64\bin\diff.exe to do the work.

Here's the deal. I'm running Windows and had installed another Bash utility and it changed my path so it no longer pointed to my mingw64\bin directory.

So if you type:

git diff

and it just returns to the prompt you may have this problem.

The actual diff.exe which is run by git is located in your mingw64\bin directory

Finally, to fix this, I actually copied my mingw64\bin directory to the location Git was looking for it in. I tried it and it still didn't work.

Then, I closed my Git Bash window and opened it again went to my same repository that was failing and now it works.

android pinch zoom

There is also this project that does the job and worked perfectly for me: https://github.com/chrisbanes/PhotoView

Can I use an image from my local file system as background in HTML?

Jeff Bridgman is correct. All you need is
background: url('pic.jpg')
and this assumes that pic is in the same folder as your html.

Also, Roberto's answer works fine. Tested in Firefox, and IE. Thanks to Raptor for adding formatting that displays full picture fit to screen, and without scrollbars... In a folder f, on the desktop is this html and a picture, pic.jpg, using your userid. Make those substitutions in the below:

<html>
<head>
    <style>
        body {

        background: url('file:///C:/Users/userid/desktop/f/pic.jpg') no-repeat center center fixed;

        background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
        -webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
        -moz-background-size: cover; /* optional for Firefox 3.6 */ 
        -o-background-size: cover; /* for Opera 9.5 */
        margin: 0; /* to remove the default white margin of body */
        padding: 0; /* to remove the default white margin of body */
        overflow: hidden;
             }
    </style>
</head>
<body>
hello
</body>
</html>

Add spaces between the characters of a string in Java?

If you use a stringbuilder, it would be efficient to initalize the length when you create the object. Length is going to be 2*lengthofString-1.

Or creating a char array and converting it back to the string would yield the same result.

Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete.

How do I run msbuild from the command line using Windows SDK 7.1?

For Visual Studio 2019 (Preview, at least) it is now in:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin\MSBuild.exe

I imagine the process will be similar for the official 2019 release.

Printing to the console in Google Apps Script?

Answering the OP questions

A) What do I not understand about how the Google Apps Script console works with respect to printing so that I can see if my code is accomplishing what I'd like?

The code on .gs files of a Google Apps Script project run on the server rather than on the web browser. The way to log messages was to use the Class Logger.

B) Is it a problem with the code?

As the error message said, the problem was that console was not defined but nowadays the same code will throw other error:

ReferenceError: "playerArray" is not defined. (line 12, file "Code")

That is because the playerArray is defined as local variable. Moving the line out of the function will solve this.

var playerArray = [];

function addplayerstoArray(numplayers) {
  for (i=0; i<numplayers; i++) {
    playerArray.push(i);
  }
}  

addplayerstoArray(7);

console.log(playerArray[3])

Now that the code executes without throwing errors, instead to look at the browser console we should look at the Stackdriver Logging. From the Google Apps Script editor UI click on View > Stackdriver Logging.

Addendum

On 2017 Google released to all scripts Stackdriver Logging and added the Class Console, so including something like console.log('Hello world!') will not throw an error but the log will be on Google Cloud Platform Stackdriver Logging Service instead of the browser console.

From Google Apps Script Release Notes 2017

June 23, 2017

Stackdriver Logging has been moved out of Early Access. All scripts now have access to Stackdriver logging.

From Logging > Stackdriver logging

The following example shows how to use the console service to log information in Stackdriver.

function measuringExecutionTime() {
  // A simple INFO log message, using sprintf() formatting.
  console.info('Timing the %s function (%d arguments)', 'myFunction', 1);

  // Log a JSON object at a DEBUG level. The log is labeled
  // with the message string in the log viewer, and the JSON content
  // is displayed in the expanded log structure under "structPayload".
  var parameters = {
      isValid: true,
      content: 'some string',
      timestamp: new Date()
  };
  console.log({message: 'Function Input', initialData: parameters});

  var label = 'myFunction() time';  // Labels the timing log entry.
  console.time(label);              // Starts the timer.
  try {
    myFunction(parameters);         // Function to time.
  } catch (e) {
    // Logs an ERROR message.
    console.error('myFunction() yielded an error: ' + e);
  }
  console.timeEnd(label);      // Stops the timer, logs execution duration.
}

List of all users that can connect via SSH

Any user with a valid shell in /etc/passwd can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.

To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.

Python, remove all non-alphabet chars from string

Try:

s = ''.join(filter(str.isalnum, s))

This will take every char from the string, keep only alphanumeric ones and build a string back from them.

Are PHP short tags acceptable to use?

3 tags are available in php:

  1. long-form tag that <?php ?> no need to directive any configured
  2. short_open_tag that <? ?> available if short_open_tag option in php.ini is on
  3. shorten tag <?= since php 5.4.0 it is always available

from php 7.0.0 asp and script tag are removed