Programs & Examples On #Actionmethod

Action methods typically have a one-to-one mapping with user interactions. Examples of user interactions include entering a URL into the browser, clicking a link, and submitting a form. Each of these user interactions causes a request to be sent to the server. In each case, the URL of the request includes information that the MVC framework uses to invoke an action method.

How to receive JSON as an MVC 5 action method parameter

fwiw, this didn't work for me until I had this in the ajax call:

contentType: "application/json; charset=utf-8",

using Asp.Net MVC 4.

Get LatLng from Zip Code - Google Maps API

Here is the function I am using for my work

function getLatLngByZipcode(zipcode) 
{
    var geocoder = new google.maps.Geocoder();
    var address = zipcode;
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();
            alert("Latitude: " + latitude + "\nLongitude: " + longitude);
        } else {
            alert("Request failed.")
        }
    });
    return [latitude, longitude];
}

Gitignore not working

@Ahmad's answer is working but if you just want to git ignore 1 specific file or few files do as @Nicolas suggests

step 1

add filename to .gitignore file

step 2

[remove filename (file path) from git cache

git rm --cached filename

setp 3

commit changes git add filename

git commit -m "add filename to .gitignore"

it will keep your git history clean because if you do git rm -r --cached . and add back all and commit them it will pollute your git history (it will show that you add a lot of files at one commit) not sure am I expressing my thought right but hope you get the point

How do I Sort a Multidimensional Array in PHP

You can use array_multisort()

Try something like this:

foreach ($mdarray as $key => $row) {
    // replace 0 with the field's index/key
    $dates[$key]  = $row[0];
}

array_multisort($dates, SORT_DESC, $mdarray);

For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:

array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);

how to read value from string.xml in android?

**

I hope this code is beneficial

**

String user = getResources().getString(R.string.muser); 

How can foreign key constraints be temporarily disabled using T-SQL?

   --Drop and Recreate Foreign Key Constraints

SET NOCOUNT ON

DECLARE @table TABLE(
   RowId INT PRIMARY KEY IDENTITY(1, 1),
   ForeignKeyConstraintName NVARCHAR(200),
   ForeignKeyConstraintTableSchema NVARCHAR(200),
   ForeignKeyConstraintTableName NVARCHAR(200),
   ForeignKeyConstraintColumnName NVARCHAR(200),
   PrimaryKeyConstraintName NVARCHAR(200),
   PrimaryKeyConstraintTableSchema NVARCHAR(200),
   PrimaryKeyConstraintTableName NVARCHAR(200),
   PrimaryKeyConstraintColumnName NVARCHAR(200)    
)

INSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)
SELECT 
   U.CONSTRAINT_NAME, 
   U.TABLE_SCHEMA, 
   U.TABLE_NAME, 
   U.COLUMN_NAME 
FROM 
   INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
      INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
         ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME
WHERE
   C.CONSTRAINT_TYPE = 'FOREIGN KEY'

UPDATE @table SET
   PrimaryKeyConstraintName = UNIQUE_CONSTRAINT_NAME
FROM 
   @table T
      INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R
         ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME

UPDATE @table SET
   PrimaryKeyConstraintTableSchema  = TABLE_SCHEMA,
   PrimaryKeyConstraintTableName  = TABLE_NAME
FROM @table T
   INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
      ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME

UPDATE @table SET
   PrimaryKeyConstraintColumnName = COLUMN_NAME
FROM @table T
   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
      ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME

--SELECT * FROM @table

--DROP CONSTRAINT:
SELECT
   '
   ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] 
   DROP CONSTRAINT ' + ForeignKeyConstraintName + '

   GO'
FROM
   @table

--ADD CONSTRAINT:
SELECT
   '
   ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] 
   ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ')

   GO'
FROM
   @table

GO

I do agree with you, Hamlin. When you are transfer data using SSIS or when want to replicate data, it seems quite necessary to temporarily disable or drop foreign key constraints and then re-enable or recreate them. In these cases, referential integrity is not an issue, because it is already maintained in the source database. Therefore, you can rest assured regarding this matter.

nil detection in Go

In Go 1.13 and later, you can use Value.IsZero method offered in reflect package.

if reflect.ValueOf(v).IsZero() {
    // v is zero, do something
}

Apart from basic types, it also works for Array, Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer, and Struct. See this for reference.

Richtextbox wpf binding

There is a much easier way!

You can easily create an attached DocumentXaml (or DocumentRTF) property which will allow you to bind the RichTextBox's document. It is used like this, where Autobiography is a string property in your data model:

<TextBox Text="{Binding FirstName}" />
<TextBox Text="{Binding LastName}" />
<RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />

Voila! Fully bindable RichTextBox data!

The implementation of this property is quite simple: When the property is set, load the XAML (or RTF) into a new FlowDocument. When the FlowDocument changes, update the property value.

This code should do the trick:

using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
public class RichTextBoxHelper : DependencyObject
{
    public static string GetDocumentXaml(DependencyObject obj)
    {
        return (string)obj.GetValue(DocumentXamlProperty);
    }

    public static void SetDocumentXaml(DependencyObject obj, string value)
    {
        obj.SetValue(DocumentXamlProperty, value);
    }

    public static readonly DependencyProperty DocumentXamlProperty =
        DependencyProperty.RegisterAttached(
            "DocumentXaml",
            typeof(string),
            typeof(RichTextBoxHelper),
            new FrameworkPropertyMetadata
            {
                BindsTwoWayByDefault = true,
                PropertyChangedCallback = (obj, e) =>
                {
                    var richTextBox = (RichTextBox)obj;

                    // Parse the XAML to a document (or use XamlReader.Parse())
                    var xaml = GetDocumentXaml(richTextBox);
                    var doc = new FlowDocument();
                    var range = new TextRange(doc.ContentStart, doc.ContentEnd);

                    range.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)),
                          DataFormats.Xaml);

                    // Set the document
                    richTextBox.Document = doc;

                    // When the document changes update the source
                    range.Changed += (obj2, e2) =>
                    {
                        if (richTextBox.Document == doc)
                        {
                            MemoryStream buffer = new MemoryStream();
                            range.Save(buffer, DataFormats.Xaml);
                            SetDocumentXaml(richTextBox,
                                Encoding.UTF8.GetString(buffer.ToArray()));
                        }
                    };
                }
            });
}

The same code could be used for TextFormats.RTF or TextFormats.XamlPackage. For XamlPackage you would have a property of type byte[] instead of string.

The XamlPackage format has several advantages over plain XAML, especially the ability to include resources such as images, and it is more flexible and easier to work with than RTF.

It is hard to believe this question sat for 15 months without anyone pointing out the easy way to do this.

How can I select from list of values in SQL Server

Simplest way to get the distinct values of a long list of comma delimited text would be to use a find an replace with UNION to get the distinct values.

SELECT 1
UNION SELECT 1
UNION SELECT 1
UNION SELECT 2
UNION SELECT 5
UNION SELECT 1
UNION SELECT 6

Applied to your long line of comma delimited text

  • Find and replace every comma with UNION SELECT
  • Add a SELECT in front of the statement

You now should have a working query

Can a table row expand and close?

You could do it like this:

HTML

<table>
    <tr>
        <td>Cell 1</td>
        <td>Cell 2</td>
        <td>Cell 3</td>
        <td>Cell 4</td>
        <td><a href="#" id="show_1">Show Extra</a></td>
    </tr>
    <tr>
        <td colspan="5">
            <div id="extra_1" style="display: none;">
                <br>hidden row
                <br>hidden row
                <br>hidden row
            </div>
        </td>
    </tr>
</table>

jQuery

$("a[id^=show_]").click(function(event) {
    $("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
    event.preventDefault();
});

See a demo on JSFiddle

How to print struct variables in console?

Visit here to see the complete code. Here you will also find a link for an online terminal where the complete code can be run and the program represents how to extract structure's information(field's name their type & value). Below is the program snippet that only prints the field names.

package main

import "fmt"
import "reflect"

func main() {
    type Book struct {
        Id    int
        Name  string
        Title string
    }

    book := Book{1, "Let us C", "Enjoy programming with practice"}
    e := reflect.ValueOf(&book).Elem()

    for i := 0; i < e.NumField(); i++ {
        fieldName := e.Type().Field(i).Name
        fmt.Printf("%v\n", fieldName)
    }
}

/*
Id
Name
Title
*/

PHP Unset Array value effect on other indexes

The Key Disappears, whether it is numeric or not. Try out the test script below.

<?php
    $t = array( 'a', 'b', 'c', 'd' );
    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 1: b, 2: c, 3: d

    unset($t[1]);

    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 2: c, 3: d
?>

Null pointer Exception on .setOnClickListener

Try giving your Button in your main.xml a more descriptive name such as:

<Button
                android:id="@+id/buttonXYZ"

(use lowercase in your xml files, at least, the first letter)

And then in your MainActivity class, declare it as:

Button buttonXYZ;

In your onCreate(Bundle savedInstanceState) method, define it as:

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

Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.

Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);

How to add footnotes to GitHub-flavoured Markdown?

Although I am not aware if it's officially documented anywhere, you can do footer notes in Github.

  1. Mark the place where you want to insert footer link with a number enclosed in square brackets, I.E. [1]

  2. On the bottom of the post, make a reference of the numbered marker and followed by a colon and the link, I.E. [1]: http://www.example.com/link1

And once you preview it, it will be rendered as numbered links in the body of the post.

Laravel - Form Input - Multiple select for a one to many relationship

Laravel 4.2

@SamMonk gave the best alternative, I followed his example and build the final piece of code

<select class="chosen-select" multiple="multiple" name="places[]" id="places">
    @foreach($places as $place)
        <option value="{{$place->id}}" @foreach($job->places as $p) @if($place->id == $p->id)selected="selected"@endif @endforeach>{{$place->name}}</option>
    @endforeach
</select>

In my project I'm going to have many table relationships like this so I wrote an extension to keep it clean. To load it, put it in some configuration file like "app/start/global.php". I've created a file "macros.php" under "app/" directory and included it in the EOF of global.php

// app/start/global.php
require app_path().'/macros.php';

// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){

    // For empty Input::old($name) session, $selected is an empty string
    if(!$selected) $selected = array();

    $opts = array(
        'class' => 'chosen-select',
        'id' => $name,
        'name' => $name . '[]',
        'multiple' => true
    );
    $options = array_merge($opts, $options);
    $attributes = HTML::attributes($options);

    // need an empty array to send if all values are unselected
    $ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
    $ret .= '<select ' . $attributes . '>';
    foreach($defaults as $def) {
        $ret .= '<option value="' . $def->id . '"';
        foreach($selected as $p) {
            // session array or passed stdClass obj
            $current = @$p->id ? $p->id: $p;
            if($def->id == $current) {
                $ret .= ' selected="selected"';
            }
        }
        $ret .= '>' . HTML::entities($def->name) . '</option>';
    }
    $ret .= '</select>';
    return $ret;
});

Usage

List without pre-selected items (create view)

{{ Form::chosen('places', $places, Input::old('places')) }}

Preselections (edit view)

{{ Form::chosen('places', $places, $job->places) }}

Complete usage

