Programs & Examples On #Kxml2

kxml2 is a parser for converting WBXML to KML and KML to WBXML

Using wget to recursively fetch a directory with arbitrary files in it

You should be able to do it simply by adding a -r

wget -r http://stackoverflow.com/

Display current date and time without punctuation

Interesting/funny way to do this using parameter expansion (requires bash 4.4 or newer):

${parameter@operator} - P operator

The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.

$ show_time() { local format='\D{%Y%m%d%H%M%S}'; echo "${format@P}"; }
$ show_time
20180724003251

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

How to check if a subclass is an instance of a class at runtime?

Class.isAssignableFrom() - works for interfaces as well. If you don't want that, you'll have to call getSuperclass() and test until you reach Object.

Access to the requested object is only available from the local network phpmyadmin

open your http.conf file

vim /opt/lampp/etc/extra/httpd-xampp.conf

Comment "Deny from all" in the following section,

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Order deny,allow
       #Deny from all
        Allow from ::1 127.0.0.0/8 \
                fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
                fe80::/10 169.254.0.0/16

        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Edit:
Try to add "Allow from all" before "ErrorDocument" line. Hope it helps.

How to load a jar file at runtime

Use org.openide.util.Lookup and ClassLoader to dynamically load the Jar plugin, as shown here.

public LoadEngine() {
    Lookup ocrengineLookup;
    Collection<OCREngine> ocrengines;
    Template ocrengineTemplate;
    Result ocrengineResults;
    try {
        //ocrengineLookup = Lookup.getDefault(); this only load OCREngine in classpath of  application
        ocrengineLookup = Lookups.metaInfServices(getClassLoaderForExtraModule());//this load the OCREngine in the extra module as well
        ocrengineTemplate = new Template(OCREngine.class);
        ocrengineResults = ocrengineLookup.lookup(ocrengineTemplate); 
        ocrengines = ocrengineResults.allInstances();//all OCREngines must implement the defined interface in OCREngine. Reference to guideline of implement org.openide.util.Lookup for more information

    } catch (Exception ex) {
    }
}

public ClassLoader getClassLoaderForExtraModule() throws IOException {

    List<URL> urls = new ArrayList<URL>(5);
    //foreach( filepath: external file *.JAR) with each external file *.JAR, do as follows
    File jar = new File(filepath);
    JarFile jf = new JarFile(jar);
    urls.add(jar.toURI().toURL());
    Manifest mf = jf.getManifest(); // If the jar has a class-path in it's manifest add it's entries
    if (mf
            != null) {
        String cp =
                mf.getMainAttributes().getValue("class-path");
        if (cp
                != null) {
            for (String cpe : cp.split("\\s+")) {
                File lib =
                        new File(jar.getParentFile(), cpe);
                urls.add(lib.toURI().toURL());
            }
        }
    }
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    if (urls.size() > 0) {
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
    }
    return cl;
}

python pandas dataframe columns convert to dict key and value

With pandas it can be done as:

If lakes is your DataFrame:

area_dict = lakes.to_dict('records')

A generic error occurred in GDI+, JPEG Image to MemoryStream

One other cause of this error and that solve my problème is that your application doesn't have a write permission on some directory.

so to complete the answer of savindra : https://stackoverflow.com/a/7426516/6444829.

Here is how you Grant File Access to IIS_IUSERS

To provide access to an ASP.NET application, you must grant access to the IIs_IUSERS.

To grant read, write, and modify permissions to a specific File or Folder

  1. In Windows Explorer, locate and select the required file.

  2. Right click the file, and then click Properties.

  3. In the Properties dialog box, click the Security tab.

  4. On the Security tab, examine the list of users. (If your application is running as a Network Service, add the network service account in the list and grant it the permission.

  5. In the Properties dialog box, click IIs_IUSERS, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.

  6. Click Apply, and then click OK.

this worked for me in my IIS of windows server 2016 and local IIS windows 10.

Getting value of HTML text input

Depends on where you want to use the email. If it's on the client side, without sending it to a PHP script, JQuery (or javascript) can do the trick.

I've created a fiddle to explain the same - http://jsfiddle.net/qHcpR/

It has an alert which goes off on load and when you click the textbox itself.

Delete files older than 15 days using PowerShell

Another alternative (15. gets typed to [timespan] automatically):

ls -file | where { (get-date) - $_.creationtime -gt 15. } | Remove-Item -Verbose

How to send value attribute from radio button in PHP

Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it:

The PHP code:

<?PHP
    $male_status = 'unchecked';
    $female_status = 'unchecked';

    if (isset($_POST['Submit1'])) {
         $selected_radio = $_POST['gender'];

         if ($selected_radio == 'male') {
                $male_status = 'checked';
          }else if ($selected_radio == 'female') {
                $female_status = 'checked';
          }
    }
?>

The HTML FORM code:

<FORM name ="form1" method ="post" action ="radioButton.php">
   <Input type = 'Radio' Name ='gender' value= 'male'
   <?PHP print $male_status; ?>
   >Male
   <Input type = 'Radio' Name ='gender' value= 'female' 
   <?PHP print $female_status; ?>
   >Female
   <P>
   <Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
</FORM>

How to remove unused dependencies from composer?

Just run composer install - it will make your vendor directory reflect dependencies in composer.lock file.

In other words - it will delete any vendor which is missing in composer.lock.

Please update the composer itself before running this.

Android: alternate layout xml for landscape mode

You can group your specific layout under the correct folder structure as follows.

layout-land-target_version

ie

layout-land-19 // target KitKat

likewise you can create your layouts.

Hope this will help you

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

I had a similar problem quite recently. In my case:

  1. I downloaded an artifact from some less popular Maven repo

  2. This repo dissappeared over this year

  3. Now builds fail, even if I have this artifact and its pom.xml in my local repo

Workaround:

delete _remote.repositories file in your local repo, where this artifact resides. Now the project builds.

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

How do I restart nginx only after the configuration test was successful on Ubuntu?

alias nginx.start='sudo nginx -c /etc/nginx/nginx.conf'
alias nginx.stop='sudo nginx -s stop'
alias nginx.reload='sudo nginx -s reload'
alias nginx.config='sudo nginx -t'
alias nginx.restart='nginx.config && nginx.stop && nginx.start'
alias nginx.errors='tail -250f /var/logs/nginx.error.log'
alias nginx.access='tail -250f /var/logs/nginx.access.log'
alias nginx.logs.default.access='tail -250f /var/logs/nginx.default.access.log'
alias nginx.logs.default-ssl.access='tail -250f /var/logs/nginx.default.ssl.log'

and then use commands "nginx.reload" etc..

Angular 2 Cannot find control with unspecified name attribute on formArrays

The problem for me was that I had

[formControlName]=""

Instead of

formControlName=""

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

Getting the Username from the HKEY_USERS values

  1. Open Reg HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\

  2. make a loop to get all subkeys

  3. the subkeys you are interested with are those started with [S-1-5-21-] which means user (see key name [ProfileImagePath] they are always started with a path c:\Users)

  4. Those starting with [S-1-5-21-12] are all local users

  5. Those starting with [S-1-5-21-13] are all network users [if joined to Domained network] that are previously logged on the machine.

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

How to get the browser to navigate to URL in JavaScript

Try these:

  1. window.location.href = 'http://www.google.com';
  2. window.location.assign("http://www.w3schools.com");
  3. window.location = 'http://www.google.com';

For more see this link: other ways to reload the page with JavaScript

How do I check for equality using Spark Dataframe without SQL Query?

There is another simple sql like option. With Spark 1.6 below also should work.

df.filter("state = 'TX'")

This is a new way of specifying sql like filters. For a full list of supported operators, check out this class.

Copy file remotely with PowerShell

None of the above answers worked for me. I kept getting this error:

Copy-Item : Access is denied
+ CategoryInfo          : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>   
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

So this did it for me:

netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes

Then from my host my machine in the Run box I just did this:

\\{IP address of nanoserver}\C$

Adding extra zeros in front of a number using jQuery?

function addLeadingZeros (n, length)
{
    var str = (n > 0 ? n : -n) + "";
    var zeros = "";
    for (var i = length - str.length; i > 0; i--)
        zeros += "0";
    zeros += str;
    return n >= 0 ? zeros : "-" + zeros;
}

//addLeadingZeros (1, 3) =   "001"
//addLeadingZeros (12, 3) =  "012"
//addLeadingZeros (123, 3) = "123"

jQuery how to find an element based on a data-attribute value?

I have faced the same issue while fetching elements using jQuery and data-* attribute.

so for your reference the shortest code is here:

This is my HTML Code:

<section data-js="carousel"></section>
<section></section>
<section></section>
<section data-js="carousel"></section>

This is my jQuery selector:

$('section[data-js="carousel"]');
// this will return array of the section elements which has data-js="carousel" attribute.

Read pdf files with php

You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com

Oracle Sql get only month and year in date datatype

Easiest solution is to create the column using the correct data type: DATE

For example:

  1. Create table:

    create table test_date (mydate date);

  2. Insert row:

    insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));

To get the month and year, do as follows:

select to_char(mydate, 'MM-YYYY') from test_date;

Your result will be as follows: 01-2011

Another cool function to use is "EXTRACT"

select extract(year from mydate) from test_date;

This will return: 2011

Way to create multiline comments in Bash?

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'

How to convert object to Dictionary<TKey, TValue> in C#?

    public static KeyValuePair<object, object > Cast<K, V>(this KeyValuePair<K, V> kvp)
    {
        return new KeyValuePair<object, object>(kvp.Key, kvp.Value);
    }

    public static KeyValuePair<T, V> CastFrom<T, V>(Object obj)
    {
        return (KeyValuePair<T, V>) obj;
    }

    public static KeyValuePair<object , object > CastFrom(Object obj)
    {
        var type = obj.GetType();
        if (type.IsGenericType)
        {
            if (type == typeof (KeyValuePair<,>))
            {
                var key = type.GetProperty("Key");
                var value = type.GetProperty("Value");
                var keyObj = key.GetValue(obj, null);
                var valueObj = value.GetValue(obj, null);
                return new KeyValuePair<object, object>(keyObj, valueObj);
            }
        }
        throw new ArgumentException(" ### -> public static KeyValuePair<object , object > CastFrom(Object obj) : Error : obj argument must be KeyValuePair<,>");
    }

From the OP:

Instead of converting my whole Dictionary, i decided to keep my obj dynamic the whole time. When i access the keys and values of my Dictionary with a foreach later, i use foreach(dynamic key in obj.Keys) and convert the keys and values to strings simply.

Creating a search form in PHP to search a database?