{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

htaccess <Directory> deny from all

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

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

Regex: ignore case sensitivity

You can practice Regex In Visual Studio and Visual Studio Code using find/replace.

You need to select both Match Case and Regular Expressions for regex expressions with case. Else [A-Z] won't work.enter image description here

Visual Studio 2019 Community

Why can't I check if a 'DateTime' is 'Nothing'?

A way around this would be to use Object datatype instead:

Private _myDate As Object
Private Property MyDate As Date
    Get
        If IsNothing(_myDate) Then Return Nothing
        Return CDate(_myDate)
    End Get
    Set(value As Date)
        If date = Nothing Then
            _myDate = Nothing
            Return
        End If
        _myDate = value
     End Set
End Property

Then you can set the date to nothing like so:

MyDate = Nothing
Dim theDate As Date = MyDate
If theDate = Nothing Then
    'date is nothing
End If

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I had this error on AWS Lightsail, used the top answer above

from

listen [::]:80;

to

listen [::]:80 ipv6only=on default_server;

and then click on "reboot" button inside my AWS account, I have main server Apache and Nginx as proxy.

Should try...catch go inside or outside a loop?

That depends on the failure handling. If you just want to skip the error elements, try inside:

for(int i = 0; i < max; i++) {
    String myString = ...;
    try {
        float myNum = Float.parseFloat(myString);
        myFloats[i] = myNum;
    } catch (NumberFormatException ex) {
        --i;
    }
}

In any other case i would prefer the try outside. The code is more readable, it is more clean. Maybe it would be better to throw an IllegalArgumentException in the error case instead if returning null.

Random Number Between 2 Double Numbers

Watch out: if you're generating the random inside a loop like for example for(int i = 0; i < 10; i++), do not put the new Random() declaration inside the loop.

From MSDN:

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value...

So based on this fact, do something as:

var random = new Random();

for(int d = 0; d < 7; d++)
{
    // Actual BOE
    boes.Add(new LogBOEViewModel()
    {
        LogDate = criteriaDate,
        BOEActual = GetRandomDouble(random, 100, 1000),
        BOEForecast = GetRandomDouble(random, 100, 1000)
    });
}

double GetRandomDouble(Random random, double min, double max)
{
     return min + (random.NextDouble() * (max - min));
}

Doing this way you have the guarantee you'll get different double values.

How does cookie based authentication work?

A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.

To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.

There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.

A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.

How to set up Android emulator proxy settings

Install Proxifier in your host computer. Setup proxifier to use your proxy. You don't need to do anything else. You will be fine. Proxifier traps the calls from the system (including the android emulator) and route it through the configured proxy.

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

Further to the above excellent comments about trusted constraints:

select * from sys.foreign_keys where is_not_trusted = 1 ;
select * from sys.check_constraints where is_not_trusted = 1 ;

An untrusted constraint, much as its name suggests, cannot be trusted to accurately represent the state of the data in the table right now. It can, however, but can be trusted to check data added and modified in the future.

Additionally, untrusted constraints are disregarded by the query optimiser.

The code to enable check constraints and foreign key constraints is pretty bad, with three meanings of the word "check".

ALTER TABLE [Production].[ProductCostHistory] 
WITH CHECK -- This means "Check the existing data in the table".
CHECK CONSTRAINT -- This means "enable the check or foreign key constraint".
[FK_ProductCostHistory_Product_ProductID] -- The name of the check or foreign key constraint, or "ALL".

How to git clone a specific tag

Use --single-branch option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.

git clone <repo_url> --branch <tag_name> --single-branch

What does __FILE__ mean in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

In PHP __FILE__ is the full path (which in my opinion is preferable). This is why, in order to make your paths portable in Ruby, you really need to use this:

File.expand_path(File.dirname(__FILE__) + "relative/path/to/file")

I should note that in Ruby 1.9.1 __FILE__ contains the full path to the file, the above description was for when I used Ruby 1.8.7.

In order to be compatible with both Ruby 1.8.7 and 1.9.1 (not sure about 1.9) you should require files by using the construct I showed above.

How to change font size in a textbox in html

For a <input type='text'> element:

input { font-size: 18px; }

or for a <textarea>:

textarea { font-size: 18px; }

or for a <select>:

select { font-size: 18px; }

you get the drift.

How to echo with different colors in the Windows command line

I was annoyed by the lack of proper coloring in cmd too, so I went ahead and created cmdcolor. It's just an stdout proxy, which looks for a limited set of ANSI/VT100 control sequences (in other words, like in bash), i.e. echo \033[31m RED \033[0m DEFAULT | cmdcolor.exe.

Usage and downloads.

line breaks in a textarea

I'm not sure this is possible but you should try <pre><textarea> ... </textarea></pre>

PHP mail function doesn't complete sending of e-mail

For sending emails from gmail smtp and using php mail function, First you have to setup the sendmail in your local machine, Once it is set it mean you have setup your local smtp server, you will then be able to send emails from the account you set in your sendmail smtp account, in my case I followed the instructions from https://www.developerfiles.com/how-to-send-emails-from-localhost-mac-os-x-el-capitan/ and was able to setup the account,

Remove rows not .isin('X')

You have many options. Collating some of the answers above and the accepted answer from this post you can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]

Note: for option 4 for you'll need to import numpy as np

Update: You can also use the .query method for this too. This allows for method chaining:
5. df.query("column not in @values").
where values is a list of the values that you don't want to include.

Overlay with spinner

And for a spinner like iOs I use this:

enter image description here

html:

  <div class='spinner'>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>

Css:

.spinner {
  font-size: 30px;
  position: relative;
  display: inline-block;
  width: 1em;
  height: 1em;
}

.spinner div {
  position: absolute;
  left: 0.4629em;
  bottom: 0;
  width: 0.074em;
  height: 0.2777em;
  border-radius: 0.5em;
  background-color: transparent;
  -webkit-transform-origin: center -0.2222em;
      -ms-transform-origin: center -0.2222em;
          transform-origin: center -0.2222em;
  -webkit-animation: spinner-fade 1s infinite linear;
          animation: spinner-fade 1s infinite linear;
}
.spinner div:nth-child(1) {
  -webkit-animation-delay: 0s;
          animation-delay: 0s;
  -webkit-transform: rotate(0deg);
      -ms-transform: rotate(0deg);
          transform: rotate(0deg);
}
.spinner div:nth-child(2) {
  -webkit-animation-delay: 0.083s;
          animation-delay: 0.083s;
  -webkit-transform: rotate(30deg);
      -ms-transform: rotate(30deg);
          transform: rotate(30deg);
}
.spinner div:nth-child(3) {
  -webkit-animation-delay: 0.166s;
          animation-delay: 0.166s;
  -webkit-transform: rotate(60deg);
      -ms-transform: rotate(60deg);
          transform: rotate(60deg);
}
.spinner div:nth-child(4) {
  -webkit-animation-delay: 0.249s;
          animation-delay: 0.249s;
  -webkit-transform: rotate(90deg);
      -ms-transform: rotate(90deg);
          transform: rotate(90deg);
}
.spinner div:nth-child(5) {
  -webkit-animation-delay: 0.332s;
          animation-delay: 0.332s;
  -webkit-transform: rotate(120deg);
      -ms-transform: rotate(120deg);
          transform: rotate(120deg);
}
.spinner div:nth-child(6) {
  -webkit-animation-delay: 0.415s;
          animation-delay: 0.415s;
  -webkit-transform: rotate(150deg);
      -ms-transform: rotate(150deg);
          transform: rotate(150deg);
}
.spinner div:nth-child(7) {
  -webkit-animation-delay: 0.498s;
          animation-delay: 0.498s;
  -webkit-transform: rotate(180deg);
      -ms-transform: rotate(180deg);
          transform: rotate(180deg);
}
.spinner div:nth-child(8) {
  -webkit-animation-delay: 0.581s;
          animation-delay: 0.581s;
  -webkit-transform: rotate(210deg);
      -ms-transform: rotate(210deg);
          transform: rotate(210deg);
}
.spinner div:nth-child(9) {
  -webkit-animation-delay: 0.664s;
          animation-delay: 0.664s;
  -webkit-transform: rotate(240deg);
      -ms-transform: rotate(240deg);
          transform: rotate(240deg);
}
.spinner div:nth-child(10) {
  -webkit-animation-delay: 0.747s;
          animation-delay: 0.747s;
  -webkit-transform: rotate(270deg);
      -ms-transform: rotate(270deg);
          transform: rotate(270deg);
}
.spinner div:nth-child(11) {
  -webkit-animation-delay: 0.83s;
          animation-delay: 0.83s;
  -webkit-transform: rotate(300deg);
      -ms-transform: rotate(300deg);
          transform: rotate(300deg);
}
.spinner div:nth-child(12) {
  -webkit-animation-delay: 0.913s;
          animation-delay: 0.913s;
  -webkit-transform: rotate(330deg);
      -ms-transform: rotate(330deg);
          transform: rotate(330deg);
}

@-webkit-keyframes spinner-fade {
  0% {
    background-color: #69717d;
  }
  100% {
    background-color: transparent;
  }
}

@keyframes spinner-fade {
  0% {
    background-color: #69717d;
  }
  100% {
    background-color: transparent;
  }
}

get from this website : https://365webresources.com/10-best-pure-css-loading-spinners-front-end-developers/

how to make a countdown timer in java

You'll see people using the Timer class to do this. Unfortunately, it isn't always accurate. Your best bet is to get the system time when the user enters input, calculate a target system time, and check if the system time has exceeded the target system time. If it has, then break out of the loop.

Spark: Add column to dataframe conditionally

How about something like this?

val newDF = df.filter($"B" === "").take(1) match {
  case Array() => df
  case _ => df.withColumn("D", $"B" === "")
}

Using take(1) should have a minimal hit

Angular2 *ngIf check object array length in template

This article helped me alot figuring out why it wasn't working for me either. It give me a lesson to think of the webpage loading and how angular 2 interacts as a timeline and not just the point in time i'm thinking of. I didn't see anyone else mention this point, so I will...

The reason the *ngIf is needed because it will try to check the length of that variable before the rest of the OnInit stuff happens, and throw the "length undefined" error. So thats why you add the ? because it won't exist yet, but it will soon.

How to select label for="XYZ" in CSS?

The selector would be label[for=email], so in CSS:

label[for=email]
{
    /* ...definitions here... */
}

...or in JavaScript using the DOM:

var element = document.querySelector("label[for=email]");

...or in JavaScript using jQuery:

var element = $("label[for=email]");

It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.

(I'm assuming that the template {t _your_email} will fill in a field with id="email". If not, use a class instead.)

Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:

label[for="field[]"]
{
    /* ...definitions here... */
}

They can be single or double quotes.

unable to install pg gem

@Winfield said it:

The pg gem requires the postgresql client libraries to bind against. This error usually means it can't find your Postgres libraries. Either you don't have them installed or you may need to pass the --with-pg-dir= to your gem install.

More than that, you only need --with-pg-config= to install it.

On a Mac

If, by any chance, you also installed postgres through the website bundle on mac, it will be on somewhere like /Applications/Postgres.app/Contents/Versions/9.3/bin.

So, either you pass it on the gem install:

gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.3/bin/pg_config

Or you set the PATH properly. Since that might be too much, to temporarily set the PATH:

export PATH=%PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin/

Remove header and footer from window.print()

This will be the simplest solution. I tried most of the solutions in the internet but only this helped me.

@print{
    @page :footer {color: #fff }
    @page :header {color: #fff}
}

Javascript - Append HTML to container element without innerHTML

I am surprised that none of the answers mentioned the insertAdjacentHTML() method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.

Basic usage:

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');

Is there a Pattern Matching Utility like GREP in Windows?

I know that it's a bit old topic but, here is another thing you can do. I work on a developer VM with no internet access and quite limited free disk space, so I made use of the java installed on it.

Compile small java program that prints regex matches to the console. Put the jar somewhere on your system, create a batch to execute it and add the folder to your PATH variable:

JGrep.java:

package com.jgrep;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JGrep {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        int printGroup = -1;
        if (args.length < 2) {
            System.out.println("Invalid arguments. Usage:");
            System.out.println("jgrep [...-MODIFIERS] [PATTERN] [FILENAME]");
            System.out.println("Available modifiers:");
            System.out.println(" -printGroup            - will print the given group only instead of the whole match. Eg: -printGroup=1");
            System.out.println("Current arguments:");
            for (int i = 0; i < args.length; i++) {
                System.out.println("args[" + i + "]=" + args[i]);
            }
            return;
        }
        Pattern pattern = null;
        String filename = args[args.length - 1];
        String patternArg = args[args.length - 2];        
        pattern = Pattern.compile(patternArg);

        int argCount = 2;
        while (args.length - argCount - 1 >= 0) {
            String arg = args[args.length - argCount - 1];
            argCount++;
            if (arg.startsWith("-printGroup=")) {
                printGroup = Integer.parseInt(arg.substring("-printGroup=".length()));
            }
        }
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
        }
        Matcher matcher = pattern.matcher(sb.toString());
        int matchesCount = 0;
        while (matcher.find()) {
            if (printGroup > 0) {
                System.out.println(matcher.group(printGroup));
            } else {
                System.out.println(matcher.group());
            }
            matchesCount++;
        }
        System.out.println("----------------------------------------");
        System.out.println("File: " + filename);
        System.out.println("Pattern: " + pattern.pattern());
        System.out.println("PrintGroup: " + printGroup);
        System.out.println("Matches: " + matchesCount);
    }
}

c:\jgrep\jgrep.bat (together with jgrep.jar):

@echo off
java -cp c:\jgrep\jgrep.jar com.jgrep.JGrep %*

and add c:\jgrep in the end of the PATH environment variable.

Now simply call jgrep "expression" file.txt from anywhere.

I needed to print some specific groups from my expression so I added a modifier and call it like jgrep -printGroup=1 "expression" file.txt.

Editing specific line in text file in Python

#read file lines and edit specific item

file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])

a[0]=a[0][0:5]+' Ericsson\n'
print(a[0])

file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

All you have to do is apply the format you want in the html helper call, ie.

@Html.TextBoxFor(m => m.RegistrationDate, "{0:dd/MM/yyyy}")

You don't need to provide the date format in the model class.

Data binding in React

Define state attributes. Add universal handleChange event handler. Add name param to input tag for mapping.

this.state = { stateAttrName:"" }

handleChange=(event)=>{
    this.setState({[event.target.name]:event.target.value });
  } 

<input className="form-control" name="stateAttrName" value= 
{this.state.stateAttrName} onChange={this.handleChange}/>

CSS Inset Borders

If you want to make sure the border is on the inside of your element, you can use

box-sizing:border-box;

this will place the following border on the inside of the element:

border: 10px solid black;

(similar result you'd get using the additonal parameter inset on box-shadow, but instead this one is for the real border and you can still use your shadow for something else.)

Note to another answer above: as soon as you use any inset on box-shadow of a certain element, you are limited to a maximum of 2 box-shadows on that element and would require a wrapper div for further shadowing.

Both solutions should as well get you rid of the undesired 3D effects. Also note both solutions are stackable (see the example I've added in 2018)

_x000D_
_x000D_
.example-border {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  border:40px solid blue;_x000D_
  box-sizing:border-box;_x000D_
  float:left;_x000D_
}_x000D_
_x000D_
.example-shadow {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  float:left;_x000D_
  margin-left:20px;_x000D_
  box-shadow:0 0 0 40px green inset;_x000D_
}_x000D_
_x000D_
.example-combined {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  float:left;_x000D_
  margin-left:20px;_x000D_
  border:20px solid orange;_x000D_
  box-sizing:border-box;_x000D_
  box-shadow:0 0 0 20px red inset;_x000D_
}
_x000D_
<div class="example-border"></div>_x000D_
<div class="example-shadow"></div>_x000D_
<div class="example-combined"></div>
_x000D_
_x000D_
_x000D_

How can I sort generic list DESC and ASC?

Without Linq:

Ascending:

li.Sort();

Descending:

li.Sort();
li.Reverse();

How to add buttons at top of map fragment API v2 layout

Maybe a simpler solution is to set an overlay in front of your map using FrameLayout or RelativeLayout and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity" >

    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scrollbars="vertical"  
        class="com.google.android.gms.maps.SupportMapFragment"/>

    <RadioGroup 
        android:id="@+id/radio_group_list_selector"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal" 
        android:background="#80000000"
        android:padding="4dp" >

        <RadioButton
            android:id="@+id/radioPopular"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="@string/Popular"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioAZ"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/AZ"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />

        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioCategory"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/Category"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioNearBy"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/NearBy"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton3"
            android:textColor="@color/textcolor_radiobutton" />
    </RadioGroup>
</FrameLayout>

How to post SOAP Request from PHP

Below is a quick example of how to do this (which best explained the matter to me) that I essentially found at this website. That website link also explains WSDL, which is important for working with SOAP services.

However, I don't think the API address they were using in the example below still works, so just switch in one of your own choosing.

$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL';

$trace = true;
$exceptions = false;

$xml_array['placeName'] = 'Pomona';
$xml_array['MaxItems'] = 3;
$xml_array['imagePresence'] = true;

$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
$response = $client->GetPlaceList($xml_array);

var_dump($response);

difference between throw and throw new Exception()

throw re-throws the caught exception, retaining the stack trace, while throw new Exception loses some of the details of the caught exception.

You would normally use throw by itself to log an exception without fully handling it at that point.

BlackWasp has a good article sufficiently titled Throwing Exceptions in C#.

Get domain name from given url

In my case i only needed the main domain and not the subdomain (no "www" or whatever the subdomain is) :

public static String getUrlDomain(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String domain = uri.getHost();
    String[] domainArray = domain.split("\\.");
    if (domainArray.length == 1) {
        return domainArray[0];
    }
    return domainArray[domainArray.length - 2] + "." + domainArray[domainArray.length - 1];
}

With this method the url "https://rest.webtoapp.io/llSlider?lg=en&t=8" will have for domain "webtoapp.io".

Android statusbar icons color

Yes it's possible to change it to gray (no custom colors) but this only works from API 23 and above you only need to add this in your values-v23/styles.xml

<item name="android:windowLightStatusBar">true</item>

enter image description here

How to see log files in MySQL?

shell> mysqladmin flush-logs


shell> mv host_name.err-old backup-directory

bundle install fails with SSL certificate verification error

This worked for me:

  • download latest gem at https://rubygems.org/pages/download
  • install the gem with gem install --local [path to downloaded gem file]
  • update the gems with update_rubygems
  • check that you're on the latest gem version with gem --version

How do you easily horizontally center a <div> using CSS?

_x000D_
_x000D_
.center {_x000D_
  height: 20px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.center>div {_x000D_
  margin: auto;_x000D_
  background-color: green;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div class="center">_x000D_
  <div>You text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JsFiddle

What is SuppressWarnings ("unchecked") in Java?

A warning by which the compiler indicates that it cannot ensure type safety. The term "unchecked" warning is misleading. It does not mean that the warning is unchecked in any way. The term "unchecked" refers to the fact that the compiler and the runtime system do not have enough type information to perform all type checks that would be necessary to ensure type safety. In this sense, certain operations are "unchecked".

The most common source of "unchecked" warnings is the use of raw types. "unchecked" warnings are issued when an object is accessed through a raw type variable, because the raw type does not provide enough type information to perform all necessary type checks.

Example (of unchecked warning in conjunction with raw types):

TreeSet set = new TreeSet(); 
set.add("abc");        // unchecked warning 
set.remove("abc");
warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.TreeSet 
               set.add("abc");  
                      ^

When the add method is invoked the compiler does not know whether it is safe to add a String object to the collection. If the TreeSet is a collection that contains String s (or a supertype thereof), then it would be safe. But from the type information provided by the raw type TreeSet the compiler cannot tell. Hence the call is potentially unsafe and an "unchecked" warning is issued.

"unchecked" warnings are also reported when the compiler finds a cast whose target type is either a parameterized type or a type parameter.

Example (of an unchecked warning in conjunction with a cast to a parameterized type or type variable):

  class Wrapper<T> { 
  private T wrapped ; 
  public Wrapper (T arg) {wrapped = arg;} 
  ... 
  public Wrapper <T> clone() { 
    Wrapper<T> clon = null; 
     try {  
       clon = (Wrapper<T>) super.clone(); // unchecked warning 
     } catch (CloneNotSupportedException e) {  
       throw new InternalError();  
     } 
     try {  
       Class<?> clzz = this.wrapped.getClass(); 
       Method   meth = clzz.getMethod("clone", new Class[0]); 
       Object   dupl = meth.invoke(this.wrapped, new Object[0]); 
       clon.wrapped = (T) dupl; // unchecked warning 
     } catch (Exception e) {} 
     return clon; 
  } 
} 
warning: [unchecked] unchecked cast 
found   : java.lang.Object 
required: Wrapper <T> 
                  clon = ( Wrapper <T>)super.clone();  
                                                ^ 
warning: [unchecked] unchecked cast 
found   : java.lang.Object 
required: T 
                  clon. wrapped = (T)dupl;

A cast whose target type is either a (concrete or bounded wildcard) parameterized type or a type parameter is unsafe, if a dynamic type check at runtime is involved. At runtime, only the type erasure is available, not the exact static type that is visible in the source code. As a result, the runtime part of the cast is performed based on the type erasure, not on the exact static type.

In the example, the cast to Wrapper would check whether the object returned from super.clone is a Wrapper , not whether it is a wrapper with a particular type of members. Similarly, the casts to the type parameter T are cast to type Object at runtime, and probably optimized away altogether. Due to type erasure, the runtime system is unable to perform more useful type checks at runtime.

In a way, the source code is misleading, because it suggests that a cast to the respective target type is performed, while in fact the dynamic part of the cast only checks against the type erasure of the target type. The "unchecked" warning is issued to draw the programmer's attention to this mismatch between the static and dynamic aspect of the cast.

Please refer: What is an "unchecked" warning?

Install opencv for Python 3.3

You can use the following command on the command prompt (cmd) on Windows:

py -3.3 -m pip install opencv-python

I made a video on how to install OpenCV Python on Windows in 1 minute here:

https://www.youtube.com/watch?v=m2-8SHk-1SM

Hope it helps!

Remove Safari/Chrome textinput/textarea glow

I just needed to remove this effect from my text input fields, and I couldn't get the other techniques to work quite right, but this is what works for me;

input[type="text"], input[type="text"]:focus{
            outline: 0;
            border:none;
            box-shadow:none;

    }

Tested in Firefox and in Chrome.

MySQL - UPDATE multiple rows with different values in one query

MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.

INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
 cod_user=VALUES(cod_user), date=VALUES(date)

This assumes that the user_rol, cod_office combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list. If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.

However, this approach makes prepared statements easier to build and more concise.

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

Prevent textbox autofill with previously entered values

Trying from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");

Call int() function on every list element?

Another way,

for i, v in enumerate(numbers): numbers[i] = int(v)

Start new Activity and finish current one in Android?

You can use finish() method or you can use:

android:noHistory="true"

And then there is no need to call finish() anymore.

<activity android:name=".ClassName" android:noHistory="true" ... />

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

You can used this line of code : url()->current()

In blade file : {{url()->current()}}

Date minus 1 year?

// set your date here
$mydate = "2009-01-01";

/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));

// format and display the computed date
echo date("Y-m-d", $lastyear);

What is more efficient? Using pow to square or just multiply it with itself?

I was also wondering about the performance issue, and was hoping this would be optimised out by the compiler, based on the answer from @EmileCormier. However, I was worried that the test code he showed would still allow the compiler to optimise away the std::pow() call, since the same values were used in the call every time, which would allow the compiler to store the results and re-use it in the loop - this would explain the almost identical run-times for all cases. So I had a look into it too.

Here's the code I used (test_pow.cpp):

#include <iostream>                                                                                                                                                                                                                       
#include <cmath>
#include <chrono>

class Timer {
  public:
    explicit Timer () : from (std::chrono::high_resolution_clock::now()) { }

    void start () {
      from = std::chrono::high_resolution_clock::now();
    }

    double elapsed() const {
      return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - from).count() * 1.0e-6;
    }

  private:
    std::chrono::high_resolution_clock::time_point from;
};

int main (int argc, char* argv[])
{
  double total;
  Timer timer;



  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,2);
  std::cout << "std::pow(i,2): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i;
  std::cout << "i*i: " << timer.elapsed() << "s (result = " << total << ")\n";

  std::cout << "\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,3);
  std::cout << "std::pow(i,3): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i*i;
  std::cout << "i*i*i: " << timer.elapsed() << "s (result = " << total << ")\n";


  return 0;
}