You're getting errors 'table liam does not exist' because the table's name is Liam which is not the same as liam. MySQL table names are case sensitive.

Android: How do I prevent the soft keyboard from pushing my view up?

In my case I needed the keyboard to stay hidden and just after the click of the button my layout needs to be adjusted, so I just added this command in the manifest and it got super right.

android:windowSoftInputMode="stateHidden|adjustResize"

How to get names of enum entries?

According to TypeScript documentation, we can do this via Enum with static functions.

Get Enum Name with static functions

enum myEnum { 
    entry1, 
    entry2 
}

namespace myEnum {
    export function GetmyEnumName(m: myEnum) {
      return myEnum[m];
    }
}


now we can call it like below
myEnum.GetmyEnumName(myEnum.entry1);
// result entry1 

for reading more about Enum with static function follow the below link https://basarat.gitbooks.io/typescript/docs/enums.html

How to copy data from one HDFS to another HDFS?

It's also useful to note that you can run the underlying MapReduce jobs with either the source or target cluster like so:

hadoop --config /path/to/hadoop/config distcp <src> <dst>

Using LINQ to concatenate strings

By 'super-cool LINQ way' you might be talking about the way that LINQ makes functional programming a lot more palatable with the use of extension methods. I mean, the syntactic sugar that allows functions to be chained in a visually linear way (one after the other) instead of nesting (one inside the other). For example:

int totalEven = Enumerable.Sum(Enumerable.Where(myInts, i => i % 2 == 0));

can be written like this:

int totalEven = myInts.Where(i => i % 2 == 0).Sum();

You can see how the second example is easier to read. You can also see how more functions can be added with less of the indentation problems or the Lispy closing parens appearing at the end of the expression.

A lot of the other answers state that the String.Join is the way to go because it is the fastest or simplest to read. But if you take my interpretation of 'super-cool LINQ way' then the answer is to use String.Join but have it wrapped in a LINQ style extension method that will allow you to chain your functions in a visually pleasing way. So if you want to write sa.Concatenate(", ") you just need to create something like this:

public static class EnumerableStringExtensions
{
   public static string Concatenate(this IEnumerable<string> strings, string separator)
   {
      return String.Join(separator, strings);
   }
}

This will provide code that is as performant as the direct call (at least in terms of algorithm complexity) and in some cases may make the code more readable (depending on the context) especially if other code in the block is using the chained function style.

is the + operator less performant than StringBuffer.append()

As far I know, every concatenation implies a memory reallocation. So the problem is not the operator used to do it, the solution is to reduce the number of concatenations. For example do the concatenations outside of the iteration structures when you can.

Creating a PHP header/footer

Just create the header.php file, and where you want to use it do:

<?php
include('header.php');
?>

Same with the footer. You don't need php tags in these files if you just have html.

See more about include here:

http://php.net/manual/en/function.include.php

Making a cURL call in C#

Don't forget to add System.Net.Http, specially if you receive this error:

Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?) 1_default.aspx D:\Projetos\Testes\FacebookAPI\FB-CustomAudience\default.aspx.cs 56 Active

In this case you shoud:

  1. Add System.Net.Http from Nuget: Tools / NuGet Package Manager / Manager NuGet Packages for Solution;
  2. Search for System.Net.Http
  3. Add in the top of your page the follow code: using System.Net.Http;

Using Python's list index() method on a list of tuples or objects?

I guess the following is not the best way to do it (speed and elegance concerns) but well, it could help :

from collections import OrderedDict as od
t = [('pineapple', 5), ('cherry', 7), ('kumquat', 3), ('plum', 11)]
list(od(t).keys()).index('kumquat')
2
list(od(t).values()).index(7)
7
# bonus :
od(t)['kumquat']
3

list of tuples with 2 members can be converted to ordered dict directly, data structures are actually the same, so we can use dict method on the fly.

jquery draggable: how to limit the draggable area?

$(function() { $( "#draggable" ).draggable({ containment: "window" }); });

of this code does not display. Full code and Demo: http://www.limitsizbilgi.com/div-tasima-surukle-birak-div-drag-and-drop-jquery.html

In order to limit the element inside its parent:

$( "#draggable" ).draggable({ containment: "window" });

How to replace ${} placeholders in a text file?

I found this thread while wondering the same thing. It inspired me to this (careful with the backticks)

$ echo $MYTEST
pass!
$ cat FILE
hello $MYTEST world
$ eval echo `cat FILE`
hello pass! world

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Use Set in Python

>>> a = [2,4]
>>> b = [1,4,3]
>>> set(a) - set(b)
set([2])

Changing navigation title programmatically

In Swift 4:

Swift 4

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Your title"
}

I hope it helps, regards!

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

How does the FetchMode work in Spring Data JPA

First of all, @Fetch(FetchMode.JOIN) and @ManyToOne(fetch = FetchType.LAZY) are antagonistic because @Fetch(FetchMode.JOIN) is equivalent to the JPA FetchType.EAGER.

Eager fetching is rarely a good choice, and for predictable behavior, you are better off using the query-time JOIN FETCH directive:

public interface PlaceRepository extends JpaRepository<Place, Long>, PlaceRepositoryCustom {

    @Query(value = "SELECT p FROM Place p LEFT JOIN FETCH p.author LEFT JOIN FETCH p.city c LEFT JOIN FETCH c.state where p.id = :id")
    Place findById(@Param("id") int id);
}

public interface CityRepository extends JpaRepository<City, Long>, CityRepositoryCustom { 
    @Query(value = "SELECT c FROM City c LEFT JOIN FETCH c.state where c.id = :id")   
    City findById(@Param("id") int id);
}

How to define two angular apps / modules in one page?

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. -- http://docs.angularjs.org/api/ng.directive:ngApp

See also

android image button

You just use an ImageButton and make the background whatever you want and set the icon as the src.

<ImageButton
    android:id="@+id/ImageButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/album_icon"
    android:background="@drawable/round_button" />

enter image description here

In C# check that filename is *possibly* valid (not that it exists)

Even if the filename is valid, you may still want to touch it to be sure the user has permission to write.

If you won't be thrashing the disk with hundreds of files in a short period of time, I think creating an empty file is a reasonable approach.

If you really want something lighter, like just checking for invalid chars, then compare your filename against Path.GetInvalidFileNameChars().

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

HTML/CSS: how to put text both right and left aligned in a paragraph

The only half-way proper way to do this is

<p>
  <span style="float: right">Text on the right</span>
  <span style="float: left">Text on the left</span>
</p> 

however, this will get you into trouble if the text overflows. If you can, use divs (block level elements) and give them a fixed width.

A table (or a number of divs with the according display: table / table-row / table-cell properties) would in fact be the safest solution for this - it will be impossible to break, even if you have lots of difficult content.

How to add "required" attribute to mvc razor viewmodel text input editor

A newer way to do this in .NET Core is with TagHelpers.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro

Building on these examples (MaxLength, Label), you can extend the existing TagHelper to suit your needs.

RequiredTagHelper.cs

using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;

namespace ProjectName.TagHelpers
{
    [HtmlTargetElement("input", Attributes = "asp-for")]
    public class RequiredTagHelper : TagHelper
    {
        public override int Order
        {
            get { return int.MaxValue; }
        }

        [HtmlAttributeName("asp-for")]
        public ModelExpression For { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output); 

            if (context.AllAttributes["required"] == null)
            {
                var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
                if (isRequired)
                {
                    var requiredAttribute = new TagHelperAttribute("required");
                    output.Attributes.Add(requiredAttribute);
                }
            }
        }
    }
}

You'll then need to add it to be used in your views:

_ViewImports.cshtml

@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"

Given the following model:

Foo.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace ProjectName.Models
{
    public class Foo
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "Full Name")]
        public string Name { get; set; }
    }
}

and view (snippet):

New.cshtml

<label asp-for="Name"></label>
<input asp-for="Name"/>

Will result in this HTML:

<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>

I hope this is helpful to anyone with same question but using .NET Core.

dispatch_after - GCD in Swift?

Swift 4 has a pretty short way of doing this:

Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
    // Your stuff here
    print("hello")
}

How to get selected value of a dropdown menu in ReactJS

The code in the render method represents the component at any given time. If you do something like this, the user won't be able to make selections using the form control:

<select value="Radish">
  <option value="Orange">Orange</option>
  <option value="Radish">Radish</option>
  <option value="Cherry">Cherry</option>
</select>

So there are two solutions for working with forms controls:

  1. Controlled Components Use component state to reflect the user's selections. This provides the most control, since any changes you make to state will be reflected in the component's rendering:

example:

var FruitSelector = React.createClass({
    getInitialState:function(){
      return {selectValue:'Radish'};
  },
    handleChange:function(e){
    this.setState({selectValue:e.target.value});
  },
  render: function() {
    var message='You selected '+this.state.selectValue;
    return (
      <div>
      <select 
        value={this.state.selectValue} 
        onChange={this.handleChange} 
      >
       <option value="Orange">Orange</option>
        <option value="Radish">Radish</option>
        <option value="Cherry">Cherry</option>
      </select>
      <p>{message}</p>
      </div>        
    );
  }
});

React.render(<FruitSelector name="World" />, document.body);

JSFiddle: http://jsfiddle.net/xe5ypghv/

  1. Uncontrolled Components The other option is to not control the value and simply respond to onChange events. In this case you can use the defaultValue prop to set an initial value.

    <div>
     <select defaultValue={this.state.selectValue} 
     onChange={this.handleChange} 
     >
        <option value="Orange">Orange</option>
        <option value="Radish">Radish</option>
        <option value="Cherry">Cherry</option>
      </select>
      <p>{message}</p>
      </div>       
    

http://jsfiddle.net/kb3gN/10396/

The docs for this are great: http://facebook.github.io/react/docs/forms.html and also show how to work with multiple selections.

UPDATE

A variant of Option 1 (using a controlled component) is to use Redux and React-Redux to create a container component. This involves connect and a mapStateToProps function, which is easier than it sounds but probably overkill if you're just starting out.

How do I center an SVG in a div?

For me, the fix was to add margin: 0 auto; onto the element containing the <svg>.

Like this:

<div style="margin: 0 auto">
   <svg ...</svg>
</div>

OAuth: how to test with local URLs?

For Mac users, edit the /etc/hosts file. You have to use sudo vi /etc/hosts if its read-only. After authorization, the oauth server sends the callback URL, and since that callback URL is rendered on your local browser, the local DNS setting will work:

127.0.0.1       mylocal.com

The imported project "C:\Microsoft.CSharp.targets" was not found

Sometimes the problem might be with hardcoded VS version in .csproj file. If you have in your csproj something like this:

[...]\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets"