This was compiled using:

g++ -std=c++11 [-O2] test_pow.cpp -o test_pow

Basically, the difference is the argument to std::pow() is the loop counter. As I feared, the difference in performance is pronounced. Without the -O2 flag, the results on my system (Arch Linux 64-bit, g++ 4.9.1, Intel i7-4930) were:

std::pow(i,2): 0.001105s (result = 3.33333e+07)
i*i: 0.000352s (result = 3.33333e+07)

std::pow(i,3): 0.006034s (result = 2.5e+07)
i*i*i: 0.000328s (result = 2.5e+07)

With optimisation, the results were equally striking:

std::pow(i,2): 0.000155s (result = 3.33333e+07)
i*i: 0.000106s (result = 3.33333e+07)

std::pow(i,3): 0.006066s (result = 2.5e+07)
i*i*i: 9.7e-05s (result = 2.5e+07)

So it looks like the compiler does at least try to optimise the std::pow(x,2) case, but not the std::pow(x,3) case (it takes ~40 times longer than the std::pow(x,2) case). In all cases, manual expansion performed better - but particularly for the power 3 case (60 times quicker). This is definitely worth bearing in mind if running std::pow() with integer powers greater than 2 in a tight loop...

Difference between matches() and find() in Java Regex

find() will consider the sub-string against the regular expression where as matches() will consider complete expression.

find() will returns true only if the sub-string of the expression matches the pattern.

public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d");
        String candidate = "Java123";
        Matcher m = p.matcher(candidate);

        if (m != null){
            System.out.println(m.find());//true
            System.out.println(m.matches());//false
        }
    }

Trees in Twitter Bootstrap

For those still searching for a tree with CSS3, this is a fantastic piece of code I found on the net:

http://thecodeplayer.com/walkthrough/css3-family-tree

HTML

<div class="tree">
  <ul>
    <li>
      <a href="#">Parent</a>
      <ul>
        <li>
          <a href="#">Child</a>
          <ul>
            <li>
              <a href="#">Grand Child</a>
            </li>
          </ul>
        </li>
        <li>
          <a href="#">Child</a>
          <ul>
            <li><a href="#">Grand Child</a></li>
            <li>
              <a href="#">Grand Child</a>
              <ul>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
              </ul>
            </li>
            <li><a href="#">Grand Child</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

CSS

* {margin: 0; padding: 0;}

.tree ul {
  padding-top: 20px; position: relative;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

.tree li {
  float: left; text-align: center;
  list-style-type: none;
  position: relative;
  padding: 20px 5px 0 5px;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

/*We will use ::before and ::after to draw the connectors*/

.tree li::before, .tree li::after{
  content: '';
  position: absolute; top: 0; right: 50%;
  border-top: 1px solid #ccc;
  width: 50%; height: 20px;
}
.tree li::after{
  right: auto; left: 50%;
  border-left: 1px solid #ccc;
}

/*We need to remove left-right connectors from elements without 
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
  display: none;
}

/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}

/*Remove left connector from first child and 
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
  border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
  border-right: 1px solid #ccc;
  border-radius: 0 5px 0 0;
  -webkit-border-radius: 0 5px 0 0;
  -moz-border-radius: 0 5px 0 0;
}
.tree li:first-child::after{
  border-radius: 5px 0 0 0;
  -webkit-border-radius: 5px 0 0 0;
  -moz-border-radius: 5px 0 0 0;
}

/*Time to add downward connectors from parents*/
.tree ul ul::before{
  content: '';
  position: absolute; top: 0; left: 50%;
  border-left: 1px solid #ccc;
  width: 0; height: 20px;
}

.tree li a{
  border: 1px solid #ccc;
  padding: 5px 10px;
  text-decoration: none;
  color: #666;
  font-family: arial, verdana, tahoma;
  font-size: 11px;
  display: inline-block;

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

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
  background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after, 
.tree li a:hover+ul li::before, 
.tree li a:hover+ul::before, 
.tree li a:hover+ul ul::before{
  border-color:  #94a0b4;
}

PS: apart from the code, I also like the way the site shows it in action... really innovative.

List of all unique characters in a string?

char_seen = []
for char in string:
    if char not in char_seen:
        char_seen.append(char)
print(''.join(char_seen))

This will preserve the order in which alphabets are coming,

output will be

abcd

How to print strings with line breaks in java

You can try using StringBuilder: -

    final StringBuilder sb = new StringBuilder();

    sb.append("SHOP MA\n");
    sb.append("----------------------------\n");
    sb.append("Pannampitiya\n");
    sb.append("09-10-2012 harsha  no: 001\n");
    sb.append("No  Item  Qty  Price  Amount\n");
    sb.append("1 Bread 1 50.00  50.00\n");
    sb.append("____________________________\n");

    // To use StringBuilder as String.. Use `toString()` method..
    System.out.println(sb.toString());   

Find index of a value in an array

Just posted my implementation of IndexWhere() extension method (with unit tests):

http://snipplr.com/view/53625/linq-index-of-item--indexwhere/

Example usage:

int index = myList.IndexWhere(item => item.Something == someOtherThing);

How to use Session attributes in Spring-mvc

If you want to delete object after each response you don't need session,

If you want keep object during user session , There are some ways:

  1. directly add one attribute to session:

    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request){
       ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
       return "testJsp";
    }
    

    and you can get it from controller like this :

    ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
    
  2. Make your controller session scoped

    @Controller
    @Scope("session")
    
  3. Scope the Objects ,for example you have user object that should be in session every time:

    @Component
    @Scope("session")
    public class User
     {
        String user;
        /*  setter getter*/
      }
    

    then inject class in each controller that you want

       @Autowired
       private User user
    

    that keeps class on session.

  4. The AOP proxy injection : in spring -xml:

    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
    
      <bean id="user"    class="com.User" scope="session">     
          <aop:scoped-proxy/>
      </bean>
    </beans>
    

    then inject class in each controller that you want

    @Autowired
    private User user
    

5.Pass HttpSession to method:

 String index(HttpSession session) {
            session.setAttribute("mySessionAttribute", "someValue");
            return "index";
        }

6.Make ModelAttribute in session By @SessionAttributes("ShoppingCart"):

  public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
//Spring V4
//you can modify session status  by sessionStatus.setComplete();
}

or you can add Model To entire Controller Class like,

@Controller
    @SessionAttributes("ShoppingCart")
    @RequestMapping("/req")
    public class MYController {

        @ModelAttribute("ShoppingCart")
        public Visitor getShopCart (....) {
            return new ShoppingCart(....); //get From DB Or Session
        }  
      }

each one has advantage and disadvantage:

@session may use more memory in cloud systems it copies session to all nodes, and direct method (1 and 5) has messy approach, it is not good to unit test.

To access session jsp

<%=session.getAttribute("ShoppingCart.prop")%>

in Jstl :

<c:out value="${sessionScope.ShoppingCart.prop}"/>

in Thymeleaf:

<p th:text="${session.ShoppingCart.prop}" th:unless="${session == null}"> . </p>

How can I rename a conda environment?

conda should have given us a simple tool like cond env rename <old> <new> but it hasn't. Simply renaming the directory, as in this previous answer, of course, breaks the hardcoded hashbangs(#!). Hence, we need to go one more level deeper to achieve what we want.

conda env list
# conda environments:
#
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
rtg                      /home/tgowda/miniconda3/envs/rtg

Here I am trying to rename rtg --> unsup (please bear with those names, this is my real use case)

$ cd /home/tgowda/miniconda3/envs 
$ OLD=rtg
$ NEW=unsup
$ mv $OLD $NEW   # rename dir

$ conda env list
# conda environments:
#
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
unsup                    /home/tgowda/miniconda3/envs/unsup


$ conda activate $NEW
$ which python
  /home/tgowda/miniconda3/envs/unsup/bin/python

the previous answer reported upto this, but wait, we are not done yet! the pending task is, $NEW/bin dir has a bunch of executable scripts with hashbangs (#!) pointing to the $OLD env paths.

See jupyter, for example:

$ which jupyter
/home/tgowda/miniconda3/envs/unsup/bin/jupyter

$ head -1 $(which jupyter) # its hashbang is still looking at old
#!/home/tgowda/miniconda3/envs/rtg/bin/python

So, we can easily fix it with a sed

$ sed  -i.bak "s:envs/$OLD/bin:envs/$NEW/bin:" $NEW/bin/*  
# `-i.bak` created backups, to be safe

$ head -1 $(which jupyter) # check if updated
#!/home/tgowda/miniconda3/envs/unsup/bin/python
$ jupyter --version # check if it works
jupyter core     : 4.6.3
jupyter-notebook : 6.0.3

$ rm $NEW/bin/*.bak  # remove backups

Now we are done

I think it should be trivial to write a portable script to do all those and bind it to conda env rename old new.


I tested this on ubuntu. For whatever unforseen reasons, if things break and you wish to revert the above changes:

$ mv $NEW  $OLD
$ sed  -i.bak "s:envs/$NEW/bin:envs/$OLD/bin:" $OLD/bin/*

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

Replace non-ASCII characters with a single space

For character processing, use Unicode strings:

PythonWin 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32.
>>> s='ABC??def'
>>> import re
>>> re.sub(r'[^\x00-\x7f]',r' ',s)   # Each char is a Unicode codepoint.
'ABC  def'
>>> b = s.encode('utf8')
>>> re.sub(rb'[^\x00-\x7f]',rb' ',b) # Each char is a 3-byte UTF-8 sequence.
b'ABC      def'

But note you will still have a problem if your string contains decomposed Unicode characters (separate character and combining accent marks, for example):

>>> s = 'mañana'
>>> len(s)
6
>>> import unicodedata as ud
>>> n=ud.normalize('NFD',s)
>>> n
'man~ana'
>>> len(n)
7
>>> re.sub(r'[^\x00-\x7f]',r' ',s) # single codepoint
'ma ana'
>>> re.sub(r'[^\x00-\x7f]',r' ',n) # only combining mark replaced
'man ana'

How to set space between listView Items in Android

This will help you add the divider height.

 getListView().setDividerHeight(10)

If you want to add a custom view, you can add a small view in the listView item layout itself.

Is there a Python equivalent to Ruby's string interpolation?

import inspect
def s(template, **kwargs):
    "Usage: s(string, **locals())"
    if not kwargs:
        frame = inspect.currentframe()
        try:
            kwargs = frame.f_back.f_locals
        finally:
            del frame
        if not kwargs:
            kwargs = globals()
    return template.format(**kwargs)

Usage:

a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found

PS: performance may be a problem. This is useful for local scripts, not for production logs.

Duplicated:

How To Launch Git Bash from DOS Command Line?

https://stackoverflow.com/a/33368029/15789

I have posted an answer here.

Open a Windows command window, and execute this script. If there is a change in your working directory, it will open a bash terminal in your working directory, and display the current git status. It keeps the bash window open, by calling exec bash.

If you have multiple projects you may create copies of this script with different project folder, and call it from a main batch script.

How to define a variable in a Dockerfile?

If the variable is re-used within the same RUN instruction, one could simply set a shell variable. I really like how they approached this with the official Ruby Dockerfile.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

Swift 4 answer...

If the table view is selected in interface builder and in the attributes inspector the style "Grouped" is selected, enter the following code in your view controller to fix the extra header space issue.

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return CGFloat.leastNonzeroMagnitude
}

PowerShell script to check the status of a URL

You must update the Windows PowerShell to minimum of version 4.0 for the script below to work.


[array]$SiteLinks = "http://mypage.global/Chemical/test.html"
"http://maypage2:9080/portal/site/hotpot/test.json"


foreach($url in $SiteLinks) {

   try {
      Write-host "Verifying $url" -ForegroundColor Yellow
      $checkConnection = Invoke-WebRequest -Uri $url
      if ($checkConnection.StatusCode -eq 200) {
         Write-Host "Connection Verified!" -ForegroundColor Green
      }

   } 
   catch [System.Net.WebException] {
      $exceptionMessage = $Error[0].Exception
      if ($exceptionMessage -match "503") {
         Write-Host "Server Unavaiable" -ForegroundColor Red
      }
      elseif ($exceptionMessage -match "404") {
         Write-Host "Page Not found" -ForegroundColor Red
      }


   }
}

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

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

Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi');    // => true
reg.test('abcdefghi');    // => false <=

This is because Regexp keeps track of the lastIndex when a new match is found.

Jenkins returned status code 128 with github

This error:

stderr: Permission denied (publickey). fatal: The remote end hung up unexpectedly

indicates that Jenkins is trying to connect to github with the wrong ssh key.

You should:

  1. Determine the user that jenkins runs as, eg. 'build' or 'jenkins'
  2. Login on the jenkins host that is trying to do the clone - that is, do not login to the master if a node is actually doing the build.
  3. Try you ssh to github - if it fails, then you need to add the proper key to /.ssh

class << self idiom in Ruby

First, the class << foo syntax opens up foo's singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.

a = 'foo'
class << a
  def inspect
    '"bar"'
  end
end
a.inspect   # => "bar"

a = 'foo'   # new object, new singleton class
a.inspect   # => "foo"

Now, to answer the question: class << self opens up self's singleton class, so that methods can be redefined for the current self object (which inside a class or module body is the class or module itself). Usually, this is used to define class/module ("static") methods:

class String
  class << self
    def value_of obj
      obj.to_s
    end
  end
end

String.value_of 42   # => "42"

This can also be written as a shorthand:

class String
  def self.value_of obj
    obj.to_s
  end
end

Or even shorter:

def String.value_of obj
  obj.to_s
end

When inside a function definition, self refers to the object the function is being called with. In this case, class << self opens the singleton class for that object; one use of that is to implement a poor man's state machine:

class StateMachineExample
  def process obj
    process_hook obj
  end

private
  def process_state_1 obj
    # ...
    class << self
      alias process_hook process_state_2
    end
  end

  def process_state_2 obj
    # ...
    class << self
      alias process_hook process_state_1
    end
  end

  # Set up initial state
  alias process_hook process_state_1
end

So, in the example above, each instance of StateMachineExample has process_hook aliased to process_state_1, but note how in the latter, it can redefine process_hook (for self only, not affecting other StateMachineExample instances) to process_state_2. So, each time a caller calls the process method (which calls the redefinable process_hook), the behaviour changes depending on what state it's in.

How to do something to each file in a directory with a batch script

Easiest method:

From Command Line, use:

for %f in (*.*) do echo %f

From a Batch File (double up the % percent signs):

for %%f in (*.*) do echo %%f

From a Batch File with folder specified as 1st parameter:

for %%f in (%1\*.*) do echo %%f

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

What is a CSRF token? What is its importance and how does it work?

Yes, the post data is safe. But the origin of that data is not. This way somebody can trick user with JS into logging in to your site, while browsing attacker's web page.

In order to prevent that, django will send a random key both in cookie, and form data. Then, when users POSTs, it will check if two keys are identical. In case where user is tricked, 3rd party website cannot get your site's cookies, thus causing auth error.

Set TextView text from html-formatted string resource in XML

  String termsOfCondition="<font color=#cc0029>Terms of Use </font>";
  String commma="<font color=#000000>, </font>";
  String privacyPolicy="<font color=#cc0029>Privacy Policy </font>";
  Spanned text=Html.fromHtml("I am of legal age and I have read, understood, agreed and accepted the "+termsOfCondition+commma+privacyPolicy);
        secondCheckBox.setText(text);

How to get absolute value from double - c-language

I have found that using cabs(double), cabsf(float), cabsl(long double), __cabsf(float), __cabs(double), __cabsf(long double) is the solution

SELECT inside a COUNT

SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

Netbeans installation doesn't find JDK

If you are certain that you have a JDK installed (and not a JRE), you can specify the location of the JDK on the commandline when starting the installer (as mentioned in the error message you get).

These FAQ entries might also help you:

http://wiki.netbeans.org/FaqInstallJavahome
http://wiki.netbeans.org/FaqSuitableJvmNotFound

Running AMP (apache mysql php) on Android

There are no PHP interpreters that I know of for Android or IOS (or WebOS or BlackBerryOS).

If you want to run a web site as an app on a mobile device or tablet as a native application, all functionality needs to be in Javascript and wrapped with a library like PhoneGap or Titanium. Android and IOS web apps are both able to use local storage databases where data can be kept until a network connection is made. Any server-side logic would require a call out to your web server and an active internet connection on the device.

How do I capitalize first letter of first name and last name in C#?

The most direct option is going to be to use the ToTitleCase function that is available in .NET which should take care of the name most of the time. As edg pointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.

However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.

firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();
lastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();

However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and split it accordingly. So if you are getting a name like "John Doe" you an split the string based upon the space character. If it is in a format such as "Doe, John" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.

What should be the package name of android app?

Package name is the reversed domain name, it is a unique name for each application on Playstore. You can't upload two apps with the same package name. You can check package name of the app from playstore url

https://play.google.com/store/apps/details?id=package_name

so you can easily check on playstore that this package name is in used by some other app or not before uploading it.

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Java foreach loop: for (Integer i : list) { ... }

One way to do that is to use a counter:

ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) { 
    ...
    if (--size == 0) {
        // Last item.
        ...
    }
}

Edit

Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for loop or the iterator, as everything you win when using the Java5 syntax will be lost in the loop itself...

for (int i = 0; i < list.size(); i++) {
    ...

    if (i == (list.size() - 1)) {
        // Last item...
    }
}

or

for (Iterator it = list.iterator(); it.hasNext(); ) {
    ...

    if (!it.hasNext()) {
        // Last item...
    }
}

Is there a way to list open transactions on SQL Server 2000 database?

DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.

An informational message is displayed if there are no active transactions in the log.

DBCC OPENTRAN

How to ignore whitespace in a regular expression subject string?

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

Django URL Redirect

In Django 1.8, this is how I did mine.

from django.views.generic.base import RedirectView

url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))

Instead of using url, you can use the pattern_name, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.

How do I create a multiline Python string with inline variables?

If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:

query = """
{{
  pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
    id
    txCount
    reserveUSD
    trackedReserveETH
    volumeUSD
  }}
}}
""".format(block=''.join(['{number: ', str(block), '}']))

 query = gql(query)

Make sure to escape all curly braces like I did: "{{", "}}"

Unsupported method: BaseConfig.getApplicationIdSuffix()

You can do this by changing the gradle file.

 build.gradle > change
    dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    }
    gradle-wrapper.properties > update
    distributionUrl=https://services.gradle.org/distributions/gradle-4.6-all.zip

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

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

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

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

what does -zxvf mean in tar -zxvf <filename>?

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

Getting View's coordinates relative to the root layout

The Android API already provides a method to achieve that. Try this:

Rect offsetViewBounds = new Rect();
//returns the visible bounds
childView.getDrawingRect(offsetViewBounds);
// calculates the relative coordinates to the parent
parentViewGroup.offsetDescendantRectToMyCoords(childView, offsetViewBounds); 

int relativeTop = offsetViewBounds.top;
int relativeLeft = offsetViewBounds.left;

Here is the doc

Visual Studio Code: Auto-refresh file changes

{
    "files.useExperimentalFileWatcher" : true
}

in Code -> Preferences -> Settings

Tested with Visual Studio Code Version 1.26.1 on mac and win

How to list files in an android directory?

Try these

 String appDirectoryName = getResources().getString(R.string.app_name);
    File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getResources().getString(R.string.app_name));
    directory.mkdirs();
    File[] fList = directory.listFiles();
    int a = 1;
    for (int x = 0; x < fList.length; x++) {

        //txt.setText("You Have Capture " + String.valueOf(a) + " Photos");
        a++;
    }
    //get all the files from a directory
    for (File file : fList) {
        if (file.isFile()) {
            list.add(new ModelClass(file.getName(), file.getAbsolutePath()));
        }
    }

Convert HTML to NSAttributedString in iOS

Made some modification on Andrew's solution and update the code to Swift 3:

This code now use UITextView as self and able to inherit its original font, font size and text color

Note: toHexString() is extension from here

extension UITextView {
    func setAttributedStringFromHTML(_ htmlCode: String, completionBlock: @escaping (NSAttributedString?) ->()) {
        let inputText = "\(htmlCode)<style>body { font-family: '\((self.font?.fontName)!)'; font-size:\((self.font?.pointSize)!)px; color: \((self.textColor)!.toHexString()); }</style>"

        guard let data = inputText.data(using: String.Encoding.utf16) else {
            print("Unable to decode data from html string: \(self)")
            return completionBlock(nil)
        }

        DispatchQueue.main.async {
            if let attributedString = try? NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) {
                self.attributedText = attributedString
                completionBlock(attributedString)
            } else {
                print("Unable to create attributed string from html string: \(self)")
                completionBlock(nil)
            }
        }
    }
}

Example usage:

mainTextView.setAttributedStringFromHTML("<i>Hello world!</i>") { _ in }

Get first day of week in SQL Server

CREATE FUNCTION dbo.fnFirstWorkingDayOfTheWeek
(
    @currentDate date
)
RETURNS INT
AS
BEGIN
    -- get DATEFIRST setting
    DECLARE @ds int = @@DATEFIRST 
    -- get week day number under current DATEFIRST setting
    DECLARE @dow int = DATEPART(dw,@currentDate) 

    DECLARE @wd  int =  1+(((@dow+@ds) % 7)+5) % 7  -- this is always return Mon as 1,Tue as 2 ... Sun as 7 

    RETURN DATEADD(dd,1-@wd,@currentDate) 

END

jQuery 'each' loop with JSON array

My solutions in one of my own sites, with a table:

$.getJSON("sections/view_numbers_update.php", function(data) {
 $.each(data, function(index, objNumber) {
  $('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
  $('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
  $('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
  $('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
 });
});

sections/view_numbers_update.php Returns something like:

[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]

HTML table:

<table id="table_numbers">
 <tr>
  <th>[...]</th>
  <th>[...]</th>
  <th>[...]</th>
  <th>Last Call</th>
  <th>Status</th>
  <th>Duration</th>
  <th>Human?</th>
  <th>[...]</th>
 </tr>
 <tr id="tr_123456">
  [...]
 </tr>
</table>

This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.

The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.

Can't include C++ headers like vector in Android NDK

In android NDK go to android-ndk-r9b>/sources/cxx-stl/gnu-libstdc++/4.X/include in linux machines

I've found solution from the below link http://osdir.com/ml/android-ndk/2011-09/msg00336.html

The ternary (conditional) operator in C

The same as

if(0)
do();


if(0)
{
do();
}

How to delete parent element using jQuery

$('#' + catId).parent().remove('.subcatBtns');

How to handle the `onKeyPress` event in ReactJS?

You need to call event.persist(); this method on your keyPress event. Example:

const MyComponent = (props) => {
   const keyboardEvents = (event) =>{
       event.persist();
       console.log(event.key); // this will return string of key name like 'Enter'
   }
   return(
         <div onKeyPress={keyboardEvents}></div>
   )
}

If you now type console.log(event) in keyboardEvents function you will get other attributes like:

keyCode // number
charCode // number
shiftKey // boolean
ctrlKey // boolean
altKey // boolean

And many other attributes

Thanks & Regards

P.S: React Version : 16.13.1

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

cat /proc/meminfo | grep MemTotal or free gives you the exact amount of RAM your server has. This is not "available memory".

I guess your issue comes up when you have a VM and you would like to calculate the full amount of memory hosted by the hypervisor but you will have to log into the hypervisor in that case.

cat /proc/meminfo | grep MemTotal

is equivalent to

 getconf -a | grep PAGES | awk 'BEGIN {total = 1} {if (NR == 1 || NR == 3) total *=$NF} END {print total / 1024" kB"}'

How to detect scroll position of page using jQuery

Now that works for me...

$(document).ready(function(){

    $(window).resize(function(e){
        console.log(e);                   
    });

    $(window).scroll(function (event) {
        var sc = $(window).scrollTop();
        console.log(sc);
    });

})

it works well... and then you can use JQuery/TweenMax to track elements and control them.

How to get previous month and year relative to today, using strtotime and date?

Have a look at the DateTime class. It should do the calculations correctly and the date formats are compatible with strttotime. Something like:

$datestring='2011-03-30 first day of last month';
$dt=date_create($datestring);
echo $dt->format('Y-m'); //2011-02

How to subtract days from a plain Date?

_x000D_
_x000D_
var date = new Date();_x000D_
var day = date.getDate();_x000D_
var mnth = date.getMonth() + 1;_x000D_
_x000D_
var fDate = day + '/' + mnth + '/' + date.getFullYear();_x000D_
document.write('Today is: ' + fDate);_x000D_
var subDate = date.setDate(date.getDate() - 1);_x000D_
var todate = new Date(subDate);_x000D_
var today = todate.getDate();_x000D_
var tomnth = todate.getMonth() + 1;_x000D_
var endDate = today + '/' + tomnth + '/' + todate.getFullYear();_x000D_
document.write('<br>1 days ago was: ' + endDate );
_x000D_
_x000D_
_x000D_

How to position two elements side by side using CSS

You have two options, either float:left or display:inline-block.

Both methods have their caveats. It seems that display:inline-block is more common nowadays, as it avoids some of the issues of floating.

Read this article http://designshack.net/articles/css/whats-the-deal-with-display-inline-block/ or this one http://www.vanseodesign.com/css/inline-blocks/ for a more in detail discussion.

CSS align images and text on same line

try to insert your img inside your h4 DEMO

<h4 class='liketext'><img style='height: 24px; width: 24px; margin-right: 4px;' src='design/like.png'/>$likes</h4>
<h4 class='liketext'> <img style='height: 24px; width: 24px; margin-right: 4px;' src='design/dislike.png'/>$dislikes</h4>?

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

Get average color of image via Javascript

First: it can be done without HTML5 Canvas or SVG.
Actually, someone just managed to generate client-side PNG files using JavaScript, without canvas or SVG, using the data URI scheme.

Second: you might actually not need Canvas, SVG or any of the above at all.
If you only need to process images on the client side, without modifying them, all this is not needed.

You can get the source address from the img tag on the page, make an XHR request for it - it will most probably come from the browser cache - and process it as a byte stream from Javascript.
You will need a good understanding of the image format. (The above generator is partially based on libpng sources and might provide a good starting point.)

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...
});

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox
    });
});

Here is demo in JSFiddle.


And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');
        }
    });
});

Two decimal places using printf( )

What you want is %.2f, not 2%f.

Also, you might want to replace your %d with a %f ;)

#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}

This will output:

When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

See here for a full description of the printf formatting options: printf

std::cin input with spaces?

Use :

getline(cin, input);

the function can be found in

#include <string>

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

How can I execute a python script from an html button?

Since you asked for a way to complete this within an HTML page I am answering this. I feel there is no need to mention the severe warnings and implications that would go along with this .. I trust you know the security of your .py script better than I do :-)

I would use the .ajax() function in the jQuery library. This will allow you to call your Python script as long as the script is in the publicly accessible html directory ... That said this is the part where I tell you to heed security precautions ...

<!DOCTYPE html>
<html>
  <head>    
  </head>
  <body>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
        function goPython(){
            $.ajax({
              url: "MYSCRIPT.py",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>

In addition .. It's worth noting that your script is going to have to have proper permissions for, say, the www-data user to be able to run it ... A chmod, and/or a chown may be necessary.

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

Hide html horizontal but not vertical scrollbar

.combobox_selector ul {
    padding: 0;
    margin: 0;
    list-style: none;
    border:1px solid #CCC;
    height: 200px;
    overflow: auto;
    overflow-x: hidden;
}

sets 200px scrolldown size, overflow-x hides any horizontal scrollbar.

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

How to get the class of the clicked element?

$("li").click(function(){
    alert($(this).attr("class"));
});

REST API - Bulk Create or Update in single request

I think that you could use a POST or PATCH method to handle this since they typically design for this.

  • Using a POST method is typically used to add an element when used on list resource but you can also support several actions for this method. See this answer: How to Update a REST Resource Collection. You can also support different representation formats for the input (if they correspond to an array or a single elements).

    In the case, it's not necessary to define your format to describe the update.

  • Using a PATCH method is also suitable since corresponding requests correspond to a partial update. According to RFC5789 (http://tools.ietf.org/html/rfc5789):

    Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

    In the case, you have to define your format to describe the partial update.

I think that in this case, POST and PATCH are quite similar since you don't really need to describe the operation to do for each element. I would say that it depends on the format of the representation to send.

The case of PUT is a bit less clear. In fact, when using a method PUT, you should provide the whole list. As a matter of fact, the provided representation in the request will be in replacement of the list resource one.

You can have two options regarding the resource paths.

  • Using the resource path for doc list

In this case, you need to explicitely provide the link of docs with a binder in the representation you provide in the request.

Here is a sample route for this /docs.

The content of such approach could be for method POST:

[
    { "doc_number": 1, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 2, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 3, "binder": 5, (other fields in the case of creation) },
    (...)
]
  • Using sub resource path of binder element

In addition you could also consider to leverage sub routes to describe the link between docs and binders. The hints regarding the association between a doc and a binder doesn't have now to be specified within the request content.

Here is a sample route for this /binder/{binderId}/docs. In this case, sending a list of docs with a method POST or PATCH will attach docs to the binder with identifier binderId after having created the doc if it doesn't exist.

The content of such approach could be for method POST:

[
    { "doc_number": 1, (other fields in the case of creation) },
    { "doc_number": 2, (other fields in the case of creation) },
    { "doc_number": 3, (other fields in the case of creation) },
    (...)
]

Regarding the response, it's up to you to define the level of response and the errors to return. I see two levels: the status level (global level) and the payload level (thinner level). It's also up to you to define if all the inserts / updates corresponding to your request must be atomic or not.

  • Atomic

In this case, you can leverage the HTTP status. If everything goes well, you get a status 200. If not, another status like 400 if the provided data aren't correct (for example binder id not valid) or something else.

  • Non atomic

In this case, a status 200 will be returned and it's up to the response representation to describe what was done and where errors eventually occur. ElasticSearch has an endpoint in its REST API for bulk update. This could give you some ideas at this level: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.

  • Asynchronous

You can also implement an asynchronous processing to handle the provided data. In this case, the HTTP status returns will be 202. The client needs to pull an additional resource to see what happens.

Before finishing, I also would want to notice that the OData specification addresses the issue regarding relations between entities with the feature named navigation links. Perhaps could you have a look at this ;-)

The following link can also help you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.

Hope it helps you, Thierry

How to hide status bar in Android

If you are hiding the status bar do this in onCreate(for Activity) and onCreateView/onViewCreated(for Fragment)

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

And don't forget to clear the flag when exiting the activity or else you will have the full screen in your whole app after visiting this activity. To clear do this in your onDestroy(for Activity) or onDestroyView(for Fragment)

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)

How to create a folder with name as current date in batch (.bat) files

You'll like this, change it so that it can suit your requirements.

mkdir today
Copy Desktop\test1\*.* today
setlocal enableextensions
set name=%DATE:/=_%
Rename "today" _OlddatabaseBackup_"%name%"

EC2 instance has no public DNS

It is related to the VPC's feature called "DNS Hostnames". You can enable or disable it. Go to the VPC, under the Actions menu select the "Edit DNS Hostnames" item and then choose "Yes". After doing so, the public DNS of the EC2 instances should be displayed.

Is there Selected Tab Changed Event in the standard WPF Tab Control

If you just want to have an event when a tab is selected, this is the correct way:

<TabControl>
    <TabItem Selector.Selected="OnTabSelected" />
    <TabItem Selector.Selected="OnTabSelected" />
    <TabItem Selector.Selected="OnTabSelected" />
    <!-- You can also catch the unselected event -->
    <TabItem Selector.Unselected="OnTabUnSelected" />
</TabControl>

And in your code

    private void OnTabSelected(object sender, RoutedEventArgs e)
    {
        var tab = sender as TabItem;
        if (tab != null)
        {
            // this tab is selected!
        }
    }

Select option padding not working in chrome

You can use font-size property for option if you need.

How to execute an oracle stored procedure?

Execute is sql*plus syntax .. try wrapping your call in begin .. end like this:

begin 
    temp_proc;
end;

(Although Jeffrey says this doesn't work in APEX .. but you're trying to get this to run in SQLDeveloper .. try the 'Run' menu there.)

How to extract string following a pattern with grep, regex or perl

If the structure of your xml (or text in general) is fixed, the easiest way is using cut. For your specific case:

echo '<table name="content_analyzer" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer2" primary-key="id">
  <type="global" />
</table>
<table name="content_analyzer_items" primary-key="id">
  <type="global" />
</table>' | grep name= | cut -f2 -d '"'

Tracking CPU and Memory usage per process

Just type perfmon into Start > Run and press enter. When the Performance window is open, click on the + sign to add new counters to the graph. The counters are different aspects of how your PC works and are grouped by similarity into groups called "Performance Object".

For your questions, you can choose the "Process", "Memory" and "Processor" performance objects. You then can see these counters in real time

You can also specify the utility to save the performance data for your inspection later. To do this, select "Performance Logs and Alerts" in the left-hand panel. (It's right under the System Monitor console which provides us with the above mentioned counters. If it is not there, click "File" > "Add/remove snap-in", click Add and select "Performance Logs and Alerts" in the list".) From the "Performance Logs and Alerts", create a new monitoring configuration under "Counter Logs". Then you can add the counters, specify the sampling rate, the log format (binary or plain text) and log location.

Flutter position stack widget in center

The Problem is the Container that gets the smallest possible size.

Just give a width: to the Container (in red) and you are done.

width: MediaQuery.of(context).size.width

enter image description here

  new Positioned(
  bottom: 0.0,
  child: new Container(
    width: MediaQuery.of(context).size.width,
    color: Colors.red,
    margin: const EdgeInsets.all(0.0),
    child: new Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        new Align(
          alignment: Alignment.bottomCenter,
          child: new ButtonBar(
            alignment: MainAxisAlignment.center,
            children: <Widget>[
              new OutlineButton(
                onPressed: null,
                child: new Text(
                  "Login",
                  style: new TextStyle(color: Colors.white),
                ),
              ),
              new RaisedButton(
                color: Colors.white,
                onPressed: null,
                child: new Text(
                  "Register",
                  style: new TextStyle(color: Colors.black),
                ),
              )
            ],
          ),
        )
      ],
    ),
  ),
),

Animate text change in UILabel

This is a C# UIView extension method that's based on @SwiftArchitect's code. When auto layout is involved and controls need to move depending on the label's text, this calling code uses the Superview of the label as the transition view instead of the label itself. I added a lambda expression for the action to make it more encapsulated.

public static void FadeTransition( this UIView AView, double ADuration, Action AAction )
{
  CATransition transition = new CATransition();

  transition.Duration = ADuration;
  transition.TimingFunction = CAMediaTimingFunction.FromName( CAMediaTimingFunction.Linear );
  transition.Type = CATransition.TransitionFade;

  AView.Layer.AddAnimation( transition, transition.Type );
  AAction();
}

Calling code:

  labelSuperview.FadeTransition( 0.5d, () =>
  {
    if ( condition )
      label.Text = "Value 1";
    else
      label.Text = "Value 2";
  } );

Plot correlation matrix using pandas

Along with other methods it is also good to have pairplot which will give scatter plot for all the cases-

import pandas as pd
import numpy as np
import seaborn as sns
rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
sns.pairplot(df)

Converting any string into camel case

If regexp isn't required, you might want to look at following code I made a long time ago for Twinkle:

String.prototype.toUpperCaseFirstChar = function() {
    return this.substr( 0, 1 ).toUpperCase() + this.substr( 1 );
}

String.prototype.toLowerCaseFirstChar = function() {
    return this.substr( 0, 1 ).toLowerCase() + this.substr( 1 );
}

String.prototype.toUpperCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toUpperCaseFirstChar() } ).join( delim );
}

String.prototype.toLowerCaseEachWord = function( delim ) {
    delim = delim ? delim : ' ';
    return this.split( delim ).map( function(v) { return v.toLowerCaseFirstChar() } ).join( delim );
}

I haven't made any performance tests, and regexp versions might or might not be faster.

PHP check whether property exists in object or class

If you want to know if a property exists in an instance of a class that you have defined, simply combine property_exists() with isset().

public function hasProperty($property)
{
    return property_exists($this, $property) && isset($this->$property);
}

Easy way to test an LDAP User's Credentials

ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>, where binddn is the DN of the person whose credentials you are authenticating.

On success (i.e., valid credentials), you get Result: Success (0). On failure, you get ldap_bind: Invalid credentials (49).

Query-string encoding of a Javascript Object

This is a solution that will work for .NET backends out of the box. I have taken the primary answer of this thread and updated it to fit our .NET needs.

function objectToQuerystring(params) {
var result = '';

    function convertJsonToQueryString(data, progress, name) {
        name = name || '';
        progress = progress || '';
        if (typeof data === 'object') {
            Object.keys(data).forEach(function (key) {
                var value = data[key];
                if (name == '') {
                    convertJsonToQueryString(value, progress, key);
                } else {
                    if (isNaN(parseInt(key))) {
                        convertJsonToQueryString(value, progress, name + '.' + key);
                    } else {
                        convertJsonToQueryString(value, progress, name + '[' + key+ ']');
                    }
                }
            })
        } else {
            result = result ? result.concat('&') : result.concat('?');
            result = result.concat(`${name}=${data}`);
        }
    }

    convertJsonToQueryString(params);
    return result;
}

Conditional Logic on Pandas DataFrame

In [34]: import pandas as pd

In [35]: import numpy as np

In [36]:  df = pd.DataFrame([1,2,3,4], columns=["data"])

In [37]: df
Out[37]: 
   data
0     1
1     2
2     3
3     4

In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")

In [39]: df
Out[39]: 
   data desired_output
0     1          False
1     2          False
2     3           True
3     4           True

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

How to include PHP files that require an absolute path?

I think the best way is to put your includes in your PHP include path. There are various ways to do this depending on your setup.

Then you can simply refer to

require_once 'inc1.php';

from inside any file regardless of where it is whether in your includes or in your web accessible files, or any level of nested subdirectories.

This allows you to have your include files outside the web server root, which is a best practice.

e.g.

site directory
    html (web root)
        your web-accessible files
    includes
        your include files

Also, check out __autoload for lazy loading of class files

http://www.google.com/search?q=setting+php+include+path

http://www.google.com/search?q=__autoload

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)

How to set initial value and auto increment in MySQL?

MySQL - Setup an auto-incrementing primary key that starts at 1001:

Step 1, create your table:

create table penguins(
  my_id       int(16) auto_increment, 
  skipper     varchar(4000),
  PRIMARY KEY (my_id)
)

Step 2, set the start number for auto increment primary key:

ALTER TABLE penguins AUTO_INCREMENT=1001;

Step 3, insert some rows:

insert into penguins (skipper) values("We need more power!");
insert into penguins (skipper) values("Time to fire up");
insert into penguins (skipper) values("kowalski's nuclear reactor.");

Step 4, interpret the output:

select * from penguins

prints:

'1001', 'We need more power!'
'1002', 'Time to fire up'
'1003', 'kowalski\'s nuclear reactor'

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

After not able to find a good universal solution I made something of my own. I have not tested it for a very large list.

It takes care of nested keys,arrays or just about anything.

Here is the github and demo

app.filter('xf', function() {
    function keyfind(f, obj) {
        if (obj === undefined)
            return -1;
        else {
            var sf = f.split(".");
            if (sf.length <= 1) {
                return obj[sf[0]];
            } else {
                var newobj = obj[sf[0]];
                sf.splice(0, 1);
                return keyfind(sf.join("."), newobj)
            }
        }

    }
    return function(input, clause, fields) {
        var out = [];
        if (clause && clause.query && clause.query.length > 0) {
            clause.query = String(clause.query).toLowerCase();
            angular.forEach(input, function(cp) {
                for (var i = 0; i < fields.length; i++) {
                    var haystack = String(keyfind(fields[i], cp)).toLowerCase();
                    if (haystack.indexOf(clause.query) > -1) {
                        out.push(cp);
                        break;
                    }
                }
            })
        } else {
            angular.forEach(input, function(cp) {
                out.push(cp);
            })
        }
        return out;
    }

})

HTML

<input ng-model="search.query" type="text" placeholder="search by any property">
<div ng-repeat="product in products |  xf:search:['color','name']">
...
</div>

What does void mean in C, C++, and C#?

It means "no value". You use void to indicate that a function doesn't return a value or that it has no parameters or both.It's much consistent with typical uses of word void in English.

Void should not be confused with null. Null means for the variable whose address is on stack, the value on the heap for that address is empty.

Examples of GoF Design Patterns in Java's core libraries

java.util.Collection#Iterator is a good example of a Factory Method. Depending on the concrete subclass of Collection you use, it will create an Iterator implementation. Because both the Factory superclass (Collection) and the Iterator created are interfaces, it is sometimes confused with AbstractFactory. Most of the examples for AbstractFactory in the the accepted answer (BalusC) are examples of Factory, a simplified version of Factory Method, which is not part of the original GoF patterns. In Facory the Factory class hierarchy is collapsed and the factory uses other means to choose the product to be returned.

  • Abstract Factory

An abstract factory has multiple factory methods, each creating a different product. The products produced by one factory are intended to be used together (your printer and cartridges better be from the same (abstract) factory). As mentioned in answers above the families of AWT GUI components, differing from platform to platform, are an example of this (although its implementation differs from the structure described in Gof).

Extract substring in Bash

Here's a prefix-suffix solution (similar to the solutions given by JB and Darron) that matches the first block of digits and does not depend on the surrounding underscores:

str='someletters_12345_morele34ters.ext'
s1="${str#"${str%%[[:digit:]]*}"}"   # strip off non-digit prefix from str
s2="${s1%%[^[:digit:]]*}"            # strip off non-digit suffix from s1
echo "$s2"                           # 12345

How do I show the schema of a table in a MySQL database?

describe [db_name.]table_name;

for formatted output, or

show create table [db_name.]table_name;

for the SQL statement that can be used to create a table.

How to implement band-pass Butterworth filter with Scipy.signal.butter

You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high] (expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band".

Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.

from scipy.signal import butter, lfilter


def butter_bandpass(lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a


def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
    b, a = butter_bandpass(lowcut, highcut, fs, order=order)
    y = lfilter(b, a, data)
    return y


if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import freqz

    # Sample rate and desired cutoff frequencies (in Hz).
    fs = 5000.0
    lowcut = 500.0
    highcut = 1250.0

    # Plot the frequency response for a few different orders.
    plt.figure(1)
    plt.clf()
    for order in [3, 6, 9]:
        b, a = butter_bandpass(lowcut, highcut, fs, order=order)
        w, h = freqz(b, a, worN=2000)
        plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)

    plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
             '--', label='sqrt(0.5)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.legend(loc='best')

    # Filter a noisy signal.
    T = 0.05
    nsamples = T * fs
    t = np.linspace(0, T, nsamples, endpoint=False)
    a = 0.02
    f0 = 600.0
    x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
    x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
    x += a * np.cos(2 * np.pi * f0 * t + .11)
    x += 0.03 * np.cos(2 * np.pi * 2000 * t)
    plt.figure(2)
    plt.clf()
    plt.plot(t, x, label='Noisy signal')

    y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
    plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
    plt.xlabel('time (seconds)')
    plt.hlines([-a, a], 0, T, linestyles='--')
    plt.grid(True)
    plt.axis('tight')
    plt.legend(loc='upper left')

    plt.show()

Here are the plots that are generated by this script:

Frequency response for several filter orders

enter image description here

Removing "bullets" from unordered list <ul>

Try this it works

<ul class="sub-menu" type="none">
           <li class="sub-menu-list" ng-repeat="menu in list.components">
               <a class="sub-menu-link">
                   {{ menu.component }}
               </a>
           </li>
        </ul>

Setting the classpath in java using Eclipse IDE

Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project

Facebook Android Generate Key Hash

The right key can be obtained from the app itself by adding the following code to toast the proper key hash (in case of Facebook SDK 3.0 onwards, this works)

try {
            PackageInfo info = getPackageManager().getPackageInfo("com.package.mypackage",         PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String sign=Base64.encodeToString(md.digest(), Base64.DEFAULT);
                Log.e("MY KEY HASH:", sign);
                Toast.makeText(getApplicationContext(),sign,         Toast.LENGTH_LONG).show();
            }
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}

Replace com.package.mypackage with your package name

How to create multiple class objects with a loop in python?

you can use list to define it.

objs = list()
for i in range(10):
    objs.append(MyClass())

How to see full query from SHOW PROCESSLIST

SHOW FULL PROCESSLIST

If you don't use FULL, "only the first 100 characters of each statement are shown in the Info field".

When using phpMyAdmin, you should also click on the "Full texts" option ("? T ?" on top left corner of a results table) to see untruncated results.

Call child component method from parent class - Angular

This Worked for me ! For Angular 2 , Call child component method in parent component

Parent.component.ts

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ChildComponent } from '../child/child'; 
    @Component({ 
               selector: 'parent-app', 
               template: `<child-cmp></child-cmp>` 
              }) 
    export class parentComponent implements OnInit{ 
        @ViewChild(ChildComponent ) child: ChildComponent ; 

        ngOnInit() { 
           this.child.ChildTestCmp(); } 
}

Child.component.ts

import { Component } from '@angular/core';
@Component({ 
  selector: 'child-cmp', 
  template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> ` 
})
export class ChildComponent {
  test: string;
  ChildTestCmp() 
  { 
    this.test = "I am child component!"; 
  }
 }

Difference between Relative path and absolute path in javascript

Completely relative:

<img src="kitten.png"/>

this is a relative path indeed.

Absolute in all respects:

<img src="http://www.foo.com/images/kitten.png"/>

this is a URL, and it can be seen in some way as an absolute path, but it's not representative for this matter.

The difference between relative and absolute paths is that when using relative paths you take as reference the current working directory while with absolute paths you refer to a certain, well known directory. Relative paths are useful when you make some program that has to use resources from certain folders that can be opened using the working directory as a starting point.

Example of relative paths:

  • image.png, which is the equivalent to .\image.png (in Windows) or ./image.png (anywhere else). The . explicitly specifies that you're expressing a path relative to the current working directory, but this is implied whenever the path doesn't begin at a root directory (designated with a slash), so you don't have to use it necessarily (except in certain contexts where a default directory (or a list of directories to search) will be applied unless you explicitly specify some directory).

  • ..\images\image2.jpg This way you can access resources from directories one step up the folders tree.  The ..\ means you've exited the current folder, entering the directory that contains both the working and images folders.  Again, use \ in Windows and / anywhere else.

Example of absolute paths:

  • D:\documents\something.doc
  • E:\music\good_music.mp3

and so on.

Best practices for API versioning?

The URL should NOT contain the versions. The version has nothing to do with "idea" of the resource you are requesting. You should try to think of the URL as being a path to the concept you would like - not how you want the item returned. The version dictates the representation of the object, not the concept of the object. As other posters have said, you should be specifying the format (including version) in the request header.

If you look at the full HTTP request for the URLs which have versions, it looks like this:

(BAD WAY TO DO IT):

http://company.com/api/v3.0/customer/123
====>
GET v3.0/customer/123 HTTP/1.1
Accept: application/xml

<====
HTTP/1.1 200 OK
Content-Type: application/xml
<customer version="3.0">
  <name>Neil Armstrong</name>
</customer>

The header contains the line which contains the representation you are asking for ("Accept: application/xml"). That is where the version should go. Everyone seems to gloss over the fact that you may want the same thing in different formats and that the client should be able ask for what it wants. In the above example, the client is asking for ANY XML representation of the resource - not really the true representation of what it wants. The server could, in theory, return something completely unrelated to the request as long as it was XML and it would have to be parsed to realize it is wrong.

A better way is:

(GOOD WAY TO DO IT)

http://company.com/api/customer/123
===>
GET /customer/123 HTTP/1.1
Accept: application/vnd.company.myapp.customer-v3+xml

<===
HTTP/1.1 200 OK
Content-Type: application/vnd.company.myapp-v3+xml
<customer>
  <name>Neil Armstrong</name>
</customer>

Further, lets say the clients think the XML is too verbose and now they want JSON instead. In the other examples you would have to have a new URL for the same customer, so you would end up with:

(BAD)
http://company.com/api/JSONv3.0/customers/123
  or
http://company.com/api/v3.0/customers/123?format="JSON"

(or something similar). When in fact, every HTTP requests contains the format you are looking for:

(GOOD WAY TO DO IT)
===>
GET /customer/123 HTTP/1.1
Accept: application/vnd.company.myapp.customer-v3+json

<===
HTTP/1.1 200 OK
Content-Type: application/vnd.company.myapp-v3+json

{"customer":
  {"name":"Neil Armstrong"}
}

Using this method, you have much more freedom in design and are actually adhering to the original idea of REST. You can change versions without disrupting clients, or incrementally change clients as the APIs are changed. If you choose to stop supporting a representation, you can respond to the requests with HTTP status code or custom codes. The client can also verify the response is in the correct format, and validate the XML.

There are many other advantages and I discuss some of them here on my blog: http://thereisnorightway.blogspot.com/2011/02/versioning-and-types-in-resthttp-api.html

One last example to show how putting the version in the URL is bad. Lets say you want some piece of information inside the object, and you have versioned your various objects (customers are v3.0, orders are v2.0, and shipto object is v4.2). Here is the nasty URL you must supply in the client:

(Another reason why version in the URL sucks)
http://company.com/api/v3.0/customer/123/v2.0/orders/4321/

Go to particular revision

One way would be to create all commits ever made to patches. checkout the initial commit and then apply the patches in order after reading.

use git format-patch <initial revision> and then git checkout <initial revision>. you should get a pile of files in your director starting with four digits which are the patches.

when you are done reading your revision just do git apply <filename> which should look like git apply 0001-* and count.

But I really wonder why you wouldn't just want to read the patches itself instead? Please post this in your comments because I'm curious.

the git manual also gives me this:

git show next~10:Documentation/README

Shows the contents of the file Documentation/README as they were current in the 10th last commit of the branch next.

you could also have a look at git blame filename which gives you a listing where each line is associated with a commit hash + author.

How do I concatenate text in a query in sql server?

If you are using SQL Server 2005 or greater, depending on the size of the data in the Notes field, you may want to consider casting to nvarchar(max) instead of casting to a specific length which could result in string truncation.

Select Cast(notes as nvarchar(max)) + 'SomeText' From NotesTable a

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

How can one tell the version of React running at runtime in the browser?

From command line to view react version, npm view react version

How to validate phone numbers using regex

Have you had a look over at RegExLib?

Entering US phone number brought back quite a list of possibilities.

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

How Many Seconds Between Two Dates?

I'm taking YYYY & ZZZZ to mean integer values which mean the year, MM & NN to mean integer values meaning the month of the year and DD & EE as integer values meaning the day of the month.

var t1 = new Date(YYYY, MM, DD, 0, 0, 0, 0);
var t2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0);
var dif = t1.getTime() - t2.getTime();

var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);

A handy source for future reference is the MDN site

Alternatively, if your dates come in a format javascript can parse

var dif = Date.parse(MM + " " + DD + ", " + YYYY) - Date.parse(NN + " " + EE + ", " + ZZZZ);

and then you can use that value as the difference in milliseconds (dif in both my examples has the same meaning)

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

Getting the IP Address of a Remote Socket Endpoint

RemoteEndPoint is a property, its type is System.Net.EndPoint which inherits from System.Net.IPEndPoint.

If you take a look at IPEndPoint's members, you'll see that there's an Address property.

How to access the php.ini from my CPanel?

In cPanel search for php, You will find "Select PHP version" under Software.

Software -> Select PHP Version -> Switch to Php Options -> Change Value -> save.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

This is LITERALLY 1 google query away, but here goes:

http://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx

Understanding legacy document modes

Use the following value to display the webpage in edge mode, which is the highest standards mode supported by Internet Explorer, from Internet Explorer 6 through IE11.

<meta http-equiv="x-ua-compatible" content="IE=edge"

Note that this is functionally equivalent to using the HTML5 doctype. It places Internet Explorer into the highest supported document mode. Edge most is most useful for regularly maintained websites that are routinely tested for interoperability between multiple browsers, including Internet Explorer.

Note Starting with IE11, edge mode is considered the preferred document mode. (In earlier versions, it was considered experimental.) To learn more, see Document modes are deprecated. Starting with Windows Internet Explorer 8, some web developers used the edge mode meta element to hide the Compatibility View button on the address bar. As of IE11, this is no longer necessary as the button has been removed from the address bar. Because it forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use edge mode for all pages viewed with Internet Explorer. Don't do this, as the X-UA-Compatible header is only supported starting with Internet Explorer 8.

Tip If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration, as shown in the earlier example.

Also among the search results is:

Capture iframe load complete event

Neither of the above answers worked for me, however this did

UPDATE:

As @doppleganger pointed out below, load is gone as of jQuery 3.0, so here's an updated version that uses on. Please note this will actually work on jQuery 1.7+, so you can implement it this way even if you're not on jQuery 3.0 yet.

$('iframe').on('load', function() {
    // do stuff 
});

Where does Android emulator store SQLite database?

I wrote a simple bash script, which pulls database from android device to your computer (Linux, Mac users)

filename:android_db_move.sh usage: android_db_move.sh com.example.app db_name.db

#!/bin/bash

REQUIRED_ARGS=2
ADB_PATH=/Users/Tadas/Library/sdk/platform-tools/adb
PULL_DIR="~/"

if [ $# -ne $REQUIRED_ARGS ]
    then
        echo ""
        echo "Usage:"
        echo "android_db_move.sh [package_name] [db_name]"
        echo "eg. android_db_move.sh lt.appcamp.impuls impuls.db"
        echo ""
    exit 1
fi;


echo""

cmd1="$ADB_PATH -d shell 'run-as $1 cat /data/data/$1/databases/$2 > /sdcard/$2' "
cmd2="$ADB_PATH pull /sdcard/$2 $PULL_DIR"

echo $cmd1
eval $cmd1
if [ $? -eq 0 ]
    then
    echo ".........OK"
fi;

echo $cmd2
eval $cmd2

if [ $? -eq 0 ]
    then
    echo ".........OK"
fi;

exit 0

Prevent typing non-numeric in input type number

Try it:

document.querySelector("input").addEventListener("keyup", function () {
   this.value = this.value.replace(/\D/, "")
});

Twitter bootstrap modal-backdrop doesn't disappear

the initial value of your data-backdrop attribute can be

"static","true", "false" .

static and true add the modal shadow, while false disable the shadow, so you just need to change this value with the first click to false . like this:

_x000D_
_x000D_
$(document).on('ready',function(){_x000D_
 _x000D_
 var count=0;_x000D_
 _x000D_
$('#id-which-triggers-modal').on('click',function(){_x000D_
  _x000D_
  if(count>0){_x000D_
  _x000D_
   $(this).attr('data-backdrop','false')_x000D_
  }_x000D_
  count++;_x000D_
});_x000D_
_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

How do I update/upsert a document in Mongoose?

Here's the simplest way to create/update while also calling the middleware and validators.

Contact.findOne({ phone: request.phone }, (err, doc) => {
    const contact = (doc) ? doc.set(request) : new Contact(request);

    contact.save((saveErr, savedContact) => {
        if (saveErr) throw saveErr;
        console.log(savedContact);
    });
})

Could not resolve all dependencies for configuration ':classpath'

The solution is in your build.gradle change this block:

allprojects {
  repositories {
    jcenter()
    google()
  }
}

to google in first position :

allprojects {
  repositories {
    google()
    jcenter()
  }
}

Undefined reference to main - collect2: ld returned 1 exit status

I my case I found out the void for the main function declaration was missing.

I was previously using Visual Studio in Windows and this was never a problem, so I thought I might leave it out now too.

Bootstrap center heading

just use class='text-center' in element for center heading.

<h2 class="text-center">sample center heading</h2>

use class='text-left' in element for left heading, and use class='text-right' in element for right heading.

Read response body in JAX-RS client from a post request

I also had the same issue, trying to run a unit test calling code that uses readEntity. Can't use getEntity in production code because that just returns a ByteInputStream and not the content of the body and there is no way I am adding production code that is hit only in unit tests.

My solution was to create a response and then use a Mockito spy to mock out the readEntity method:

Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);

Note that you can't use the when(mockResponse.readEntity(String.class) option because that throws the same IllegalStateException.

Hope this helps!

Sharing link on WhatsApp from mobile website (not application) for Android

The official docs say to use: wa.me. Don't use wa.me. I apologize for the length of these results, but it's been a rapidly-evolving issue....

April, 2020 Results

Share Link

This link is incorrect. Close this window and try a different link.

May, 2020 Results

Share Link GitHub Ticket: WhatsApp short link without phone number not working anymore

We couldn't find the page you were looking for

Looks like you're looking for a page that doesn't exist. Or a page we might have just deleted. Either way, go back or be sure to check the url, your spelling and try again.

August, 2020 Results

Share Link

Works as expected!

LATEST - October, 2020 Results

Share Link

(Broken again!) og:image tag previews are disabled when using wa.me.

Based on some of the comments I'm seeing, it seems like this still be an intermittent problem, so, going forward, I recommend you stick to the api.whatsapp.com URL!

If you want to share, you must absolutely use one of the two following URL formats:

https://api.whatsapp.com/send?text=YourShareTextHere
https://api.whatsapp.com/send?text=YourShareTextHere&phone=123

If you are interested in watching a project that keeps track of these URLs, then check us out!: https://github.com/bradvin/social-share-urls#telegramme

Social Share URLs

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

Why does using an Underscore character in a LIKE filter give me all the results?

Underscore is a wildcard for something. for example 'A_%' will look for all match that Start whit 'A' and have minimum 1 extra character after that

Java - using System.getProperty("user.dir") to get the home directory

way of getting home directory of current user is

String currentUsersHomeDir = System.getProperty("user.home");

and to append path separator

String otherFolder = currentUsersHomeDir + File.separator + "other";

File.separator

The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:

$.get(
    'index.php?r=admin/post/ajax',
    {"parentCatId":parentCatId},
    function(data){                     
        $.each(data, function(key, value){
            console.log(key + ":" + value)
        })
    },
    'json'
);

How to use setInterval and clearInterval?

Use setTimeout(drawAll, 20) instead. That only executes the function once.