You should check if the number is correct (the reason it's wrong can be the project was created with another version of Visual Studio). If it's wrong, replace it with your current version of build tools OR use the VS variable:

[...]\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets"

Mysql password expired. Can't connect

I did something like this.

UPDATE mysql.user SET authentication_string = PASSWORD(''), password_expired = 'N' WHERE User = 'root' AND Host = 'localhost';

Running JAR file on Windows

Easiest route is probably upgrading or re-installing the Java Runtime Environment (JRE).

Or this:

  • Open the Windows Explorer, from the Tools select 'Folder Options...'
  • Click the File Types tab, scroll down and select JAR File type.
  • Press the Advanced button.
  • In the Edit File Type dialog box, select open in Actions box and click Edit...
  • Press the Browse button and navigate to the location the Java interpreter javaw.exe.
  • In the Application used to perform action field, needs to display something similar to C:\Program Files\Java\j2re1.4.2_04\bin\javaw.exe" -jar "%1" % (Note: the part starting with 'javaw' must be exactly like that; the other part of the path name can vary depending on which version of Java you're using) then press the OK buttons until all the dialogs are closed.

Which was stolen from here: http://windowstipoftheday.blogspot.com/2005/10/setting-jar-file-association.html

Android ImageView's onClickListener does not work

Ok,

I managed to solve this tricky issue. The thing was like I was using FrameLayout. Don't know why but it came to my mind that may be the icon would be getting hidden behind some other view.

I tried putting the icon at the end of my layout and now I am able to see the Toast as well as the Log.

Thank you everybody for taking time to solve the issue.. Was surely tricky..

How do I enable EF migrations for multiple contexts to separate databases?

EF 4.7 actually gives a hint when you run Enable-migrations at multiple context.

More than one context type was found in the assembly 'Service.Domain'.

To enable migrations for 'Service.Domain.DatabaseContext.Context1', 
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context1.
To enable migrations for 'Service.Domain.DatabaseContext.Context2',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context2.

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

Using set_time_limit(0) is useless when using php-fpm or similar process manager.

Bottomline is not to use set_time_limit when using php-fpm, to increase your execution timeout, check this tutorial.

How to get the focused element with jQuery?

If you want to confirm if focus is with an element then

if ($('#inputId').is(':focus')) {
    //your code
}

How do I check if a number is a palindrome?

I didn't notice any answers that solved this problem using no extra space, i.e., all solutions I saw either used a string, or another integer to reverse the number, or some other data structures.

Although languages like Java wrap around on integer overflow, this behavior is undefined in languages like C. (Try reversing 2147483647 (Integer.MAX_VALUE) in Java)
Workaround could to be to use a long or something but, stylistically, I don't quite like that approach.

Now, the concept of a palindromic number is that the number should read the same forwards and backwards. Great. Using this information, we can compare the first digit and the last digit. Trick is, for the first digit, we need the order of the number. Say, 12321. Dividing this by 10000 would get us the leading 1. The trailing 1 can be retrieved by taking the mod with 10. Now, to reduce this to 232. (12321 % 10000)/10 = (2321)/10 = 232. And now, the 10000 would need to be reduced by a factor of 2. So, now on to the Java code...

private static boolean isPalindrome(int n) {
    if (n < 0)
        return false;

    int div = 1;
    // find the divisor
    while (n / div >= 10)
        div *= 10;

    // any number less than 10 is a palindrome
    while (n != 0) {
        int leading = n / div;
        int trailing = n % 10;
        if (leading != trailing)
            return false;

        // % with div gets rid of leading digit
        // dividing result by 10 gets rid of trailing digit
        n = (n % div) / 10;

        // got rid of 2 numbers, update div accordingly
        div /= 100;
    }
    return true;
}

Edited as per Hardik's suggestion to cover the cases where there are zeroes in the number.

Copy Data from a table in one Database to another separate database

It's db1.dbo.TempTable and db2.dbo.TempTable

The four-part naming scheme goes:

ServerName.DatabaseName.Schema.Object

Escape @ character in razor view engine

I tried all the options above and none worked. This is what I did that worked :

@{
    string str = @"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$";
}

<td>Email</td>
<td>
   <input type="text" id="txtEmail" required name="email" pattern=@str /> 
</td>

I created a string varible and passed all the RegEx pattern code into it, then used the variable in the html, and Razor was cool with it.

How to update and delete a cookie?

http://www.quirksmode.org/js/cookies.html

update would just be resetting it using createCookie

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

Google Maps v2 - set both my location and zoom in

It's possible to change location, zoom, bearing and tilt all in one go. It's also possible to set the duration on the animateCamera() call.

CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(MOUNTAIN_VIEW)      // Sets the center of the map to Mountain View
    .zoom(17)                   // Sets the zoom
    .bearing(90)                // Sets the orientation of the camera to east
    .tilt(30)                   // Sets the tilt of the camera to 30 degrees
    .build();                   // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

Have a look at the docs here:

https://developers.google.com/maps/documentation/android/views?hl=en-US#moving_the_camera

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How to only get file name with Linux 'find'?

Use -execdir which automatically holds the current file in {}, for example:

find . -type f -execdir echo '{}' ';'

You can also use $PWD instead of . (on some systems it won't produce an extra dot in the front).

If you still got an extra dot, alternatively you can run:

find . -type f -execdir basename '{}' ';'

-execdir utility [argument ...] ;

The -execdir primary is identical to the -exec primary with the exception that utility will be executed from the directory that holds the current file.

When used + instead of ;, then {} is replaced with as many pathnames as possible for each invocation of utility. In other words, it'll print all filenames in one line.

How to generate Javadoc HTML files in Eclipse?

You can also do it from command line much easily.

  1. Open command line from the folder/package.
  2. From command line run:

    javadoc YourClassName.java

  3. To batch generate docs for multiple Class:

    javadoc *.java

How to check the version before installing a package using apt-get?

Also, according to the man page:

apt-cache showpkg <package_name>

can also be used to:

...display information about the packages listed on the command line. Remaining arguments are package names. The available versions and reverse dependencies of each package listed are listed, as well as forward dependencies for each version. Forward (normal) dependencies are those packages upon which the package in question depends; reverse dependencies are those packages that depend upon the package in question. Thus, forward dependencies must be satisfied for a package, but reverse dependencies need not be.

Ex:

apt-cache policy conky

conky:
  Installed: (none)
  Candidate: 1.10.3-1
  Version table:
     1.10.3-1 500
        500 http://us.archive.ubuntu.com/ubuntu yakkety/universe amd64 Packages
        500 http://us.archive.ubuntu.com/ubuntu yakkety/universe i386 Packages

Java and SQLite

I understand you asked specifically about SQLite, but maybe HSQL database would be a better fit with Java. It is written in Java itself, runs in the JVM, supports in-memory tables etc. and all that features make it quite usable for prototyping and unit-testing.

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

Generate a random number in a certain range in MATLAB

if you are looking to generate all the number within a specific rang randomly then you can try

r = randi([a b],1,d)

a = start point

b = end point

d = how many number you want to generate but keep in mind that d should be less than or equal to b-a

How do I create a new class in IntelliJ without using the mouse?

On Mac you can navigate to the location in Project view where you want to create your class and then use ?N followed by Enter.

DevTools failed to load SourceMap: Could not load content for chrome-extension

For me, the problem was caused not by the app in development itself but by the Chrome extension: React Developer Tool. I solved partially that by right-clicking the extension icon in the toolbar, clicking "manage extension" (I'm freely translating menu text here since my browser language is in Brazilian Portuguese), then enabling "Allow access to files URLs." But this measure fixed just some of the alerts.

I found issues in the react repo that suggests the cause is a bug in their extension and is planned to be corrected soon - see issues 20091 and 20075.

You can confirm is extension-related by accessing your app in an anonymous tab without any extension enabled.

SQL Server 2005 Using CHARINDEX() To split a string

Try the following query:

DECLARE @item VARCHAR(MAX) = 'LD-23DSP-1430'

SELECT
SUBSTRING( @item, 0, CHARINDEX('-', @item)) ,
SUBSTRING(
               SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)) ,
               0 ,
               CHARINDEX('-', SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)))
              ),
REVERSE(SUBSTRING( REVERSE(@ITEM), 0, CHARINDEX('-', REVERSE(@ITEM))))

Find all controls in WPF Window by type

And this is how it works upwards

    private T FindParent<T>(DependencyObject item, Type StopAt) where T : class
    {
        if (item is T)
        {
            return item as T;
        }
        else
        {
            DependencyObject _parent = VisualTreeHelper.GetParent(item);
            if (_parent == null)
            {
                return default(T);
            }
            else
            {
                Type _type = _parent.GetType();
                if (StopAt != null)
                {
                    if ((_type.IsSubclassOf(StopAt) == true) || (_type == StopAt))
                    {
                        return null;
                    }
                }

                if ((_type.IsSubclassOf(typeof(T)) == true) || (_type == typeof(T)))
                {
                    return _parent as T;
                }
                else
                {
                    return FindParent<T>(_parent, StopAt);
                }
            }
        }
    }

How to set commands output as a variable in a batch file

I most cases, creating a temporary file named after your variable name might be acceptable. (as you are probably using meaningful variables name...)

Here, my variable name is SSH_PAGEANT_AUTH_SOCK

dir /w "\\.\pipe\\"|find "pageant" > %temp%\SSH_PAGEANT_AUTH_SOCK && set /P SSH_PAGEANT_AUTH_SOCK=<%temp%\SSH_PAGEANT_AUTH_SOCK

VBA setting the formula for a cell

Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.

strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address

The workbook and worksheet that strProjectName references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.

Relational Database Design Patterns?

AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)

I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).

Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

This is a simple solution for merging two dictionaries where += can be applied to the values, it has to iterate over a dictionary only once

a = {'a':1, 'b':2, 'c':3}

dicts = [{'b':3, 'c':4, 'd':5},
         {'c':9, 'a':9, 'd':9}]

def merge_dicts(merged,mergedfrom):
    for k,v in mergedfrom.items():
        if k in merged:
            merged[k] += v
        else:
            merged[k] = v
    return merged

for dct in dicts:
    a = merge_dicts(a,dct)
print (a)
#{'c': 16, 'b': 5, 'd': 14, 'a': 10}

<input type="file"> limit selectable files by extensions

Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.

fatal error LNK1104: cannot open file 'kernel32.lib'

I just met and solved this problem by myself. My problem is a little different. I'm using visual studio on Windows 10. When I create the project, the Target Platform Version was automatically set to 10.0.15063.0. But there is no kernel32.lib for this version of SDK, neither are other necessary header files and lib files. So I modified the Target Platform Version to 8.1. And it worked.

Environment:

  • Windows 10
  • Visual Studio 2015
  • Visual C++

Solution:

  1. Open the project's Property Page;
  2. Navigate to General page;
  3. Modify Target Platform Version to the desired target platform (e.g. 8.1).

Is there any way to set environment variables in Visual Studio Code?

My response is fairly late. I faced the same problem. I am on Windows 10. This is what I did:

  • Open a new Command prompt (CMD.EXE)
  • Set the environment variables . set myvar1=myvalue1
  • Launch VS Code from that Command prompt by typing code and then press ENTER
  • VS code was launched and it inherited all the custom variables that I had set in the parent CMD window

Optionally, you can also use the Control Panel -> System properties window to set the variables on a more permanent basis

Hope this helps.

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" ... />

Unstaged changes left after git reset --hard

Possible Cause #1 - Line Ending Normalization

One situation in which this can happen is when the file in question was checked into the repository without the correct configuration for line endings (1) resulting in a file in the repository with either the incorrect line endings, or mixed line endings. To confirm, verify that git diff shows only changes in line endings (these may not be visible by default, try git diff | cat -v to see carriage returns as literal ^M characters).

Subsequently, someone probably added a .gitattributes or modified the core.autocrlf setting to normalize line endings (2). Based on the .gitattributes or global config, Git has applied local changes to your working copy that apply the line ending normalization requested. Unfortunately, for some reason git reset --hard does not undo these line normalization changes.

Solution

Workarounds in which the local line endings are reset will not solve the problem. Every time the file is "seen" by git, it will try and reapply the normalization, resulting in the same issue.

The best option is to let git apply the normalization it wants to by normalizing all the line endings in the repo to match the .gitattributes, and committing those changes -- see Trying to fix line-endings with git filter-branch, but having no luck.

If you really want to try and revert the changes to the file manually then the easiest solution seems to be to erase the modified files, and then to tell git to restore them, although I note this solution does not seem to work consistently 100% of the time (WARNING: DO NOT run this if your modified files have changes other than line endings!!):

    git status --porcelain | grep "^ M" | cut -c4- | xargs rm
    git checkout -- .

Note that, unless you do normalize the line endings in the repository at some point, you will keep running into this issue.

Possible Cause #2 - Case Insensitivity

The second possible cause is case insensitivity on Windows or Mac OS/X. For example, say a path like the following exists in the repository:

/foo/bar

Now someone on Linux commits files into /foo/Bar (probably due to a build tool or something that created that directory) and pushes. On Linux, this is actually now two separate directories:

/foo/bar/fileA
/foo/Bar/fileA

Checking this repo out on Windows or Mac may result in modified fileA that cannot be reset, because on each reset, git on Windows checks out /foo/bar/fileA, and then because Windows is case insensitive, overwrites the content of fileA with /foo/Bar/fileA, resulting in them being "modified".

Another case may be an individual file(s) that exists in the repo, which when checked out on a case insensitive filesystem, would overlap. For example:

/foo/bar/fileA
/foo/bar/filea

There may be other similar situations that could cause such problems.

git on case insensitive filesystems should really detect this situation and show a useful warning message, but it currently does not (this may change in the future -- see this discussion and related proposed patches on the git.git mailing list).

Solution

The solution is to bring the case of files in the git index and the case on the Windows filesystem into alignment. This can either be done on Linux which will show the true state of things, OR on Windows with very useful open source utility Git-Unite. Git-Unite will apply the necessary case changes to the git index, which can then be committed to the repo.

(1) This was most likely by someone using Windows, without any .gitattributes definition for the file in question, and using the default global setting for core.autocrlf which is false (see (2)).

(2) http://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/

move a virtual machine from one vCenter to another vCenter

You don't have to export your VMs at all. You can move the VM and clone to a TAXI host in vCenter 1. Then add the host to vCenter 2, and vMotion away whatever VMs to other hosts previously managed by vCenter 2. When done, you can add the TAXI host back to vCenter 1.

What is the difference between prefix and postfix operators?

In fact return (i++) will only return 10.

The ++ and -- operators can be placed before or after the variable, with different effects. If they are before, then they will be processed and returned and essentially treated just like (i-1) or (i+1), but if you place the ++ or -- after the i, then the return is essentailly

return i;
i + 1;

So it will return 10 and never increment it.

What are the proper permissions for an upload folder with PHP/Apache?

I will add that if you are using SELinux that you need to make sure the type context is tmp_t You can accomplish this by using the chcon utility

chcon -t tmp_t uploads

MySql Query Replace NULL with Empty String in Select

select IFNULL(`prereq`,'') as ColumnName FROM test

this query is selecting "prereq" values and if any one of the values are null it show an empty string as you like So, it shows all values but the NULL ones are showns in blank

How to get the selected radio button’s value?

You can do something like this:

_x000D_
_x000D_
var radios = document.getElementsByName('genderS');_x000D_
_x000D_
for (var i = 0, length = radios.length; i < length; i++) {_x000D_
  if (radios[i].checked) {_x000D_
    // do whatever you want with the checked radio_x000D_
    alert(radios[i].value);_x000D_
_x000D_
    // only one radio can be logically checked, don't check the rest_x000D_
    break;_x000D_
  }_x000D_
}
_x000D_
<label for="gender">Gender: </label>_x000D_
<input type="radio" name="genderS" value="1" checked="checked">Male</input>_x000D_
<input type="radio" name="genderS" value="0">Female</input>
_x000D_
_x000D_
_x000D_

jsfiddle

Edit: Thanks HATCHA and jpsetung for your edit suggestions.

How to read a PEM RSA private key from .NET

ok, Im using mac to generate my self signed keys. Here is the working method I used.

I created a shell script to speed up my key generation.

genkey.sh

#/bin/sh

ssh-keygen -f host.key
openssl req -new -key host.key -out request.csr
openssl x509 -req -days 99999 -in request.csr -signkey host.key -out server.crt
openssl pkcs12 -export -inkey host.key -in server.crt -out private_public.p12 -name "SslCert"
openssl base64 -in private_public.p12 -out Base64.key

add the +x execute flag to the script

chmod +x genkey.sh

then call genkey.sh

./genkey.sh

I enter a password (important to include a password at least for the export at the end)

Enter pass phrase for host.key:
Enter Export Password:   {Important to enter a password here}
Verifying - Enter Export Password: { Same password here }

I then take everything in Base64.Key and put it into a string named sslKey

private string sslKey = "MIIJiAIBA...................................." +
                        "......................ETC...................." +
                        "......................ETC...................." +
                        "......................ETC...................." +
                        ".............ugICCAA=";

I then used a lazy load Property getter to get my X509 Cert with a private key.

X509Certificate2 _serverCertificate = null;
X509Certificate2 serverCertificate{
    get
    {
        if (_serverCertificate == null){
            string pass = "Your Export Password Here";
            _serverCertificate = new X509Certificate(Convert.FromBase64String(sslKey), pass, X509KeyStorageFlags.Exportable);
        }
        return _serverCertificate;
    }
}

I wanted to go this route because I am using .net 2.0 and Mono on mac and I wanted to use vanilla Framework code with no compiled libraries or dependencies.

My final use for this was the SslStream to secure TCP communication to my app

SslStream sslStream = new SslStream(serverCertificate, false, SslProtocols.Tls, true);

I hope this helps other people.

NOTE

Without a password I was unable to correctly unlock the private key for export.

Send attachments with PHP Mail()?

I ended up writing my own email sending/encoding function. This has worked well for me for sending PDF attachments. I have not used the other features in production.

Note: Despite the spec being quite emphatic that you must use \r\n to separate headers, I found it only worked when I used PHP_EOL. I have only tested this on Linux. YMMV

<?php
# $args must be an associative array
#     required keys: from, to, body
#          body can be a string or a [tree of] associative arrays. See examples below
#     optional keys: subject, reply_to, cc, bcc
# EXAMPLES:
#    # text-only email:
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        # body will be text/plain because we're passing a string that doesn't start with '<'
#        'body' => 'Hi, testing 1 2 3',
#    ));
#
#    # html-only email
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        # body will be text/html because we're passing a string that starts with '<'
#        'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
#    ));
#
#    # text-only email (explicitly, in case first character is dynamic or something)
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        # body will be text/plain because we're passing a string that doesn't start with '<'
#        'body' => array(
#            'type' => 'text',
#            'body' => $message_text,
#        )
#    ));
#
#    # email with text and html alternatives (auto-detected mime types)
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'alternatives',
#            'body' => array(
#                "Hi!\n\nI like cheese",
#                '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
#            )
#        )
#    ));
#
#    # email with text and html alternatives (explicit types)
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'alternatives',
#            'body' => array(
#                array(
#                    'type' => 'text',
#                    'body' => "Hi!\n\nI like cheese",
#                ),
#                array(
#                    'type' => 'html',
#                    'body' => '<h1>Hi!</h1><p>I like cheese</p>',
#                ),
#            )
#        )
#    ));
#
#    # email with an attachment
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'mixed',
#            'body' => array(
#                "Hi!\n\nCheck out this (inline) image",
#                array(
#                    'type' => 'image/png',
#                    'disposition' => 'inline',
#                    'body' => $image_data, # raw file contents
#                ),
#                "Hi!\n\nAnd here's an attachment",
#                array(
#                    'type' => 'application/pdf; name="attachment.pdf"',
#                    'disposition' => 'attachment; filename="attachment.pdf"',
#                    'body' => $pdf_data, # raw file contents
#                ),
#                "Or you can use shorthand:",
#                array(
#                    'type' => 'application/pdf',
#                    'attachment' => 'attachment.pdf', # name for client (not data source)
#                    'body' => $pdf_data, # raw file contents
#                ),
#            )
#        )
#    ))
function email2($args) {
    if (!isset($args['from'])) { return 1; }
    $from = $args['from'];
    if (!isset($args['to'])) { return 2; }
    $to = $args['to'];
    $subject = isset($args['subject']) ? $args['subject'] : '';
    $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
    $cc = isset($args['cc']) ? $args['cc'] : '';
    $bcc = isset($args['bcc']) ? $args['bcc'] : '';

    #FIXME should allow many more characters here (and do Q encoding)
    $subject = isset($args['subject']) ? $args['subject'] : '';
    $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

    $headers = "From: $from";
    if($reply_to) {
        $headers .= PHP_EOL . "Reply-To: $reply_to";
    }
    if($cc) {
        $headers .= PHP_EOL . "CC: $cc";
    }
    if($bcc) {
        $headers .= PHP_EOL . "BCC: $bcc";
    }

    $r = email2_helper($args['body']);
    $headers .= PHP_EOL . $r[0];
    $body = $r[1];

    if (mail($to, $subject, $body, $headers)) {
        return 0;
    } else {
        return 5;
    }
}

function email2_helper($body, $top = true) {
    if (is_string($body)) {
        if (substr($body, 0, 1) == '<') {
            return email2_helper(array('type' => 'html', 'body' => $body), $top);
        } else {
            return email2_helper(array('type' => 'text', 'body' => $body), $top);
        }
    }
    # now we can assume $body is an associative array
    # defaults:
    $type = 'application/octet-stream';
    $mime = false;
    $boundary = null;
    $disposition = null;
    $charset = false;
    # process 'type' first, because it sets defaults for others
    if (isset($body['type'])) {
        $type = $body['type'];
        if ($type === 'text') {
            $type = 'text/plain';
            $charset = true;
        } elseif ($type === 'html') {
            $type = 'text/html';
            $charset = true;
        } elseif ($type === 'alternative' || $type === 'alternatives') {
            $mime = true;
            $type = 'multipart/alternative';
        } elseif ($type === 'mixed') {
            $mime = true;
            $type = 'multipart/mixed';
        }
    }
    if (isset($body['disposition'])) {
        $disposition = $body['disposition'];
    }
    if (isset($body['attachment'])) {
        if ($disposition == null) {
            $disposition = 'attachment';
        }
        $disposition .= "; filename=\"{$body['attachment']}\"";
        $type .= "; name=\"{$body['attachment']}\"";
    }
    # make headers
    $headers = array();
    if ($top && $mime) {
        $headers[] = 'MIME-Version: 1.0';
    }
    if ($mime) {
        $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
        $type .= "; boundary=$boundary";
    }
    if ($charset) {
        $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
    }
    $headers[] = "Content-Type: $type";
    if ($disposition !== null) {
        $headers[] = "Content-Disposition: {$disposition}";
    }

    $data = '';
    # return array, first el is headers, 2nd is body (php's mail() needs them separate)
    if ($mime) {
        foreach ($body['body'] as $sub_body) {
            $data .= "--$boundary" . PHP_EOL;
            $r = email2_helper($sub_body, false);
            $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
            $data .= $r[1] . PHP_EOL . PHP_EOL; # body
        }
        $data .= "--$boundary--";
    } else {
        if(preg_match('/[^\x09\x0A\x0D\x20-\x7E]/', $body['body'])) {
            $headers[] = "Content-Transfer-Encoding: base64";
            $data .= chunk_split(base64_encode($body['body']));
        } else {
            $data .= $body['body'];
        }
    }
    return array(join(PHP_EOL, $headers), $data);
}

compare two files in UNIX

Well, you can just sort the files first, and diff the sorted files.

sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted

You can also filter the output to report lines in file2 which are absent from file1:

diff -u file1.sorted file2.sorted | grep "^+" 

As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:

diff <(sort file1) <(sort file2)

Querying DynamoDB by date

You could make the Hash key something along the lines of a 'product category' id, then the range key as a combination of a timestamp with a unique id appended on the end. That way you know the hash key and can still query the date with greater than.

How to set Google Chrome in WebDriver

It was giving Illegal Exception.

My workaround with code:

public void dofirst(){
    System.setProperty("webdriver.chrome.driver","D:\\Softwares\\selenium\\chromedriver_win32\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.facebook.com");
}

List files recursively in Linux CLI with path relative to the current directory

That does the trick:

ls -R1 $PWD | while read l; do case $l in *:) d=${l%:};; "") d=;; *) echo "$d/$l";; esac; done | grep -i ".txt"

But it does that by "sinning" with the parsing of ls, though, which is considered bad form by the GNU and Ghostscript communities.

javax.persistence.NoResultException: No entity found for query

When you don't know whether there are any results, use getResultList().

List<User> foundUsers = (List<User>) query.getResultList();
        if (foundUsers == null || foundUsers.isEmpty()) {
            return false;
        }
User foundUser = foundUsers.get(0);

Cannot open include file: 'unistd.h': No such file or directory

If you're using ZLib in your project, then you need to find :

#if 1

in zconf.h and replace(uncomment) it with :

#if HAVE_UNISTD_H /* ...the rest of the line

If it isn't ZLib I guess you should find some alternative way to do this. GL.

How can I avoid ResultSet is closed exception in Java?

Check whether you have declared the method where this code is executing as static. If it is static there may be some other thread resetting the ResultSet.

ReactJS - Get Height of an element

Here's a nice reusable hook amended from https://swizec.com/blog/usedimensions-a-react-hook-to-measure-dom-nodes:

import { useState, useCallback, useEffect } from 'react';

function getDimensionObject(node) {
  const rect = node.getBoundingClientRect();

  return {
    width: rect.width,
    height: rect.height,
    top: 'x' in rect ? rect.x : rect.top,
    left: 'y' in rect ? rect.y : rect.left,
    x: 'x' in rect ? rect.x : rect.left,
    y: 'y' in rect ? rect.y : rect.top,
    right: rect.right,
    bottom: rect.bottom
  };
}

export function useDimensions(data = null, liveMeasure = true) {
  const [dimensions, setDimensions] = useState({});
  const [node, setNode] = useState(null);

  const ref = useCallback(node => {
    setNode(node);
  }, []);

  useEffect(() => {
    if (node) {
      const measure = () =>
        window.requestAnimationFrame(() =>
          setDimensions(getDimensionObject(node))
        );
      measure();

      if (liveMeasure) {
        window.addEventListener('resize', measure);
        window.addEventListener('scroll', measure);

        return () => {
          window.removeEventListener('resize', measure);
          window.removeEventListener('scroll', measure);
        };
      }
    }
  }, [node, data]);

  return [ref, dimensions, node];
}

To implement:

import { useDimensions } from '../hooks';

// Include data if you want updated dimensions based on a change.
const MyComponent = ({ data }) => {
  const [
    ref,
    { height, width, top, left, x, y, right, bottom }
  ] = useDimensions(data);

  console.log({ height, width, top, left, x, y, right, bottom });

  return (
    <div ref={ref}>
      {data.map(d => (
        <h2>{d.title}</h2>
      ))}
    </div>
  );
};

Update select2 data without rebuilding the control

I think it suffices to hand the data over directly:

$("#inputhidden").select2("data", data, true);

Note that the second parameter seems to indicate that a refresh is desired.

Thanks to @Bergi for help with this.


If that doesn't automatically update you could either try calling it's updateResults method directly.

$("#inputhidden").select2("updateResults");

Or trigger it indirectly by sending a trigger to the "input.select2-input" like so:

var search = $("#inputhidden input.select2-input");
search.trigger("input");

Is it possible to set ENV variables for rails development environment in my code?

The way I am trying to do this in my question actually works!

# environment/development.rb

ENV['admin_password'] = "secret" 

I just had to restart the server. I thought running reload! in rails console would be enough but I also had to restart the web server.

I am picking my own answer because I feel this is a better place to put and set the ENV variables

Read entire file in Scala?

// for file with utf-8 encoding
val lines = scala.io.Source.fromFile("file.txt", "utf-8").getLines.mkString

Java SecurityException: signer information does not match

In my case, I had duplicated JAR version of BouncyCastle in my library path :S

100% width background image with an 'auto' height

Just use a two color background image:

<div style="width:100%; background:url('images/bkgmid.png');
       background-size: cover;">
content
</div>

URL Encode a string in jQuery for an AJAX request

try this one

var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val().replace(/ /g, '+');

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Opening Chrome From Command Line

open command prompt and type

cd\ (enter)

then type

start chrome "www.google.com"(any website you require)

Val and Var in Kotlin

Two ways to create variable in KOTLIN VAL and VAR

1.VAL stores constant values. Also called Final Variable

2.VAR stores Changeable Values

Click here for example

Convert Unix timestamp into human readable date using MySQL

Need a unix timestamp in a specific timezone?

Here's a one liner if you have quick access to the mysql cli:

mysql> select convert_tz(from_unixtime(1467095851), 'UTC', 'MST') as 'local time';

+---------------------+
| local time          |
+---------------------+
| 2016-06-27 23:37:31 |
+---------------------+

Replace 'MST' with your desired timezone. I live in Arizona thus the conversion from UTC to MST.

PHP - remove <img> tag from string

You need to assign the result back to $content as preg_replace does not modify the original string.

$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);

git cherry-pick says "...38c74d is a merge but no -m option was given"

-m means the parent number.

From the git doc:

Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.

For example, if your commit tree is like below:

- A - D - E - F -   master
   \     /
    B - C           branch one

then git cherry-pick E will produce the issue you faced.

git cherry-pick E -m 1 means using D-E, while git cherry-pick E -m 2 means using B-C-E.

Send multiple checkbox data to PHP via jQuery ajax()

The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.

echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;

Apache: Restrict access to specific source IP inside virtual host

If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):

Order deny,allow
Deny from all
Allow from 10.0.0.1

You can even specify a subnet

Allow from 10.0.0

Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.

How can I set the value of a DropDownList using jQuery?

There are many ways to do it. here are some of them:

$("._statusDDL").val('2');

OR

$('select').prop('selectedIndex', 3);

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

The simplest way to check the existence of the column in mongo compass is :

{ 'column_name': { $exists: true } }

What is the best way to connect and use a sqlite database from C#

There is a list of Sqlite wrappers for .Net at http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers. From what I've heard http://sqlite.phxsoftware.com/ is quite good. This particular one lets you access Sqlite through ADO.Net just like any other database.

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

Using Python, find anagrams for a list of words

If you want a solution in java,

public List<String> findAnagrams(List<String> dictionary) {

    // TODO do null check and other basic validations.
    Map<String, List<String>> wordMap = new HashMap<String, List<String>>();

    for(String word : dictionary) {

        // ignore if word is null
        char[] tempWord = word.tocharArray();
        Arrays.sort(tempWord);
        String newWord = new String(tempWord);

        if(wordMap.containsKey(newWord)) {
            wordMap.put(newWord, wordMap.get(word).add(word));
        } else {
            wordMap.put(newWord, new ArrayList<>() {word});
        }

    }

    List<String> anagrams = new ArrayList<>();

    for(String key : wordMap.keySet()) {

        if(wordMap.get(key).size() > 1) {
            anagrams.addAll(wordMap.get(key));
        }

    }

    return anagrams;
}

Offline Speech Recognition In Android (JellyBean)

A simple and flexible offline recognition on Android is implemented by CMUSphinx, an open source speech recognition toolkit. It works purely offline, fast and configurable It can listen continuously for keyword, for example.

You can find latest code and tutorial here.

Update in 2019: Time goes fast, CMUSphinx is not that accurate anymore. I recommend to try Kaldi toolkit instead. The demo is here.

php return 500 error but no error log

In the past, I had no error logs in two cases:

  1. The user under which Apache was running had no permissions to modify php_error_log file.
  2. Error 500 occurred because of bad configuration of .htaccess, for example wrong rewrite module settings. In this situation errors are logged to Apache error_log file.

label or @html.Label ASP.net MVC 4

When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance

  • When dealing with hyperlinks, since the HTML helper simplifies routing
  • When you bind to your model, using @Html.LabelFor, @Html.TextBoxFor, etc
  • When you use the @Html.EditorFor, as you can assign specific behavior och looks in a editor view

How do I specify a password to 'psql' non-interactively?

I tend to prefer passing a URL to psql:

psql "postgresql://$DB_USER:$DB_PWD@$DB_SERVER/$DB_NAME"

This gives me the freedom to name my environment variables as I wish and avoids creating unnecessary files.

This requires libpq. The documentation can be found here.

Jquery each - Stop loop and return object

Because when you use a return statement inside an each loop, a "non-false" value will act as a continue, whereas false will act as a break. You will need to return false from the each function. Something like this:

function findXX(word) {
    var toReturn; 
    $.each(someArray, function(i) {
        $('body').append('-> '+i+'<br />');
        if(someArray[i] == word) {
            toReturn = someArray[i];
            return false;
        }   
    }); 
    return toReturn; 
}

From the docs:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Converting between java.time.LocalDateTime and java.util.Date

I think below approach will solve the conversion without taking time-zone into consideration. Please comment if it has any pitfalls.

    LocalDateTime datetime //input
    public static final DateTimeFormatter yyyyMMddHHmmss_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formatDateTime = datetime.format(yyyyMMddHHmmss_DATE_FORMAT);
    Date outputDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(formatDateTime); //output

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

Global Git ignore

You need to set up your global core.excludesfile configuration file to point to this global ignore file.

e.g.

*nix or Windows git bash:

git config --global core.excludesFile '~/.gitignore'

Windows cmd:

git config --global core.excludesFile "%USERPROFILE%\.gitignore"

Windows PowerShell:

git config --global core.excludesFile "$Env:USERPROFILE\.gitignore"

For Windows it set to the location C:\Users\{myusername}\.gitignore. You can verify that the config value is correct by doing:

git config --global core.excludesFile

The result should be the expanded path to your user profile's .gitignore. Ensure that the value does not contain the unexpanded %USERPROFILE% string.

Important: The above commands will only set the location of the ignore file that git will use. The file has to still be manually created in that location and populated with the ignore list. (from muruge's comment)

You can read about the command at https://help.github.com/articles/ignoring-files/#create-a-global-gitignore

Specifying Style and Weight for Google Fonts

They use regular CSS.

Just use your regular font family like this:

font-family: 'Open Sans', sans-serif;

Now you decide what "weight" the font should have by adding

for semi-bold

font-weight:600;

for bold (700)

font-weight:bold;

for extra bold (800)

font-weight:800;

Like this its fallback proof, so if the google font should "fail" your backup font Arial/Helvetica(Sans-serif) use the same weight as the google font.

Pretty smart :-)

Note that the different font weights have to be specifically imported via the link tag url (family query param of the google font url) in the header.

For example the following link will include both weights 400 and 700:

<link href='fonts.googleapis.com/css?family=Comfortaa:400,700'; rel='stylesheet' type='text/css'>

How to get number of rows inserted by a transaction

In case you need further info for your log/audit you can OUTPUT clause: This way, not only you keep the number of rows affected, but also what records.

As an example of the Output Clause during inserts: SQL Server list of insert identities

DECLARE @InsertedIDs table(ID int);

INSERT INTO YourTable
    OUTPUT INSERTED.ID
        INTO @InsertedIDs 
    SELECT ...

HTH

How to view hierarchical package structure in Eclipse package explorer

For Eclipse in Macbook it is just 2 click process:

  • Click on view menu (3 dot symbol) in package explorer -> hover over package presentation -> Click on Hierarchical

enter image description here

Does WGET timeout?

Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:

ignore_user_abort(TRUE);

In this way even if wget terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time limit (ini directive: 30 seconds by default).

As per wget anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

First you need to install cors by using below command :

npm install cors --save

Now add the following code to your app starting file like ( app.js or server.js)

var express = require('express');
var app = express();

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

require('./router/index')(app);

Get index of element as child relative to parent

There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li siblings in an array, and on click, check the indexOf the clicked element in that array.

_x000D_
_x000D_
const lis = [...document.querySelectorAll('#wizard > li')];_x000D_
lis.forEach((li) => {_x000D_
  li.addEventListener('click', () => {_x000D_
    const index = lis.indexOf(li);_x000D_
    console.log(index);_x000D_
  });_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Or, with event delegation:

_x000D_
_x000D_
const lis = [...document.querySelectorAll('#wizard li')];_x000D_
document.querySelector('#wizard').addEventListener('click', ({ target }) => {_x000D_
  // Make sure the clicked element is a <li> which is a child of wizard:_x000D_
  if (!target.matches('#wizard > li')) return;_x000D_
  _x000D_
  const index = lis.indexOf(target);_x000D_
  console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of lis on every click, rather than beforehand:

_x000D_
_x000D_
const wizard = document.querySelector('#wizard');_x000D_
wizard.addEventListener('click', ({ target }) => {_x000D_
  // Make sure the clicked element is a <li>_x000D_
  if (!target.matches('li')) return;_x000D_
  _x000D_
  const lis = [...wizard.children];_x000D_
  const index = lis.indexOf(target);_x000D_
  console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
    <li>Step 1</li>_x000D_
    <li>Step 2</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

git - Your branch is ahead of 'origin/master' by 1 commit

If you just want to throw away the changes and revert to the last commit (the one you wanted to share):

git reset --hard HEAD~

You may want to check to make absolutely sure you want this (git log), because you'll loose all changes.

A safer alternative is to run

git reset --soft HEAD~ # reset to the last commit
git stash              # stash all the changes in the working tree 
git push               # push changes 
git stash pop          # get your changes back 

How to delete zero components in a vector in Matlab?

I often ended up doing things like this. Therefore I tried to write a simple function that 'snips' out the unwanted elements in an easy way. This turns matlab logic a bit upside down, but looks good:

b = snip(a,'0')

you can find the function file at: http://www.mathworks.co.uk/matlabcentral/fileexchange/41941-snip-m-snip-elements-out-of-vectorsmatrices

It also works with all other 'x', nan or whatever elements.

Angular ngClass and click event for toggling class

Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-

<div (click)="status=!status"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

So when status is true the class success is applied. When it is false danger class is applied.

This will work without any additional code in the ts file.

Static variables in JavaScript

I have universal method:

  • create object like: stat_flags = {};
  • use it with adding fields on the fly: flags.popup_save_inited = true;
  • next time ask is there flag you need in the object and do your logic

Example:

class ACTGeneratedPages {
    constructor(table_data, html_table_id) {
        this.flags = {};//static flags for any processes

        //any your code here

    }

    call_popup(post_id) {

        let _this = this;
        document.getElementById('act-popup-template').style.display = 'block';

        if (!this.flags.popup_save_inited) {//second time listener will not be attached
            document.querySelector('.act-modal-save').addEventListener('click', function (e) {
                //saving data code here
                return false;
            });
        }

        this.flags.popup_save_inited = true;//set flag here
    }

}

Python - difference between two strings

The answer to my comment above on the Original Question makes me think this is all he wants:

loopnum = 0
word = 'afrykanerskojezyczny'
wordlist = ['afrykanerskojezycznym','afrykanerskojezyczni','nieafrykanerskojezyczni']
for i in wordlist:
    wordlist[loopnum] = word
    loopnum += 1

This will do the following:

For every value in wordlist, set that value of the wordlist to the origional code.

All you have to do is put this piece of code where you need to change wordlist, making sure you store the words you need to change in wordlist, and that the original word is correct.

Hope this helps!

Hive cast string to date dd-MM-yyyy

If I have understood it correctly, you are trying to convert a String representing a given date, to another type.

Note: (As @Samson Scharfrichter has mentioned)

  • the default representation of a date is ISO8601
  • a date is stored in binary (not as a string)

There are a few ways to do it. And you are close to the solution. I would use the CAST (which converts to a DATE_TYPE):

SELECT cast('2018-06-05' as date); 

Result: 2018-06-05 DATE_TYPE

or (depending on your pattern)

select cast(to_date(from_unixtime(unix_timestamp('05-06-2018', 'dd-MM-yyyy'))) as date)

Result: 2018-06-05 DATE_TYPE

And if you decide to convert ISO8601 to a date type:

select cast(to_date(from_unixtime(unix_timestamp(regexp_replace('2018-06-05T08:02:59Z', 'T',' ')))) as date);

Result: 2018-06-05 DATE_TYPE

Hive has its own functions, I have written some examples for the sake of illustration of these date- and cast- functions:

Date and timestamp functions examples:

Convert String/Timestamp/Date to DATE

SELECT cast(date_format('2018-06-05 15:25:42.23','yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_date(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_timestamp(),'yyyy-MM-dd') as date);  -- 2018-06-05 DATE_TYPE

Convert String/Timestamp/Date to BIGINT_TYPE

SELECT to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
SELECT to_unix_timestamp(current_date(),'yyyy/MM/dd HH:mm:ss'); -- 1528205000 BIGINT_TYPE
SELECT to_unix_timestamp(current_timestamp(),'yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE

Convert String/Timestamp/Date to STRING

SELECT date_format('2018-06-05 15:25:42.23','yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_timestamp(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_date(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE

Convert BIGINT unixtime to STRING

SELECT to_date(from_unixtime(unixtime,'yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 STRING_TYPE

Convert String to BIGINT unixtime

SELECT unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP; -- 1528149600 BIGINT_TYPE

Convert String to TIMESTAMP

SELECT cast(unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP); -- 1528149600 TIMESTAMP_TYPE

Idempotent (String -> String)

SELECT from_unixtime(to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 15:25:42 STRING_TYPE

Idempotent (Date -> Date)

SELECT cast(current_date() as date); -- 2018-06-26 DATE_TYPE

Current date / timestamp

SELECT current_date(); -- 2018-06-26 DATE_TYPE
SELECT current_timestamp(); -- 2018-06-26 14:03:38.285 TIMESTAMP_TYPE

What are the differences in die() and exit() in PHP?

Functionality-wise they are identical but I use them in the following scenarios to make code readable:

Use die() when there is an error and have to stop the execution.

e.g. die( 'Oops! Something went wrong' );

Use exit() when there is not an error and have to stop the execution.

e.g. exit( 'Request has been processed successfully!' );

Iterate over each line in a string in PHP

I would like to propose a significantly faster (and memory efficient) alternative: strtok rather than preg_split.

$separator = "\r\n";
$line = strtok($subject, $separator);

while ($line !== false) {
    # do something with $line
    $line = strtok( $separator );
}

Testing the performance, I iterated 100 times over a test file with 17 thousand lines: preg_split took 27.7 seconds, whereas strtok took 1.4 seconds.

Note that though the $separator is defined as "\r\n", strtok will separate on either character - and as of PHP4.1.0, skip empty lines/tokens.

See the strtok manual entry: http://php.net/strtok

How to fix homebrew permissions?

Command from top-voted answer not work for me.

It got output:

chown: /usr/{my_username}dmin: illegal user name

This command works fine (group for /usr/local was admin already):

sudo chown -R $USER /usr/local

Multiple WHERE clause in Linq

Also, you can use bool method(s)

Query :

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where isValid(Field<string>("UserName"))// && otherMethod() && otherMethod2()                           
            select r;   

        DataTable newDT = query.CopyToDataTable();

Method:

bool isValid(string userName)
{
    if(userName == "XXXX" || userName == "YYYY")
        return false;
    else return true;
}

Call to undefined function oci_connect()

Alright, folks.

First, use

<?php 
phpinfo();
?> 

and determine your PHP Version (located at the very top, e.g. 7.0.xxx) and also, your PHP Version architecture: x64 or x86 and also, Thread Safe or Not THread Safe (located in the first table as "Thread Safety".) "Disabled" obviously means "Not Thread Safe".

It is absolutely critical that the following three pieces of software that you will need are:

  1. for the same major version of PHP (7.0 for 7.0.xxx)
  2. same version of Oracle as the version you are accessing (11g, 12g, etc)
  3. the same Not Thread Safe / Thread Safe version of PHP
  4. all for the same architecture.

If any of the following are for a different architecture, Not Thread Safe/Thread Safe version, PHP major version number, or database version, you'll get errors:

 1. PHP for Windows
 2. OCI8 PECL Drivers for PHP (https://pecl.php.net/package/oci8)
 3. Oracle Instant Client

Remember: If you are connecting to an 11g Oracle instance, you need an 11g driver.

Second, install the correct PHP, OCI8 PECL Driver, and instant client.

I chose:

d:\php\ for php
d:\oci\ for instant client
unzip the contents of the OCI8 PECL Driver into d:\php\ext\

Third, modify d:\php\php.ini according the instructions given by Oracle:

1. set the extension directory
2. set only one of the following:
  a. for 11g drivers, use extension=php_oci8_11g.dll
  b. for 12c drivers, use extension=php_oci8_12c.dll
  c. for other oracle DB drivers, use the correct oracle extension.

Fourth: Add d:\oci\ (or whatever your instant client install location is) to your system PATH.

Fifth: reboot your PC.

Sixth, on a command prompt, type "where oci*" and verify that your Instant Client install path version of oci.dll is present.

Seventh, go to d:\php\ and type "php -m" and you should see OCI8 in the list.

If you do not see OCI8 in the list of modules after typing "php -m", open up d:\php\errorlog.txt

If you see something like:

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\php_oci8_11g.dll' - %1 is not a valid Win32 application.

then either instant client or your PECL driver download is not the same architecture as your PHP version.

If you see something like:

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\php_oci8_12c.dll' - The specified procedure could not be found.

then you are using the wrong OCI8 PECL driver for your version of instant client.

Hope this helps.

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Usually the problem is not closing brackets (}) or missing semicolon (;)

Understanding the main method of python

If you import the module (.py) file you are creating now from another python script it will not execute the code within

if __name__ == '__main__':
    ...

If you run the script directly from the console, it will be executed.

Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.

This is expanded upon a little more at python.berkely.edu

How to make an AJAX call without jQuery?

XMLHttpRequest()

You can use the XMLHttpRequest() constructor to create a new XMLHttpRequest (XHR) object which will allow you to interact with a server using standard HTTP request methods (such as GET and POST):

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

const request = new XMLHttpRequest();

request.addEventListener('load', function () {
  if (this.readyState === 4 && this.status === 200) {
    console.log(this.responseText);
  }
});

request.open('POST', 'example.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);

fetch()

You can also use the fetch() method to obtain a Promise which resolves to the Response object representing the response to your request:

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

fetch('example.php', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
  body: data,
}).then(response => {
  if (response.ok) {
    response.text().then(response => {
      console.log(response);
    });
  }
});

navigator.sendBeacon()

On the other hand, if you are simply attempting to POST data and do not need a response from the server, the shortest solution would be to use navigator.sendBeacon():

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

navigator.sendBeacon('example.php', data);

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

Unfortunately this is a restriction of the Google maps service.

I am currently working on an application using the geocoding feature, and I'm saving each unique address on a per-user basis. I generate the address information (city, street, state, etc) based on the information returned by Google maps, and then save the lat/long information in the database as well. This prevents you from having to re-code things, and gives you nicely formatted addresses.

Another reason you want to do this is because there is a daily limit on the number of addresses that can be geocoded from a particular IP address. You don't want your application to fail for a person for that reason.

SQL select only rows with max value on a column

SELECT *
FROM Employee
where Employee.Salary in (select max(salary) from Employee group by Employe_id)
ORDER BY Employee.Salary

Generating a PDF file from React Components

npm install jspdf --save

//code on react

import jsPDF from 'jspdf';


var doc = new jsPDF()


 doc.fromHTML("<div>JOmin</div>", 1, 1)


onclick //

 doc.save("name.pdf")

How to delete an object by id with entity framework

If you dont want to query for it just create an entity, and then delete it.

Customer customer  = new Customer() {  Id = 1   } ; 
context.AttachTo("Customers", customer);
context.DeleteObject(customer);
context.Savechanges();

What's the scope of a variable initialized in an if statement?

Scope in python follows this order:

  • Search the local scope

  • Search the scope of any enclosing functions

  • Search the global scope

  • Search the built-ins

(source)

Notice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.

How do you install GLUT and OpenGL in Visual Studio 2012?

For an easy and appropriate way of doing this, first download a prepackaged release of freeglut from here. Then read its Readme.txt.

I copied some important parts of that package here:

... Create a folder on your PC which is readable by all users, for example “C:\Program Files\Common Files\MSVC\freeglut\” on a typical Windows system. Copy the “lib\” and “include\” folders from this zip archive to that location ... freeglut DLL can be placed in the same folder as your application...

... Open up the project properties, and select “All Configurations” (this is necessary to ensure our changes are applied for both debug and release builds). Open up the “general” section under “C/C++”, and configure the “include\” folder you created above as an “Additional Include Directory”. If you have more than one GLUT package which contains a “glut.h” file, it’s important to ensure that the freeglut include folder appears above all other GLUT include folders ... Open up the “general” section under “Linker”, and configure the “lib\” folder you created above as an “Additional Library Directory”...

Current date and time as string

Using C++ in MS Visual Studio 2015 (14), I use:

#include <chrono>

string NowToString()
{
  chrono::system_clock::time_point p = chrono::system_clock::now();
  time_t t = chrono::system_clock::to_time_t(p);
  char str[26];
  ctime_s(str, sizeof str, &t);
  return str;
}

Disable same origin policy in Chrome

On a Windows PC, use an older version of Chrome and the command will work for all you guys. I downgraded my Chrome to 26 version and it worked.

"React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View>

In my case, I just had to put the element one line down:

This throws an error:

_x000D_
_x000D_
export function DismissKeyboard(props: IProps) {
  return <TouchableWithoutFeedback
    onPress={() => Keyboard.dismiss()}> {props.children}
  </TouchableWithoutFeedback>;
}
_x000D_
_x000D_
_x000D_

While this does not throw an error:

_x000D_
_x000D_
export function DismissKeyboard(props: IProps) {
  return <TouchableWithoutFeedback
    onPress={() => Keyboard.dismiss()}>
    {props.children}
  </TouchableWithoutFeedback>;
}
_x000D_
_x000D_
_x000D_

How to query first 10 rows and next time query other 10 rows from table

You can use postgresql Cursors

BEGIN;
DECLARE C CURSOR FOR where * FROM msgtable where cdate='18/07/2012';

Then use

FETCH 10 FROM C;

to fetch 10 rows.

Finnish with

COMMIT;

to close the cursor.

But if you need to make a query in different processes, LIMIT and OFFSET as suggested by @Praveen Kumar is better

Convert integer to class Date

as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

Calling the base constructor in C#

If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.

public class MyClass : BaseClass
{
    private MyClass(string someString) : base(someString)
    {
        //your code goes in here
    }

    public static MyClass FactoryMethod(string someString)
    {
        //whatever you want to do with your string before passing it in
        return new MyClass(someString);
    }
}

Ruby objects and JSON serialization (without Rails)

Jbuilder is a gem built by rails community. But it works well in non-rails environments and have a cool set of features.

# suppose we have a sample object as below
sampleObj.name #=> foo
sampleObj.last_name #=> bar

# using jbuilder we can convert it to json:
Jbuilder.encode do |json|
  json.name sampleObj.name
  json.last_name sampleObj.last_name
end #=> "{:\"name\" => \"foo\", :\"last_name\" => \"bar\"}"

QLabel: set color of text and background

This one is working perfect

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

getColor() method returns the selected color. You can change label color using stylesheet

How to create empty text file from a batch file?

One more to add to the books - short and sweet to type.

break>file.txt
break>"file with spaces in name.txt"

Excel VBA - select multiple columns not in sequential order

Some things of top of my head.

Method 1.

Application.Union(Range("a1"), Range("b1"), Range("d1"), Range("e1"), Range("g1"), Range("h1")).EntireColumn.Select

Method 2.

Range("a1,b1,d1,e1,g1,h1").EntireColumn.Select

Method 3.

Application.Union(Columns("a"), Columns("b"), Columns("d"), Columns("e"), Columns("g"), Columns("h")).Select

Convert hex string (char []) to int?

I know this is really old but I think the solutions looked too complicated. Try this in VB:

Public Function HexToInt(sHEX as String) as long
Dim iLen as Integer
Dim i as Integer 
Dim SumValue as Long 
Dim iVal as long
Dim AscVal as long

    iLen = Len(sHEX)
    For i = 1 to Len(sHEX)
      AscVal = Asc(UCase(Mid$(sHEX, i,  1)))
      If AscVal >= 48 And AscVal  <= 57 Then
        iVal  = AscVal - 48
      ElseIf AscVal >= 65 And AscVal <= 70 Then
        iVal = AscVal - 55
      End If 
      SumValue = SumValue + iVal * 16 ^ (iLen- i)
    Next i 
    HexToInt  = SumValue
End Function 

Can someone give an example of cosine similarity, in a very simple, graphical way?

For simplicity I am reducing the vector a and b:

Let :
    a : [1, 1, 0]
    b : [1, 0, 1]

Then cosine similarity (Theta):

 (Theta) = (1*1 + 1*0 + 0*1)/sqrt((1^2 + 1^2))* sqrt((1^2 + 1^2)) = 1/2 = 0.5

then inverse of cos 0.5 is 60 degrees.

How do I convert a PDF document to a preview image in PHP?

Here is a simple class I've written and used on a couple of projects. It just wraps imagick and handles writing each page out to disk. If anyone is still looking for an easy way to do this, this link might be helpful.

SELECT FOR UPDATE with SQL Server

Create a fake update to enforce the rowlock.

UPDATE <tablename> (ROWLOCK) SET <somecolumn> = <somecolumn> WHERE id=1

If that's not locking your row, god knows what will.

After this "UPDATE" you can do your SELECT (ROWLOCK) and subsequent updates.

Why use pip over easy_install?

Another—as of yet unmentioned—reason for favoring pip is because it is the new hotness and will continue to be used in the future.

The infographic below—from the Current State of Packaging section in the The Hitchhiker's Guide to Packaging v1.0—shows that setuptools/easy_install will go away in the future.

enter image description here

Here's another infographic from distribute's documentation showing that Setuptools and easy_install will be replaced by the new hotness—distribute and pip. While pip is still the new hotness, Distribute merged with Setuptools in 2013 with the release of Setuptools v0.7.

enter image description here

Getting attribute of element in ng-click function in angularjs

Try passing it directly to the ng-click function:

<div class="col-lg-1 text-center">
    <span class="glyphicon glyphicon-trash" data="{{event.id}}"
          ng-click="deleteEvent(event.id)"></span>
</div>

Then it should be available in your handler:

$scope.deleteEvent=function(idPassedFromNgClick){
    console.log(idPassedFromNgClick);
}

Here's an example

What are the differences between numpy arrays and matrices? Which one should I use?

Scipy.org recommends that you use arrays:

*'array' or 'matrix'? Which should I use? - Short answer

Use arrays.

  • They are the standard vector/matrix/tensor type of numpy. Many numpy function return arrays, not matrices.

  • There is a clear distinction between element-wise operations and linear algebra operations.

  • You can have standard vectors or row/column vectors if you like.

The only disadvantage of using the array type is that you will have to use dot instead of * to multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.).

Laravel Eloquent where field is X or null

You could merge two queries together:

$merged = $query_one->merge($query_two);

How do I disable fail_on_empty_beans in Jackson?

If you wish to get JSON object without any extra fields - please add this annotation to your class, it worked perfect for me.

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

You can also add in your application.properties file this row, but it will add an extra field to your JSON.

spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false

Escaping HTML strings with jQuery

After last tests I can recommend fastest and completely cross browser compatible native javaScript (DOM) solution:

function HTMLescape(html){
    return document.createElement('div')
        .appendChild(document.createTextNode(html))
        .parentNode
        .innerHTML
}

If you repeat it many times you can do it with once prepared variables:

//prepare variables
var DOMtext = document.createTextNode("test");
var DOMnative = document.createElement("span");
DOMnative.appendChild(DOMtext);

//main work for each case
function HTMLescape(html){
  DOMtext.nodeValue = html;
  return DOMnative.innerHTML
}

Look at my final performance comparison (stack question).

Strangest language feature

To alternate between things in many languages:

boolean b = true;
for(int i = 0; i < 10; i++)
  if(b = !b)
    print i;

on first glance: how can b really not be equal to itself!? This acctually would print odd numbers only

Laravel 5 route not defined, while it is?

I'm using Laravel 5.7 and tried all of the above answers but nothing seemed to be hitting the spot.

For me, it was a rather simple fix by removing the cache files created by Laravel.
It seemed that my changes were not being reflected, and therefore my application wasn't seeing the routes.

A bit overkill, but I decided to reset all my cache at the same time using the following commands:

php artisan route:clear
php artisan view:clear
php artisan cache:clear

The main one here is the first command which will delete the bootstrap/cache/routes.php file.
The second command will remove the cached files for the views that are stored in the storage/framework/cache folder.
Finally, the last command will clear the application cache.

How to check if a Constraint exists in Sql server?

try this:

SELECT
    * 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    WHERE CONSTRAINT_NAME ='FK_ChannelPlayerSkins_Channels'

-- EDIT --

When I originally answered this question, I was thinking "Foreign Key" because the original question asked about finding "FK_ChannelPlayerSkins_Channels". Since then many people have commented on finding other "constraints" here are some other queries for that:

--Returns one row for each CHECK, UNIQUE, PRIMARY KEY, and/or FOREIGN KEY
SELECT * 
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_NAME='XYZ'  


--Returns one row for each FOREIGN KEY constrain
SELECT * 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    WHERE CONSTRAINT_NAME='XYZ'


--Returns one row for each CHECK constraint 
SELECT * 
    FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS
    WHERE CONSTRAINT_NAME='XYZ'

here is an alternate method

--Returns 1 row for each CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY, and/or DEFAULT
SELECT 
    OBJECT_NAME(OBJECT_ID) AS NameofConstraint
        ,SCHEMA_NAME(schema_id) AS SchemaName
        ,OBJECT_NAME(parent_object_id) AS TableName
        ,type_desc AS ConstraintType
    FROM sys.objects
    WHERE type_desc LIKE '%CONSTRAINT'
        AND OBJECT_NAME(OBJECT_ID)='XYZ'

If you need even more constraint information, look inside the system stored procedure master.sys.sp_helpconstraint to see how to get certain information. To view the source code using SQL Server Management Studio get into the "Object Explorer". From there you expand the "Master" database, then expand "Programmability", then "Stored Procedures", then "System Stored Procedures". You can then find "sys.sp_helpconstraint" and right click it and select "modify". Just be careful to not save any changes to it. Also, you can just use this system stored procedure on any table by using it like EXEC sp_helpconstraint YourTableNameHere.

'nuget' is not recognized but other nuget commands working

In Visual Studio:

Tools -> Nuget Package Manager -> Package Manager Console.

In PM:

Install-Package NuGet.CommandLine

Close Visual Studio and open it again.

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...
    }
}

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

Could not load NIB in bundle

DO NOT PUT .xib WHEN YOU INSERT IN THE XIB NAME! IT IS ALREADY IMPLIED!

Dont do this:

 UIView *viewFromNib = [[NSBundle mainBundle] loadNibNamed:@"ResultsAssessmentView.xib" owner:self options:nil][0];

Do this:

 UIView *viewFromNib = [[NSBundle mainBundle] loadNibNamed:@"ResultsAssessmentView" owner:self options:nil][0];

What is event bubbling and capturing?

Description:

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

Event capturing

When you use event capturing

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

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

Event bubbling

When you use event bubbling

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

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


What to use?

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

How to declare an ArrayList with values?

Use this one:

ArrayList<String> x = new ArrayList(Arrays.asList("abc", "mno"));

How to set the current working directory?

It work for Mac also

import os
path="/Users/HOME/Desktop/Addl Work/TimeSeries-Done"
os.chdir(path)

To check working directory

os.getcwd()

How to change style of a default EditText

Now For AppCompatEditText

Note: We need to use app:backgroundTint instead of android:backgroundTint

<android.support.v7.widget.AppCompatEditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:hint="Underline color change"
    app:backgroundTint="@color/blue_gray_light" />

Blurring an image via CSS?

You can use CSS3 filters. They are relatively easy to implement, though are only supported on webkit at the minute. Samsung Galaxy 2's browser should support though, as I think that's a webkit browser?

How to set the first option on a select box using jQuery?

Something like this should do the trick: https://jsfiddle.net/TmJCE/898/

$('#name2').change(function(){
    $('#name').prop('selectedIndex',0);
});


$('#name').change(function(){
    $('#name2').prop('selectedIndex',0);
});

Converting a PDF to PNG

For a PDF that ImageMagick was giving inaccurate colors I found that GraphicsMagick did a better job:

$ gm convert -quality 100 -thumbnail x300 -flatten journal.pdf\[0\] cover.jpg

How to remove all of the data in a table using Django

Inside a manager:

def delete_everything(self):
    Reporter.objects.all().delete()

def drop_table(self):
    cursor = connection.cursor()
    table_name = self.model._meta.db_table
    sql = "DROP TABLE %s;" % (table_name, )
    cursor.execute(sql)

How do I pass command line arguments to a Node.js program?

A simple snippet if any need it:

var fs = require('fs'), objMod = {};

process.argv.slice(2).map(function(y, i) {
  y = y.split('=');
  if (y[0] && y[1]) objMod[y[0]] = y[1];
  else console.log('Error in argument number ' + (i+1));
});

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

I got a similar prompt. It was because I had specified the x-axis in terms of some percentage (for example: 10%A, 20%B,....). So an alternate approach could be that you multiply these values and write them in the simplest form.

What is the best way to check for Internet connectivity using .NET?

Try to avoid testing connections by catching the exception. because we really Expect that sometimes we may lose network connection.

 if (NetworkInterface.GetIsNetworkAvailable() &&
     new Ping().Send(new IPAddress(new byte[] { 8, 8, 8, 8 }),2000).Status == IPStatus.Success)
 //is online
 else
 //is offline

Is it possible to declare a variable in Gradle usable in Java?

I'm using this code and working very fine.

def baseUrl = '\"http://patelwala.com/myapi/"'
def googleServerKey = '\"87171841097-opu71rk2ps35ibv96ud57g3ktto6ioio.apps.googleusercontent.com"'
android {
  buildTypes {
  release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id', googleServerKey
    }
    releasedebug {
        initWith debug
        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id' ,googleServerKey
    }
    debug {

        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id', googleServerKey
    }
 }
}

}

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

Do it like this:

var value = $("#text").val(); // value = 9.61 use $("#text").text() if you are not on select box...
value = value.replace(".", ":"); // value = 9:61
// can then use it as
$("#anothertext").val(value);

Updated to reflect to current version of jQuery. And also there are a lot of answers here that would best fit to any same situation as this. You, as a developer, need to know which is which.

Replace all occurrences

To replace multiple characters at a time use some thing like this: name.replace(/&/g, "-"). Here I am replacing all & chars with -. g means "global"

Note - you may need to add square brackets to avoid an error - title.replace(/[+]/g, " ")

credits vissu and Dante Cullari