Programs & Examples On #Redgate

Redgate Software makes tools for Microsoft Developers working with SQL, .NET, Oracle and Cloud. The tools are designed to optimise the deployment process for database development team. For .NET developers, Redgate tools help to optimise software performance and improving quality of software.

Something better than .NET Reflector?

The .NET source code is available now.

See this link or this

Or if you look for a decompiler, I was using DisSharper. It was good enough for me.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Personally I'd go with AJAX.

If you cannot switch to @Ajax... helpers, I suggest you to add a couple of properties in your model

public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }

Change your view to a strongly typed Model via

@using MyModel

Before returning the View, in case of successfull creation do something like

MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);

then in your view, add this

@{
   if (model.TriggerOnLoad) {
   <text>
   <script type="text/javascript">
     alert('@Model.TriggerOnLoadMessage');
   </script>
   </text>
   }
}

Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:

$(document).ready(function () {
   alert('@Model.TriggerOnLoadMessage');
});

Please remember to reset the Model properties upon successfully alert emission.

Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:

@Html.EditorFor (m => m.TriggerOnLoadMessage)

But in case you want to build up such a thing, maybe it's better to define your own C# class:

class ClientMessageNotification {
    public bool TriggerOnLoad { get; set; }
    public string TriggerOnLoadMessage { get; set: }
}

and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.

How to retrieve a single file from a specific revision in Git?

Using git show

To complete your own answer, the syntax is indeed

git show object
git show $REV:$FILE
git show somebranch:from/the/root/myfile.txt
git show HEAD^^^:test/test.py

The command takes the usual style of revision, meaning you can use any of the following:

  1. branch name (as suggested by ash)
  2. HEAD + x number of ^ characters
  3. The SHA1 hash of a given revision
  4. The first few (maybe 5) characters of a given SHA1 hash

Tip It's important to remember that when using "git show", always specify a path from the root of the repository, not your current directory position.

(Although Mike Morearty mentions that, at least with git 1.7.5.4, you can specify a relative path by putting "./" at the beginning of the path. For example:

git show HEAD^^:./test.py

)

Using git restore

With Git 2.23+ (August 2019), you can also use git restore which replaces the confusing git checkout command

git restore -s <SHA1>     -- afile
git restore -s somebranch -- afile

That would restore on the working tree only the file as present in the "source" (-s) commit SHA1 or branch somebranch.
To restore also the index:

git restore -s <SHA1> -SW -- afile

(-SW: short for --staged --worktree)

Using low-level git plumbing commands

Before git1.5.x, this was done with some plumbing:

git ls-tree <rev>
show a list of one or more 'blob' objects within a commit

git cat-file blob <file-SHA1>
cat a file as it has been committed within a specific revision (similar to svn cat). use git ls-tree to retrieve the value of a given file-sha1

git cat-file -p $(git-ls-tree $REV $file | cut -d " " -f 3 | cut -f 1)::

git-ls-tree lists the object ID for $file in revision $REV, this is cut out of the output and used as an argument to git-cat-file, which should really be called git-cat-object, and simply dumps that object to stdout.


Note: since Git 2.11 (Q4 2016), you can apply a content filter to the git cat-file output.

See commit 3214594, commit 7bcf341 (09 Sep 2016), commit 7bcf341 (09 Sep 2016), and commit b9e62f6, commit 16dcc29 (24 Aug 2016) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 7889ed2, 21 Sep 2016)

git config diff.txt.textconv "tr A-Za-z N-ZA-Mn-za-m <"
git cat-file --textconv --batch

Note: "git cat-file --textconv" started segfaulting recently (2017), which has been corrected in Git 2.15 (Q4 2017)

See commit cc0ea7c (21 Sep 2017) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfbc2fc, 28 Sep 2017)

MS Access - execute a saved query by name in VBA

You should investigate why VBA can't find queryname.

I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute.

CurrentDb.Execute "qryAddLoginfoRow"

My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.

Edit: You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute line.

Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name

The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb to Execute.

MySQL error code: 1175 during UPDATE in MySQL Workbench

SET SQL_SAFE_UPDATES = 0;

# your code SQL here

SET SQL_SAFE_UPDATES = 1;

Alternate background colors for list items

You can do it by specifying alternating class names on the rows. I prefer using row0 and row1, which means you can easily add them in, if the list is being built programmatically:

for ($i = 0; $i < 10; ++$i) {
    echo '<tr class="row' . ($i % 2) . '">...</tr>';
}

Another way would be to use javascript. jQuery is being used in this example:

$('table tr:odd').addClass('row1');

Edit: I don't know why I gave examples using table rows... replace tr with li and table with ul and it applies to your example

How to get a variable type in Typescript?

I suspect you can adjust your approach a little and use something along the lines of the example here:

https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

Emulate Samsung Galaxy Tab

I found under website.

http://developer.samsung.com/android/tools-sdks/Samsung-GALAXY-Tab-Emulator

Extract zip file to add-ons under android sdk path. then launch Android SDK Manager. under "extras" folder check "Android + Google APIs for GALAXY Tab, API 8, revision 1" item and install package.

That's all.

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

in my case I was missing to write in web.xml:

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:applicationContext.xml</param-value>
   </context-param>

and in the application context file:

<context:component-scan base-package=[your package name] />

after add this tags and run maven to rebuild project the autowired error in intellj desapears and the bean icon appears in the left margin: enter image description here

How do I check to see if my array includes an object?

If you want to check if an object is within in array by checking an attribute on the object, you can use any? and pass a block that evaluates to true or false:

unless @suggested_horses.any? {|h| h.id == horse.id }
  @suggested_horses << horse
end

ToString() function in Go

When you have own struct, you could have own convert-to-string function.

package main

import (
    "fmt"
)

type Color struct {
    Red   int `json:"red"`
    Green int `json:"green"`
    Blue  int `json:"blue"`
}

func (c Color) String() string {
    return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}

func main() {
    c := Color{Red: 123, Green: 11, Blue: 34}
    fmt.Println(c) //[123, 11, 34]
}

Make the image go behind the text and keep it in center using CSS

There are two ways to handle this.

  • Background Image
  • Using z-index property of CSS

The background image is probably easier. You need a fixed width somewhere.

.background-image {
    width: 400px;
    background: url(background.png) 50% 50%;
}
<form><div class="background-image"></div></form>

How to get the browser viewport dimensions?

I looked and found a cross browser way:

_x000D_
_x000D_
function myFunction(){_x000D_
  if(window.innerWidth !== undefined && window.innerHeight !== undefined) { _x000D_
    var w = window.innerWidth;_x000D_
    var h = window.innerHeight;_x000D_
  } else {  _x000D_
    var w = document.documentElement.clientWidth;_x000D_
    var h = document.documentElement.clientHeight;_x000D_
  }_x000D_
  var txt = "Page size: width=" + w + ", height=" + h;_x000D_
  document.getElementById("demo").innerHTML = txt;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <body onresize="myFunction()" onload="myFunction()">_x000D_
   <p>_x000D_
    Try to resize the page._x000D_
   </p>_x000D_
   <p id="demo">_x000D_
    &nbsp;_x000D_
   </p>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to index into a dictionary?

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use d.keys()[i] and d.values()[i] or d.items()[i]. (Note that these methods create a list of all keys, values or items in Python 2.x. So if you need them more then once, store the list in a variable to improve performance.)

If you do care about the order of the entries, starting with Python 2.7 you can use collections.OrderedDict. Or use a list of pairs

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

if you don't need access by key. (Why are your numbers strings by the way?)

In Python 3.7, normal dictionaries are ordered, so you don't need to use OrderedDict anymore (but you still can – it's basically the same type). The CPython implementation of Python 3.6 already included that change, but since it's not part of the language specification, you can't rely on it in Python 3.6.

How to change TextField's height and width?

You can try the margin property in the Container. Wrap the TextField inside a Container and adjust the margin property.

new Container(
  margin: const EdgeInsets.only(right: 10, left: 10),
  child: new TextField( 
    decoration: new InputDecoration(
      hintText: 'username',
      icon: new Icon(Icons.person)),
  )
),

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

So ridiculous, but I still wanna share my experience in case of that someone falls into the situation like me.

Please check if you changed: compileSdkVersion --> implementationSdkVersion by mistake

Creating Dynamic button with click event in JavaScript

this:

element.setAttribute("onclick", alert("blabla"));

should be:

element.onclick = function () {
  alert("blabla");
}

Because you call alert instead push alert as string in attribute

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

Call a url from javascript

Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.

In jQuery:

$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })

In plain vanilla javaScript (from w3c):

var xmlhttp;
function loadXMLDoc(url)
{
    xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for all new browsers
      xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
  }
else
  {
      alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
    if (xmlhttp.readyState==4)
      {// 4 = "loaded"
          if (xmlhttp.status==200)
            {// 200 = OK
             //xmlhttp.data and shtuff
            // ...our code here...
        }
  else
        {
            alert("Problem retrieving data");
        }
  }
}

What is the use of "assert"?

From docs:

Assert statements are a convenient way to insert debugging assertions into a program

You can read more here: http://docs.python.org/release/2.5.2/ref/assert.html

Show ImageView programmatically

//LinearLayOut Setup
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));

//ImageView Setup
ImageView imageView = new ImageView(this);

//setting image resource
imageView.setImageResource(R.drawable.play);

//setting image position
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
LayoutParams.WRAP_CONTENT));

//adding view to layout
linearLayout.addView(imageView);
//make visible to program
setContentView(linearLayout);

jQuery get html of container including the container itself

Firefox doesn't support outerHTML, so you need to define a function to help support it:

function outerHTML(node) {
    return node.outerHTML || (
        function(n) {
            var div = document.createElement('div');
            div.appendChild( n.cloneNode(true) );
            var h = div.innerHTML;
            div = null;
            return h;
        }
    )(node);
}

Then, you can use outerHTML:

var x = outerHTML($('#container').get(0));
$('#save').val(x);

What is better, adjacency lists or adjacency matrices for graph problems in C++?

I am just going to touch on overcoming the trade-off of regular adjacency list representation, since other answers have covered other aspects.

It is possible to represent a graph in adjacency list with EdgeExists query in amortized constant time, by taking advantage of Dictionary and HashSet data structures. The idea is to keep vertices in a dictionary, and for each vertex, we keep a hash set referencing to other vertices it has edges with.

One minor trade-off in this implementation is that it will have space complexity O(V + 2E) instead of O(V + E) as in regular adjacency list, since edges are represented twice here (because each vertex have its own hash set of edges). But operations such as AddVertex, AddEdge, RemoveEdge can be done in amortized time O(1) with this implementation, except for RemoveVertex which takes O(V) like adjacency matrix. This would mean that other than implementation simplicity, adjacency matrix don't have any specific advantage. We can save space on sparse graph with almost the same performance in this adjacency list implementation.

Take a look at implementations below in Github C# repository for details. Note that for weighted graph it uses a nested dictionary instead of dictionary-hash set combination so as to accommodate weight value. Similarly for directed graph there is separate hash sets for in & out edges.

Advanced-Algorithms

Note: I believe using lazy deletion we can further optimize RemoveVertex operation to O(1) amortized, even though I haven't tested that idea. For example, upon deletion just mark the vertex as deleted in dictionary, and then lazily clear orphaned edges during other operations.

get enum name from enum value

In my case value was not an integer but a String. getNameByCode method can be added to the enum to get name of a String value-

enum CODE {
    SUCCESS("SCS"), DELETE("DEL");

    private String status;

    /**
     * @return the status
     */
    public String getStatus() {
        return status;
    }

    /**
     * @param status
     *            the status to set
     */
    public void setStatus(String status) {
        this.status = status;
    }

    private CODE(String status) {
        this.status = status;
    }

    public static String getNameByCode(String code) {
        for (int i = 0; i < CODE.values().length; i++) {
            if (code.equals(CODE.values()[i].status))
                return CODE.values()[i].name();
        }
        return null;
    }

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

Delete ActionLink with confirm dialog

those are routes you're passing in

<%= Html.ActionLink("Delete", "Delete",
    new { id = item.storyId }, 
    new { onclick = "return confirm('Are you sure you wish to delete this article?');" })     %>

The overloaded method you're looking for is this one:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    Object routeValues,
    Object htmlAttributes
)

http://msdn.microsoft.com/en-us/library/dd492124.aspx

How to get Exception Error Code in C#

You can use this to check the exception and the inner exception for a Win32Exception derived exception.

catch (Exception e) {  
    var w32ex = e as Win32Exception;
    if(w32ex == null) {
        w32ex = e.InnerException as Win32Exception;
    }    
    if(w32ex != null) {
        int code =  w32ex.ErrorCode;
        // do stuff
    }    
    // do other stuff   
}

Starting with C# 6, when can be used in a catch statement to specify a condition that must be true for the handler for a specific exception to execute.

catch (Win32Exception ex) when (ex.InnerException is Win32Exception) {
    var w32ex = (Win32Exception)ex.InnerException;
    var code =  w32ex.ErrorCode;
}

As in the comments, you really need to see what exception is actually being thrown to understand what you can do, and in which case a specific catch is preferred over just catching Exception. Something like:

  catch (BlahBlahException ex) {  
      // do stuff   
  }

Also System.Exception has a HRESULT

 catch (Exception ex) {  
     var code = ex.HResult;
 }

However, it's only available from .NET 4.5 upwards.

Number of processors/cores in command line

When someone asks for "the number of processors/cores" there are 2 answers being requested. The number of "processors" would be the physical number installed in sockets on the machine.

The number of "cores" would be physical cores. Hyperthreaded (virtual) cores would not be included (at least to my mind). As someone who writes a lot of programs with thread pools, you really need to know the count of physical cores vs cores/hyperthreads. That said, you can modify the following script to get the answers that you need.

#!/bin/bash

MODEL=`cat /cpu/procinfo | grep "model name" | sort | uniq`
ALL=`cat /proc/cpuinfo | grep "bogo" | wc -l`
PHYSICAL=`cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l`
CORES=`cat /proc/cpuinfo | grep "cpu cores" | sort | uniq | cut -d':' -f2`
PHY_CORES=$(($PHYSICAL * $CORES))
echo "Type $MODEL"
echo "Processors $PHYSICAL"
echo "Physical cores $PHY_CORES"
echo "Including hyperthreading cores $ALL"

The result on a machine with 2 model Xeon X5650 physical processors each with 6 physical cores that also support hyperthreading:

Type model name : Intel(R) Xeon(R) CPU           X5650  @ 2.67GHz
Processors 2
Physical cores 12
Including hyperthreading cores 24

On a machine with 2 mdeol Xeon E5472 processors each with 4 physical cores that doesn't support hyperthreading

Type model name : Intel(R) Xeon(R) CPU           E5472  @ 3.00GHz
Processors 2
Physical cores 8
Including hyperthreading cores 8

How do I negate a condition in PowerShell?

Powershell also accept the C/C++/C* not operator

if ( !(Test-Path C:\Code) ){ write "it doesn't exist!" }

I use it often because I'm used to C*...
allows code compression/simplification...
I also find it more elegant...

How may I sort a list alphabetically using jQuery?

@SolutionYogi's answer works like a charm, but it seems that using $.each is less straightforward and efficient than directly appending listitems :

var mylist = $('#list');
var listitems = mylist.children('li').get();

listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})

mylist.empty().append(listitems);

Fiddle

Loop through all the resources in a .resx file

Blogged about it on my blog :) Short version is, to find the full names of the resources(unless you already know them):

var assembly = Assembly.GetExecutingAssembly();

foreach (var resourceName in assembly.GetManifestResourceNames())
    System.Console.WriteLine(resourceName);

To use all of them for something:

foreach (var resourceName in assembly.GetManifestResourceNames())
{
    using(var stream = assembly.GetManifestResourceStream(resourceName))
    {
        // Do something with stream
    }
}

To use resources in other assemblies than the executing one, you'd just get a different assembly object by using some of the other static methods of the Assembly class. Hope it helps :)

PermissionError: [Errno 13] Permission denied

Change the permissions of the directory you want to save to so that all users have read and write permissions.

estimating of testing effort as a percentage of development time

When you speak of tests, you could mean waterfall or agile test development. In an agile environment, developers should spend 50% of their time developing and maintaining tests.

But that 50% extra will save you time when the re-factoring and manual verification time comes.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

Rotating a two-dimensional array in Python

Rotating Counter Clockwise ( standard column to row pivot ) As List and Dict

rows = [
  ['A', 'B', 'C', 'D'],
  [1,2,3,4],
  [1,2,3],
  [1,2],
  [1],
]

pivot = []

for row in rows:
  for column, cell in enumerate(row):
    if len(pivot) == column: pivot.append([])
    pivot[column].append(cell)

print(rows)
print(pivot)
print(dict([(row[0], row[1:]) for row in pivot]))

Produces:

[['A', 'B', 'C', 'D'], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1]]
[['A', 1, 1, 1, 1], ['B', 2, 2, 2], ['C', 3, 3], ['D', 4]]
{'A': [1, 1, 1, 1], 'B': [2, 2, 2], 'C': [3, 3], 'D': [4]}

Correct way to initialize HashMap and can HashMap hold different value types?

Eclipse is suggesting you to define generic type so that you can have type safety. You can write

Map m = new HashMap();

which does not ensure type safety but following will ensure type safety

Map<Object,Object> = new HashMap<Object,Object>();

The Object can be any type such as String, Integer etc.

Can I use a case/switch statement with two variables?

Yes you can also do:

    switch (true) {

     case (var1 === true && var2 === true) :
       //do something
       break;
     case (var1 === false && var2 === false) :
       //do something
       break;

      default:

    }

This will always execute the switch, pretty much just like if/else but looks cleaner. Just continue checking your variables in the case expressions.

How do you create a UIImage View Programmatically - Swift

First create UIImageView then add image in UIImageView .

    var imageView : UIImageView
    imageView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
    imageView.image = UIImage(named:"image.jpg")
    self.view.addSubview(imageView)

Append key/value pair to hash with << in Ruby

Similar as they are, merge! and store treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!'s key: "value" syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.

hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash

{:key=>"value"}

hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash

{:key=>"value", "key"=>"value"}

To get the shovel operator << working, I would advise using Mark Thomas's answer.

Get local href value from anchor (a) tag

The href property sets or returns the value of the href attribute of a link.

  var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
    var url="https://www.google.com/";
    console.log( url+hello);

Swift Error: Editor placeholder in source file

you had this

destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)

which was place holder text above you need to insert some values

class Edge{

}

public class Node{

  var key: String?
  var neighbors: [Edge]
  var visited: Bool = false
  var lat: Double
  var long: Double

  init(key: String?, neighbors: [Edge], visited: Bool, lat: Double, long: Double) {
    self.neighbors = [Edge]()
    self.key = key
    self.visited = visited
    self.lat = lat
    self.long = long
  }

}

class Path {

  var total: Int!
  var destination: Node
  var previous: Path!

  init(){
    destination = Node(key: "", neighbors: [], visited: true, lat: 12.2, long: 22.2)
  }
}

Leap year calculation

In the Gregorian calendar 3 criteria must be taken into account to identify leap years:

  1. The year is evenly divisible by 4;
  2. If the year can be evenly divided by 100, it is NOT a leap year, unless;
  3. The year is also evenly divisible by 400. Then it is a leap year. Why the year divided by 100 is not leap year

Create PDF from a list of images

first pip install pillow in command line Interface. Images can be in jpg or png format. if you have 2 or more images and want to make in 1 pdf file.

Code:

from PIL import Image

image1 = Image.open(r'locationOfImage1\\Image1.png')
image2 = Image.open(r'locationOfImage2\\Image2.png')
image3 = Image.open(r'locationOfImage3\\Image3.png')

im1 = image1.convert('RGB')
im2 = image2.convert('RGB')
im3 = image3.convert('RGB')

imagelist = [im2,im3]

im1.save(r'locationWherePDFWillBeSaved\\CombinedPDF.pdf',save_all=True, append_images=imagelist)

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

Retrieving data from a POST method in ASP.NET

You can get a form value posted to a page using code similiar to this (C#) -

string formValue;
if (!string.IsNullOrEmpty(Request.Form["txtFormValue"]))
{
  formValue= Request.Form["txtFormValue"];
}

or this (VB)

Dim formValue As String
If Not String.IsNullOrEmpty(Request.Form("txtFormValue")) Then
    formValue = Request.Form("txtFormValue")
End If

Once you have the values you need you can then construct a SQL statement and and write the data to a database.

Hiding user input on terminal in Linux script

Just supply -s to your read call like so:

$ read -s PASSWORD
$ echo $PASSWORD

check null,empty or undefined angularjs

You can use angular's function called angular.isUndefined(value) returns boolean.

You may read more about angular's functions here: AngularJS Functions (isUndefined)

'pip' is not recognized as an internal or external command

For me the command:

set PATH=%PATH%;C:\Python34\Scripts

worked immediately (try after echo %PATH% and you will see that your path has the value C:\Python34\Scripts).

Thanks to: Adding a directory to the PATH environment variable in Windows

Firebase Permission Denied

Another solution is to actually create or login the user automatically if you already have the credentials handy. Here is how I do it using Plain JS.

function loginToFirebase(callback)
{
    let email = '[email protected]';
    let password = 'xxxxxxxxxxxxxx';
    let config =
    {
        apiKey: "xxx",
        authDomain: "xxxxx.firebaseapp.com",
        projectId: "xxx-xxx",
        databaseURL: "https://xxx-xxx.firebaseio.com",
        storageBucket: "gs://xx-xx.appspot.com",
    };

    if (!firebase.apps.length)
    {
        firebase.initializeApp(config);
    }

    let database = firebase.database();
    let storage = firebase.storage();

    loginFirebaseUser(email, password, callback);
}

function loginFirebaseUser(email, password, callback)
{
    console.log('Logging in Firebase User');

    firebase.auth().signInWithEmailAndPassword(email, password)
        .then(function ()
        {
            if (callback)
            {
                callback();
            }
        })
        .catch(function(login_error)
        {
            let loginErrorCode = login_error.code;
            let loginErrorMessage = login_error.message;

            console.log(loginErrorCode);
            console.log(loginErrorMessage);

            if (loginErrorCode === 'auth/user-not-found')
            {
                createFirebaseUser(email, password, callback)
            }
        });
}

function createFirebaseUser(email, password, callback)
{
    console.log('Creating Firebase User');

    firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(function ()
        {
            if (callback)
            {
                callback();
            }
        })
        .catch(function(create_error)
        {
            let createErrorCode = create_error.code;
            let createErrorMessage = create_error.message;

            console.log(createErrorCode);
            console.log(createErrorMessage);
        });
}

Get all table names of a particular database by SQL query?

The following query will select all of the Tables in the database named DBName:

USE DBName
GO 
SELECT *
FROM sys.Tables
GO

How do I programmatically "restart" an Android app?

in MainActivity call restartActivity Method:

public static void restartActivity(Activity mActivity) {
    Intent mIntent = mActivity.getIntent();
    mActivity.finish();
    mActivity.startActivity(mIntent);
}

Better way to convert file sizes in Python

Here is my implementation:

from bisect import bisect

def to_filesize(bytes_num, si=True):
    decade = 1000 if si else 1024
    partitions = tuple(decade ** n for n in range(1, 6))
    suffixes = tuple('BKMGTP')

    i = bisect(partitions, bytes_num)
    s = suffixes[i]

    for n in range(i):
        bytes_num /= decade

    f = '{:.3f}'.format(bytes_num)

    return '{}{}'.format(f.rstrip('0').rstrip('.'), s)

It will print up to three decimals and it strips trailing zeros and periods. The boolean parameter si will toggle usage of 10-based vs. 2-based size magnitude.

This is its counterpart. It allows to write clean configuration files like {'maximum_filesize': from_filesize('10M'). It returns an integer that approximates the intended filesize. I am not using bit shifting because the source value is a floating point number (it will accept from_filesize('2.15M') just fine). Converting it to an integer/decimal would work but makes the code more complicated and it already works as it is.

def from_filesize(spec, si=True):
    decade = 1000 if si else 1024
    suffixes = tuple('BKMGTP')

    num = float(spec[:-1])
    s = spec[-1]
    i = suffixes.index(s)

    for n in range(i):
        num *= decade

    return int(num)

Get the week start date and week end date from week number

Week Start & End Date From Date For Power BI Dax Formula

WeekStartDate = [DateColumn] - (WEEKDAY([DateColumn])-1)
WeekEndDate = [DateColumn] + (7-WEEKDAY([DateColumn]))

delete image from folder PHP

You can delete files in PHP using the unlink() function.

unlink('path/to/file.jpg');

How do I prevent people from doing XSS in Spring MVC?

When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.

I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91

Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.

Share data between html pages

Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)

I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.

But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.

These two links might help you, it shows the example via Node backend, but you get the point how it works:

Link 1

And, of course, the CORS spec:

Link 2

~Cheers

What is the meaning of the prefix N in T-SQL statements and when should I use it?

It's declaring the string as nvarchar data type, rather than varchar

You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.

To quote from Microsoft:

Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.


If you want to know the difference between these two data types, see this SO post:

What is the difference between varchar and nvarchar?

Getting fb.me URL

You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

The code from the accepted answer helped me to debug the issue. I then realized that the SN field of the certificate argument wasn't the same as what I thought was my SMTP server. By setting the Host property of the SmtpClient instance to the SN value of the certificate I was able to fix the issue.

Is there an equivalent of CSS max-width that works in HTML emails?

Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

If you want your content aligned left instead of centered, just leave out the first empty cell.

Example:

<table border="0" cellspacing="0" width="100%">
    <tr>
        <td></td>
        <td width="350">The width of this cell should be a maximum of 
                  350 pixels, but shrink to widths less than 350 pixels.
        </td>
        <td></td>
     </tr>
</table> 

In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

http://jsfiddle.net/YcwM7/

How do I get class name in PHP?

<?php
namespace CMS;
class Model {
  const _class = __CLASS__;
}

echo Model::_class; // will return 'CMS\Model'

for older than PHP 5.5

Detect Close windows event by jQuery

You can use:

$(window).unload(function() {
    //do something
}

Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.

The beforeunload event fires whenever the user leaves your page for any reason.

$(window).on("beforeunload", function() { 
    return confirm("Do you really want to close?"); 
})

Source Browser window close event

Real-world examples of recursion

Everything where you use iteration is done more natural with recursion if it where not for the practical limitation of causing a stack overflow ;-)

But seriously Recursion and Iteration are very interchangeable you can rewrite all algorithm using recursion to use iteration and vise versa. Mathematicians like recursion and programmers like iteration. That is probably also why you see all these contrived examples you mention. I think the method of mathematical proof called Mathematical induction has something to do why mathematicians like recursion. http://en.wikipedia.org/wiki/Mathematical_induction

How to set a CheckBox by default Checked in ASP.Net MVC

An alternative solution is using jQuery:

    <script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            PrepareCheckbox();
        });
        function PrepareCheckbox(){
            document.getElementById("checkbox").checked = true;
        }
    </script>

Override body style for content in an iframe

An iframe has another scope, so you can't access it to style or to change its content with javascript.

It's basically "another page".

The only thing you can do is to edit its own CSS, because with your global CSS you can't do anything.

How to find index of STRING array in Java from a given value?

String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
    if (TYPES[i].equals(carName)) {
        index = i;
        break;
    }
}

After this index is the array index of your car, or -1 if it doesn't exist.

How to change a field name in JSON using Jackson

There is one more option to rename field:

Jackson MixIns.

Useful if you deal with third party classes, which you are not able to annotate, or you just do not want to pollute the class with Jackson specific annotations.

The Jackson documentation for Mixins is outdated, so this example can provide more clarity. In essence: you create mixin class which does the serialization in the way you want. Then register it to the ObjectMapper:

objectMapper.addMixIn(ThirdParty.class, MyMixIn.class);

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Because inheritance is overused even when you can't say "hey, that method looks useful, I'll extend that class as well".

public class MyGodClass extends AppDomainObject, HttpServlet, MouseAdapter, 
             AbstractTableModel, AbstractListModel, AbstractList, AbstractMap, ...

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

lets keep it short :

CI: A software development practice where members of a team integrate their work at least daily. Each integration is verified by automated build (include tests)to detect error as quick as possible. CD: CD Builds on CI, where you build software in such a way that the software can be released to production at any time.

Creating a UICollectionView programmatically

swift 4 code


//
//  ViewController.swift
//  coolectionView
//




import UIKit

class ViewController: UIViewController , UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    @IBOutlet weak var collectionView: UICollectionView!

    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        if indexPath.row % 3 != 0
        {
        return CGSize(width:collectionView.frame.width/2 - 7.5 , height: 100)
        }
        else
        {
            return CGSize(width:collectionView.frame.width - 10 , height: 100 )
        }
    }


    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell1234", for: indexPath as IndexPath) as! CollectionViewCell1234

        // Use the outlet in our custom class to get a reference to the UILabel in the cell
        cell.lbl1.text = self.items[indexPath.item]
        cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
        cell.layer.borderColor = UIColor.black.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 8

        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }



}

Passing Multiple route params in Angular2

Two Methods for Passing Multiple route params in Angular

Method-1

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2/:id1/:id2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', "id1","id2"]);
 }
}

Method-2

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', {id1: "id1 Value", id2: 
    "id2  Value"}]);
 }
}

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

I used this command and it worked fine with me:

>git push -f origin master

But notice, that may delete some files you already have on the remote repo. That came in handy with me as the scenario was different; I was pushing my local project to the remote repo which was empty but the READ.ME

How to create a custom attribute in C#

Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:

The decorated property [of class Foo]:

[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }

Fetching it:

PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
    MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
    string propertyValue = myAttribute.SomeProperty;
}

You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo, as well:

foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
    string propertyName = propertyInfo.Name;

    object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
    // Just in case you have a property without this annotation
    if (attribute.Length > 0)
    {
        MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
        string propertyValue = myAttribute.SomeProperty;
        // TODO: whatever you need with this propertyValue
    }
}

Major thanks to you, Darin!!

"git rm --cached x" vs "git reset head --? x"?

There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.

When you do something like git add file you add it to the index. And when you commit it, you add it to the tree as well.

It will probably help you to know the three more common flags in git reset:

git reset [--<mode>] [<commit>]

This form resets the current branch head to <commit> and possibly updates the index (resetting it to the tree of <commit>) and the working tree depending on <mode>, which must be one of the following:
--soft

Does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--mixed

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

Now, when you do something like git reset HEAD, what you are actually doing is git reset HEAD --mixed and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD is the exact opposite of git add.

git rm, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add was used to add a new (previously untracked) file, then git rm --cached is the exact opposite of git add (and is pretty much identical to git reset HEAD).

Git 2.25 introduced a new command for these cases, git restore, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.

Angular 2 change event - model changes

If this helps you,

<input type="checkbox"  (ngModelChange)="mychange($event)" [ngModel]="mymodel">

mychange(val)
{
   console.log(val); // updated value
}

How to comment/uncomment in HTML code

Yes, to comment structural metadata out,

Using <script>/* ... */</script> in .html

Comment out large sections of HTML (Comment Out Block)

my personal way in a .html file is opening: <script>/* and close it with */</script>

<script>/* hiding code go here */</script>

Is a workaround to the problem since is not HTML.

Considering your code in .html...

  <!-- Here starts the sidebar -->
  <div id="sidebar">
  ....
  </div>

<script>/*
  <!-- Here starts the main contents pane -->
  <div id="main-contents">
  ...
  </div>

  <!-- Here starts the footer -->
  <div id="footer">
  ...
  </div>
*/</script>

And in a case is HTML inside PHP file using comment tag <?/* or <?php /* and close it with */?> . Remember that the file must be .php extension and don't work in .html.

<?/* hiding code go here */?>

Considering your code in .php...

  <!-- Here starts the sidebar -->
  <div id="sidebar">
  ....
  </div>

<?/*
  <!-- Here starts the main contents pane -->
  <div id="main-contents">
  ...
  </div>

  <!-- Here starts the footer -->
  <div id="footer">
  ...
  </div>
*/?>

Is worth nothing that is not HTML but a common developer practice is to comment out parts of metadata so that it will not be rendered and/or executed in the browser. In HTML, commenting out multiple lines can be time-consuming. It is useful to exclude pieces of template structural metadata containing comments, CSS or code and systematically commenting out to find the source of an error. It is considered a bad practice to comment blocks out and it is recommended to use a version control system. The attribute "type" is required in HTML4 and optional in HTML5.

Error: Could not find or load main class

I know this question was tagged with linux, but on windows, you might need to separate your cp args with a ; instead of a :.

java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar;./vensim.jar SpatialModel vars

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html

Minimum rights required to run a windows service as a domain account

I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.

How do I split a string with multiple separators in JavaScript?

Hi for example if you have split and replace in String 07:05:45PM

var hour = time.replace("PM", "").split(":");

Result

[ '07', '05', '45' ]

reCAPTCHA ERROR: Invalid domain for site key

I guess the quickest way is just to disable the domain check while you're developing it enter image description here

MySQL user DB does not have password columns - Installing MySQL on OSX

Thank you for your help. Just in case if people are still having problems, try this.

For MySQL version 5.6 and under

Have you forgotten your Mac OS X 'ROOT' password  and need to reset it?  Follow these 4 simple steps:

  1.  Stop the mysqld server.  Typically this can be done by from 'System Prefrences' > MySQL > 'Stop MySQL Server'
  2.  Start the server in safe mode with privilege bypass      From a terminal:      sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3.  In a new terminal window:      sudo /usr/local/mysql/bin/mysql -u root      UPDATE mysql.user SET Password=PASSWORD('NewPassword') WHERE User='root';      FLUSH PRIVILEGES;      \q
  4.  Stop the mysqld server again and restart it in normal mode.

For MySQL version 5.7 and up

  1.  Stop the mysqld server.  Typically this can be done by from 'System Prefrences' > MySQL > 'Stop MySQL Server'
  2.  Start the server in safe mode with privilege bypass      From a terminal:      sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3.  In a new terminal window:            sudo /usr/local/mysql/bin/mysql -u root      UPDATE mysql.user SET authentication_string=PASSWORD('NewPassword') WHERE User='root';      FLUSH PRIVILEGES;      \q      
  4.  Stop the mysqld server again and restart it in normal mode.

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

How to add an element to a list?

I would do this:

data["list"].append({'b':'2'})

so simply you are adding an object to the list that is present in "data"

How can I return two values from a function in Python?

I think you what you want is a tuple. If you use return (i, card), you can get these two results by:

i, card = select_choice()

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I was working with spring boot jpa and fixed by implementing @EnableTransactionManagement

Attached file may help you.

how to add new <li> to <ul> onclick with javascript

First you have to create a li(with id and value as you required) then add it to your ul.

Javascript ::

addAnother = function() {
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    var children = ul.children.length + 1
    li.setAttribute("id", "element"+children)
    li.appendChild(document.createTextNode("Element "+children));
    ul.appendChild(li)
}

Check this example that add li element to ul.

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

No real answer to your question but:
Generally relying on the clients IP address is in my opinion not a good practice as it is not usable to identify clients in a unique fashion.

Problems on the road are that there are quite a lot scenarios where the IP does not really align to a client:

  • Proxy/Webfilter (mangle almost everything)
  • Anonymizer network (no chance here either)
  • NAT (an internal IP is not very useful for you)
  • ...

I cannot offer any statistics on how many IP addresses are on average reliable but what I can tell you that it is almost impossible to tell if a given IP address is the real clients address.

How to delete images from a private docker registry?

I've faced same problem with my registry then i tried the solution listed below from a blog page. It works.

Step 1: Listing catalogs

You can list your catalogs by calling this url:

http://YourPrivateRegistyIP:5000/v2/_catalog

Response will be in the following format:

{
  "repositories": [
    <name>,
    ...
  ]
}

Step 2: Listing tags for related catalog

You can list tags of your catalog by calling this url:

http://YourPrivateRegistyIP:5000/v2/<name>/tags/list

Response will be in the following format:

{
"name": <name>,
"tags": [
    <tag>,
    ...
]

}

Step 3: List manifest value for related tag

You can run this command in docker registry container:

curl -v --silent -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X GET http://localhost:5000/v2/<name>/manifests/<tag> 2>&1 | grep Docker-Content-Digest | awk '{print ($3)}'

Response will be in the following format:

sha256:6de813fb93debd551ea6781e90b02f1f93efab9d882a6cd06bbd96a07188b073

Run the command given below with manifest value:

curl -v --silent -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X DELETE http://127.0.0.1:5000/v2/<name>/manifests/sha256:6de813fb93debd551ea6781e90b02f1f93efab9d882a6cd06bbd96a07188b073

Step 4: Delete marked manifests

Run this command in your docker registy container:

bin/registry garbage-collect  /etc/docker/registry/config.yml  

Here is my config.yml

root@c695814325f4:/etc# cat /etc/docker/registry/config.yml
version: 0.1
log:
  fields:
  service: registry
storage:
    cache:
        blobdescriptor: inmemory
    filesystem:
        rootdirectory: /var/lib/registry
    delete:
        enabled: true
http:
    addr: :5000
    headers:
        X-Content-Type-Options: [nosniff]
health:
  storagedriver:
    enabled: true
    interval: 10s
    threshold: 3

ImportError: No module named tensorflow

Try installing tensorflow again with the whatever version you want and with option --ignore-installed like:

pip install tensorflow==1.2.0 --ignore-installed

I solved same issue using this command.

How to join (merge) data frames (inner, outer, left, right)

By using the merge function and its optional parameters:

Inner join: merge(df1, df2) will work for these examples because R automatically joins the frames by common variable names, but you would most likely want to specify merge(df1, df2, by = "CustomerId") to make sure that you were matching on only the fields you desired. You can also use the by.x and by.y parameters if the matching variables have different names in the different data frames.

Outer join: merge(x = df1, y = df2, by = "CustomerId", all = TRUE)

Left outer: merge(x = df1, y = df2, by = "CustomerId", all.x = TRUE)

Right outer: merge(x = df1, y = df2, by = "CustomerId", all.y = TRUE)

Cross join: merge(x = df1, y = df2, by = NULL)

Just as with the inner join, you would probably want to explicitly pass "CustomerId" to R as the matching variable. I think it's almost always best to explicitly state the identifiers on which you want to merge; it's safer if the input data.frames change unexpectedly and easier to read later on.

You can merge on multiple columns by giving by a vector, e.g., by = c("CustomerId", "OrderId").

If the column names to merge on are not the same, you can specify, e.g., by.x = "CustomerId_in_df1", by.y = "CustomerId_in_df2" where CustomerId_in_df1 is the name of the column in the first data frame and CustomerId_in_df2 is the name of the column in the second data frame. (These can also be vectors if you need to merge on multiple columns.)

How to search for a string in cell array in MATLAB?

did you try

indices = Find(strs, 'KU')

see link

alternatively,

indices = strfind(strs, 'KU');

should also work if I'm not mistaken.

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

Easier way to create circle div than using an image?

Here's a demo: http://jsfiddle.net/thirtydot/JJytE/1170/

CSS:

.circleBase {
    border-radius: 50%;
    behavior: url(PIE.htc); /* remove if you don't care about IE8 */
}

.type1 {
    width: 100px;
    height: 100px;
    background: yellow;
    border: 3px solid red;
}
.type2 {
    width: 50px;
    height: 50px;
    background: #ccc;
    border: 3px solid #000;
}
.type3 {
    width: 500px;
    height: 500px;
    background: aqua;
    border: 30px solid blue;
}

HTML:

<div class="circleBase type1"></div>

<div class="circleBase type2"></div><div class="circleBase type2"></div>

<div class="circleBase type3"></div>

To make this work in IE8 and older, you must download and use CSS3 PIE. My demo above won't work in IE8, but that's only because jsFiddle doesn't host PIE.htc.

My demo looks like this:

What is "X-Content-Type-Options=nosniff"?

Just to elaborate a bit on the meta-tag thing. I've heard a talk, where a statement was made, one should always insert the "no-sniff" meta tag in the html to prevent browser sniffing (just like OP did):

<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />

However, this is not a valid method for w3c compliant websites, the validator will raise an error:

Bad value text/html; charset=UTF-8; X-Content-Type-Options=nosniff for attribute content on element meta: The legacy encoding contained ;, which is not a valid character in an encoding name.

And there is no fixing this. To rightly turn off no-sniff, one has to go to the server settings and turn it off there. Because the "no-sniff" option is something from the HTTP header, not from the HTML file which is attached at the HTTP response.

To check if the no-sniff option is disabled, one can enable the developer console, networks tab and then inspect the HTTP response header:

Visualization of enabled no-sniff option

Can I change the headers of the HTTP request sent by the browser?

I don't think it's possible to do it in the way you are trying to do it.

Indication of the accepted data format is usually done through adding the extension to the resource name. So, if you have resource like

/resources/resource

and GET /resources/resource returns its HTML representation, to indicate that you want its XML representation instead, you can use following pattern:

/resources/resource.xml

You have to do the accepted content type determination magic on the server side, then.

Or use Javascript as James suggests.

Batch script to install MSI

Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like

  • Using start /wait
  • Using !ERRORLEVEL! variable instead of %ERRORLEVEL%
  • Using SetLocal EnableDelayedExpansion

Nothing works and what mostly annoys me it's the fact that it works in the command line.

Express.js Response Timeout

Before you set your routes, add the code:

app.all('*', function(req, res, next) {
    setTimeout(function() {
        next();
    }, 120000); // 120 seconds
});

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

If you want to use for <input> it will not work, for <input> or text area you need to use Javascript

<script language="javascript" type="text/javascript">
function capitaliseName()
{
    var str = document.getElementById("name").value;
    document.getElementById("name").value = str.charAt(0).toUpperCase() + str.slice(1);

}
</script>

<textarea name="NAME" id="name" onkeydown = "capitaliseName()"></textarea>

that is supposed to work well for <input> or <textarea>

"unable to locate adb" using Android Studio

if using avast go for virus chest,will find adb,restore it by clicking right button..thats all,perfectly works

Click in OK button inside an Alert (Selenium IDE)

about Selenium IDE, I am not an expert but you have to add the line "choose ok on next confirmation" before the event which trigger the alert/confirm dialog box as you can see into this screenshot:

Selenium IDE order matter

What properties can I use with event.target?

event.target returns the DOM element, so you can retrieve any property/ attribute that has a value; so, to answer your question more specifically, you will always be able to retrieve nodeName, and you can retrieve href and id, provided the element has a href and id defined; otherwise undefined will be returned.

However, inside an event handler, you can use this, which is set to the DOM element as well; much easier.

$('foo').bind('click', function () {
    // inside here, `this` will refer to the foo that was clicked
});

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

Check if MySQL table exists or not

Taken from another post

$checktable = mysql_query("SHOW TABLES LIKE '$this_table'");
$table_exists = mysql_num_rows($checktable) > 0;

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

In ---- model: Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

Change the class ----- extends Model to class ----- extends Eloquent

Using CSS for a fade-in effect on page load

You can use the onload="" HTML attribute and use JavaScript to adjust the opacity style of your element.

Leave your CSS as you proposed. Edit your HTML code to:

<body onload="document.getElementById(test).style.opacity='1'">
    <div id="test">
        <p>?This is a test</p>
    </div>
</body>

This also works to fade-in the complete page when finished loading:

HTML:

<body onload="document.body.style.opacity='1'">
</body>

CSS:

body{ 
    opacity: 0;
    transition: opacity 2s;
    -webkit-transition: opacity 2s; /* Safari */
}

Check the W3Schools website: transitions and an article for changing styles with JavaScript.

How to merge two sorted arrays into a sorted array?

var arrCombo = function(arr1, arr2){
  return arr1.concat(arr2).sort(function(x, y) {
    return x - y;
  });
};

What is uintptr_t data type

It's an unsigned integer type exactly the size of a pointer. Whenever you need to do something unusual with a pointer - like for example invert all bits (don't ask why) you cast it to uintptr_t and manipulate it as a usual integer number, then cast back.

ERROR: Sonar server 'http://localhost:9000' can not be reached

In the config file there is a colon instead of an equal sign after the sonar.web.host.

Is:

sonar.web.host:sonarqube

Should be

sonar.web.host=sonarqube

jQueryUI modal dialog does not show close button (x)

Just linking the CSS worked for me. It may have been missing from my project entirely:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

How do I iterate through table rows and cells in JavaScript?

Using a single for loop:

var table = document.getElementById('tableID');  
var count = table.rows.length;  
for(var i=0; i<count; i++) {    
    console.log(table.rows[i]);    
}

Xcode 10, Command CodeSign failed with a nonzero exit code

After trying everything, my solution was removing some PNG files, build and run (ok) and adding again the PNG images. Weird!

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Possible Duplicate Question

<@include> - The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.

  • Only one servlet is executed at run time.
  • Scriptlet variables declared in the parent page can be accessed in the included page (remember, they are the same page).
  • The included page does not need to able to be compiled as a standalone JSP. It can be a code fragment or plain text. The included page will never be compiled as a standalone. The included page can also have any extension, though .jspf has become a conventionally used extension.
  • One drawback on older containers is that changes to the include pages may not take effect until the parent page is updated. Recent versions of Tomcat will check the include pages for updates and force a recompile of the parent if they're updated.
  • A further drawback is that since the code is inlined directly into the service method of the generated servlet, the method can grow very large. If it exceeds 64 KB, your JSP compilation will likely fail.

<jsp:include> - The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.

  • Each included page is executed as a separate servlet at run time.
  • Pages can conditionally be included at run time. This is often useful for templating frameworks that build pages out of includes. The parent page can determine which page, if any, to include according to some run-time condition.
  • The values of scriptlet variables need to be explicitly passed to the include page.
  • The included page must be able to be run on its own.
  • You are less likely to run into compilation errors due to the maximum method size being exceeded in the generated servlet class.

Depending on your needs, you may either use <@include> or <jsp:include>

How do you add a timed delay to a C++ program?

to delay output in cpp for fixed time, you can use the Sleep() function by including windows.h header file syntax for Sleep() function is Sleep(time_in_ms) as

cout<<"Apple\n";
Sleep(3000);
cout<<"Mango";

OUTPUT. above code will print Apple and wait for 3 seconds before printing Mango.

Deserializing a JSON file with JavaScriptSerializer()

  1. You need to create a class that holds the user values, just like the response class User.
  2. Add a property to the Response class 'user' with the type of the new class for the user values User.

    public class Response {
    
        public string id { get; set; }
        public string text { get; set; }
        public string url { get; set; }
        public string width { get; set; }
        public string height { get; set; }
        public string size { get; set; }
        public string type { get; set; }
        public string timestamp { get; set; }
        public User user { get; set; }
    
    }
    
    public class User {
    
        public int id { get; set; }
        public string screen_name { get; set; }
    
    }
    

In general you should make sure the property types of the json and your CLR classes match up. It seems that the structure that you're trying to deserialize contains multiple number values (most likely int). I'm not sure if the JavaScriptSerializer is able to deserialize numbers into string fields automatically, but you should try to match your CLR type as close to the actual data as possible anyway.

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

This is the job for style property:

document.getElementById("remember").style.visibility = "visible";

Failed Apache2 start, no error log

in the apache virtualhost you have to define the path to the error log file. when apache2 start for the first time it will create it automatically.

for example ErrorLog "/var/www/www.localhost.com/log-apache2/error.log" in the apache virtualhost..

Bash: Strip trailing linebreak from output

One way:

wc -l < log.txt | xargs echo -n

What is the proper REST response code for a valid request but an empty data?

204 is more appropriate. Especially when you have a alert system to ensure you website is secure, 404 in this case would cause confusion because you don't know some 404 alerts is backend errors or normal requests but response empty.

Maven does not find JUnit tests to run

Many of these answers were quite useful to me in the past, but I would like to add an additional scenario that has cost me some time, as it may help others in the future:

Make sure that the test classes and methods are public.

My problem was that I was using an automatic test class/methods generation feature of my IDE (IntelliJ) and for some reason it created them as package-private. I find this to be easier to miss than one would expect.

How to 'insert if not exists' in MySQL?

Solution:

INSERT INTO `table` (`value1`, `value2`) 
SELECT 'stuff for value1', 'stuff for value2' FROM DUAL 
WHERE NOT EXISTS (SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1) 

Explanation:

The innermost query

SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1

used as the WHERE NOT EXISTS-condition detects if there already exists a row with the data to be inserted. After one row of this kind is found, the query may stop, hence the LIMIT 1 (micro-optimization, may be omitted).

The intermediate query

SELECT 'stuff for value1', 'stuff for value2' FROM DUAL

represents the values to be inserted. DUAL refers to a special one row, one column table present by default in all Oracle databases (see https://en.wikipedia.org/wiki/DUAL_table). On a MySQL-Server version 5.7.26 I got a valid query when omitting FROM DUAL, but older versions (like 5.5.60) seem to require the FROM information. By using WHERE NOT EXISTS the intermediate query returns an empty result set if the innermost query found matching data.

The outer query

INSERT INTO `table` (`value1`, `value2`) 

inserts the data, if any is returned by the intermediate query.

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

You may want to take a look at GemBox.Spreadsheet.

They have a free version with all features but limited to 150 rows per sheet and 5 sheets per workbook, if that falls within your needs.

I haven't had need to use it myself yet, but does look interesting.

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Can't append <script> element

I want to do the same thing but to append a script tag in other frame!

var url = 'library.js'; 
var script = window.parent.frames[1].document.createElement('script' ); 
script.type = 'text/javascript'; 
script.src = url;
$('head',window.parent.frames[1].document).append(script);

AngularJS: how to implement a simple file upload with multipart form?

I just wrote a simple directive (from existing one ofcourse) for a simple uploader in AngularJs.

(The exact jQuery uploader plugin is https://github.com/blueimp/jQuery-File-Upload)

A Simple Uploader using AngularJs (with CORS Implementation)

(Though the server side is for PHP, you can simple change it node also)

Why use argparse rather than optparse?

The best source for rationale for a Python addition would be its PEP: PEP 389: argparse - New Command Line Parsing Module, in particular, the section entitled, Why aren't getopt and optparse enough?

How to use gitignore command in git

If you don't have a .gitignore file. You can create a new one by

touch .gitignore

And you can exclude a folder by entering the below command in the .gitignore file

/folderName

push this file into your git repository so that when a new person clone your project he don't have to add the same again

.NET HttpClient. How to POST string value?

using System;
using System.Collections.Generic;
using System.Net.Http;

class Program
{
    static void Main(string[] args)
    {
        Task.Run(() => MainAsync());
        Console.ReadLine();
    }

    static async Task MainAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:6740");
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("", "login")
            });
            var result = await client.PostAsync("/api/Membership/exists", content);
            string resultContent = await result.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
        }
    }
}

MySQL date format DD/MM/YYYY select query?

Use:

SELECT DATE_FORMAT(NAME_COLUMN, "%d/%l/%Y") AS 'NAME'
SELECT DATE_FORMAT(NAME_COLUMN, "%d/%l/%Y %H:%i:%s") AS 'NAME'

Reference: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

How to get URI from an asset File?

Worked for me Try this code

   uri = Uri.fromFile(new File("//assets/testdemo.txt"));
   String testfilepath = uri.getPath();
    File f = new File(testfilepath);
    if (f.exists() == true) {
    Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
    } else {
   Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
 }

Regular expression for not allowing spaces in the input field

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()

Than Below string will work

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor

Recursively find all files newer than a given time

Assuming a modern release, find -newermt is powerful:

find -newermt '10 minutes ago' ## other units work too, see `Date input formats`

or, if you want to specify a time_t (seconds since epoch):

find -newermt @1568670245

For reference, -newermt is not directly listed in the man page for find. Instead, it is shown as -newerXY, where XY are placeholders for mt. Other replacements are legal, but not applicable for this solution.

From man find -newerXY:

Time specifications are interpreted as for the argument to the -d option of GNU date.

So the following are equivalent to the initial example:

find -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d '10 minutes ago')" ## long form using 'date'
find -newermt "@$(date +%s -d '10 minutes ago')" ## short form using 'date' -- notice '@'

The date -d (and find -newermt) arguments are quite flexible, but the documentation is obscure. Here's one source that seems to be on point: Date input formats

Nested attributes unpermitted parameters

From the docs

To whitelist an entire hash of parameters, the permit! method can be used

params.require(:log_entry).permit!

Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this

  def question_params

      params.require(:question).permit!

  end

Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.

Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.

Eclipse Build Path Nesting Errors

Here is a simple solution:

  1. Right click the project >> properties >> build path;
  2. In Source tab, Select all the source folders;
  3. Remove them;
  4. Right click on project, Maven >> Update the project.

How to get the day name from a selected date?

try this:

DateTime.Now.DayOfWeek

NSNotificationCenter addObserver in Swift

Pass Data using NSNotificationCenter

You can also pass data using NotificationCentre in swift 3.0 and NSNotificationCenter in swift 2.0.

Swift 2.0 Version

Pass info using userInfo which is a optional Dictionary of type [NSObject : AnyObject]?

let imageDataDict:[String: UIImage] = ["image": image]

// Post a notification
 NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

// handle notification
func showSpinningWheel(notification: NSNotification) {
  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
}

Swift 3.0 Version

The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift

let imageDataDict:[String: UIImage] = ["image": image]

// post a notification
 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
// `default` is now a property, not a method call

// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// handle notification
func showSpinningWheel(_ notification: NSNotification) {

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
}

Source pass data using NotificationCentre(swift 3.0) and NSNotificationCenter(swift 2.0)

How to add pandas data to an existing csv file?

You can specify a python write mode in the pandas to_csv function. For append it is 'a'.

In your case:

df.to_csv('my_csv.csv', mode='a', header=False)

The default mode is 'w'.

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I had this problem for our FSharp targets (FSharpTargetsPath was empty).

Many of the paths are built with reference to the VS version.

For various reasons, our build runs with system privileges, and the environment variable "VisualStudioVersion" was only set (by the VS 2013 installer) at the "user" level - which is fair enough.

Ensure that the "VisualStudioVersion" environment variable is set to "12.0" at the level (System or User) that you are running at.

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

If you are reusing an element over and over (A bootstrap modal dialog in my case), then calling ko.applyBindings(el) multiple times will cause this problem.

Instead just do it once like this:

if (!applied) {
    ko.applyBindings(el);
    applied = true;
}

Or like this:

var apply = function (viewModel, containerElement) {
    ko.applyBindings(viewModel, containerElement);
    apply = function() {}; // only allow this function to be called once.
}

PS: This might happen more often to you if you use the mapping plugin and convert your JSON data to observables.

jquery UI dialog: how to initialize without a title bar?

I think the cleanest way of doing it would be to create a new myDialog widget, consisting of the dialog widget minus the title bar code. Excising the title bar code looks straightforward.

https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.dialog.js

How to update one file in a zip archive

Try the following:

zip [zipfile] [file to update] 

An example:

$ zip test.zip test/test.txt
updating: test/test.txt (stored 0%)

Default values for Vue component props & how to check if a user did not set the prop?

This is an old question, but regarding the second part of the question - how can you check if the user set/didn't set a prop?

Inspecting this within the component, we have this.$options.propsData. If the prop is present here, the user has explicitly set it; default values aren't shown.

This is useful in cases where you can't really compare your value to its default, e.g. if the prop is a function.

How to get Printer Info in .NET?

Please notice that the article that dowski and Panos was reffering to (MSDN Win32_Printer) can be a little misleading.

I'm referring the first value of most of the arrays. some begins with 1 and some begins with 0. for example, "ExtendedPrinterStatus" first value in table is 1, therefore, your array should be something like this:

string[] arrExtendedPrinterStatus = { 
    "","Other", "Unknown", "Idle", "Printing", "Warming Up",
    "Stopped Printing", "Offline", "Paused", "Error", "Busy",
    "Not Available", "Waiting", "Processing", "Initialization",
    "Power Save", "Pending Deletion", "I/O Active", "Manual Feed"
};

and on the other hand, "ErrorState" first value in table is 0, therefore, your array should be something like this:

string[] arrErrorState = {
    "Unknown", "Other", "No Error", "Low Paper", "No Paper", "Low Toner",
    "No Toner", "Door Open", "Jammed", "Offline", "Service Requested",
    "Output Bin Full"
};

BTW, "PrinterState" is obsolete, but you can use "PrinterStatus".

Radio buttons not checked in jQuery

$("input").is(":not(':checked')"))

This is jquery 1.3, mind the ' and " signs!

CSS @media print issues with background-color;

Thought I'd add a recent and 2015 relevant aid from a recent print css experience.

Was able to print backgrounds and colors regardless of print dialog box settings.

To do this, I had to use a combination of !important & -webkit-print-color-adjust:exact !important to get background and colors to print properly.

Also, when declaring colors, I found the most stubborn areas needed a definition directly to your target. For example:

<div class="foo">
 <p class="red">Some text</p>
</div>

And your CSS:

.red {color:red !important}
.foo {color:red !important} /* <-- This won't always paint the p */

docker mounting volumes on host

This is from the Docker documentation itself, might be of help, simple and plain:

"The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.".

Insert current date in datetime format mySQL

use this

$date = date('m/d/Y h:i:s', time());

and then in MYSQL do

type=varchar

then date and time will be successfully inserted

Set mouse focus and move cursor to end of input using jQuery

like other said, clear and fill worked for me:

    var elem = $('#input_field');
    var val = elem.val();
    elem.focus().val('').val(val);

Get column index from label in a data frame

match("B", names(df))

Can work also if you have a vector of names.

How do I install opencv using pip?

if you are using Pycharm navigate settings > Project:name > Project interpreter just search the module by name(in this case OpenCV-python) and install it. worked for me

Facebook share link - can you customize the message body text?

You can't do this using sharer.php, but you can do something similar using the Dialog API. http://developers.facebook.com/docs/reference/dialogs/

http://www.facebook.com/dialog/feed?  
app_id=123050457758183&  
link=http://developers.facebook.com/docs/reference/dialogs/&
picture=http://fbrell.com/f8.jpg&  
name=Facebook%20Dialogs&  
caption=Reference%20Documentation& 
description=Dialogs%20provide%20a%20simple,%20consistent%20interface%20for%20applications%20to%20interact%20with%20users.&
message=Facebook%20Dialogs%20are%20so%20easy!&
redirect_uri=http://www.example.com/response

Facebook dialog example

The catch is you must create a dummy Facebook application just to have an app_id. Note that your Facebook application doesn't have to do ANYTHING at all. Just be sure that it is properly configured, and you should be all set.

Split list into smaller lists (split in half)

Another take on this problem in 2020 ... Here's a generalization of the problem. I interpret the 'divide a list in half' to be .. (i.e. two lists only and there shall be no spillover to a third array in case of an odd one out etc). For instance, if the array length is 19 and a division by two using // operator gives 9, and we will end up having two arrays of length 9 and one array (third) of length 1 (so in total three arrays). If we'd want a general solution to give two arrays all the time, I will assume that we are happy with resulting duo arrays that are not equal in length (one will be longer than the other). And that its assumed to be ok to have the order mixed (alternating in this case).

"""
arrayinput --> is an array of length N that you wish to split 2 times
"""
ctr = 1 # lets initialize a counter

holder_1 = []
holder_2 = []

for i in range(len(arrayinput)): 

    if ctr == 1 :
        holder_1.append(arrayinput[i])
    elif ctr == 2: 
        holder_2.append(arrayinput[i])

    ctr += 1 

    if ctr > 2 : # if it exceeds 2 then we reset 
        ctr = 1 

This concept works for any amount of list partition as you'd like (you'd have to tweak the code depending on how many list parts you want). And is rather straightforward to interpret. To speed things up , you can even write this loop in cython / C / C++ to speed things up. Then again, I've tried this code on relatively small lists ~ 10,000 rows and it finishes in a fraction of second.

Just my two cents.

Thanks!

Adding rows to tbody of a table using jQuery

With Lodash you can create a template and you can do that following way:

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-12">
                <table id="tblEntAttributes" class="table">
                    <tbody>
                        <tr>
                            <td>
                                chkboxId
                            </td>
                            <td>
                               chkboxValue
                            </td>
                            <td>
                                displayName
                            </td>
                            <td>
                               logicalName
                            </td>
                            <td>
                                dataType
                            </td>
                        </tr>
                    </tbody>
                </table>
                <button class="btn btn-primary" id="test">appendTo</button>
            </div>
        </div>
     </div>

And here goes the javascript:

        var count = 1;
        window.addEventListener('load', function () {
            var compiledRow = _.template("<tr><td><input type=\"checkbox\" id=\"<%= chkboxId %>\" value=\"<%= chkboxValue %>\"></td><td><%= displayName %></td><td><%= logicalName %></td><td><%= dataType %></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>");
            document.getElementById('test').addEventListener('click', function (e) {
                var ajaxData = { 'chkboxId': 'chkboxId-' + count, 'chkboxValue': 'chkboxValue-' + count, 'displayName': 'displayName-' + count, 'logicalName': 'logicalName-' + count, 'dataType': 'dataType-' + count };
                var tableRowData = compiledRow(ajaxData);
                $("#tblEntAttributes tbody").append(tableRowData);
                count++;
            });
        });

Here it is in jsbin

What is a regex to match ONLY an empty string?

Based on the most-approved answer, here is yet another way:

var result = !/[\d\D]/.test(string);  //[\d\D] will match any character

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

Getting error "The package appears to be corrupt" while installing apk file

After searching a lot I found a solution:

Go to Build-> Build Apk(s).

After creating apk you will see a dialog as below.

enter image description here

Click on locate and install it in your phone

Enjoy

Visual Studio: ContextSwitchDeadlock

In Visual Studio 2017 Spanish version.

"Depurar" -> "Ventanas" -> "Configuración de Excepciones"

and search "ContextSwitchDeadlock". Then, uncheck it. Or shortcut

Ctrl+D,E

Best.

Toolbar overlapping below status bar

Use android:fitsSystemWindows="true" in the root view of your layout (LinearLayout in your case). And android:fitsSystemWindows is an

internal attribute to adjust view layout based on system windows such as the status bar. If true, adjusts the padding of this view to leave space for the system windows. Will only take effect if this view is in a non-embedded activity.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol fitsSystemWindows.

Regex to match only uppercase "words" with some exceptions

Maybe you can run this regex first to see if the line is all caps:

^[A-Z \d\W]+$

That will match only if it's a line like THING P1 MUST CONNECT TO X2.

Otherwise, you should be able to pull out the individual uppercase phrases with this:

[A-Z][A-Z\d]+

That should match "P1" and "J236" in The thing P1 must connect to the J236 thing in the Foo position.

Creating stored procedure with declare and set variables

I assume you want to pass the Order ID in. So:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

Add (insert) a column between two columns in a data.frame

Add in your new column:

df$d <- list/data

Then you can reorder them.

df <- df[, c("a", "b", "d", "c")]

From milliseconds to hour, minutes, seconds and milliseconds

not really eleganter, but a bit shorter would be

function to_tuple(x):
   y = 60*60*1000
   h = x/y
   m = (x-(h*y))/(y/60)
   s = (x-(h*y)-(m*(y/60)))/1000
   mi = x-(h*y)-(m*(y/60))-(s*1000)

   return (h,m,s,mi)

href="file://" doesn't work

The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is because you specified http://file://

The http:// at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.

Note

If you link to something like

<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>

The above represents a link to a file called k:/yourfile.pdf on the k: drive on the machine on which you are viewing the URL.

You can do this, for example the below creates a link to C:\temp\test.pdf

<a href="file:///C:/Temp/test.pdf">test.pdf</a>

By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.

Most people do not have a K:/ drive.

But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).

You could try

<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>

Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is a malformed

In Python, how do you convert a `datetime` object to seconds?

I tried the standard library's calendar.timegm and it works quite well:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

Ref: https://docs.python.org/2/library/calendar.html#calendar.timegm

Edit a specific Line of a Text File in C#

You need to Open the output file for write access rather than using a new StreamReader, which always overwrites the output file.

StreamWriter stm = null;
fi = new FileInfo(@"C:\target.xml");
if (fi.Exists)
   stm = fi.OpenWrite();

Of course, you will still have to seek to the correct line in the output file, which will be hard since you can't read from it, so unless you already KNOW the byte offset to seek to, you probably really want read/write access.

FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

with this stream, you can read until you get to the point where you want to make changes, then write. Keep in mind that you are writing bytes, not lines, so to overwrite a line you will need to write the same number of characters as the line you want to change.

Batch Files - Error Handling

Other than ERRORLEVEL, batch files have no error handling. You'd want to look at a more powerful scripting language. I've been moving code to PowerShell.

The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.

Right now, it looks like any time invested in learning and using PowerShell will be time well spent.

RegEx for matching UK Postcodes

Below method will check the post code and provide complete info

const valid_postcode = postcode => {
    try {
        postcode = postcode.replace(/\s/g, "");
        const fromat = postcode
            .toUpperCase()
            .match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/);
        const finalValue = `${fromat[1]} ${fromat[2]}`;
        const regex = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$/i;
        return {
            isValid: regex.test(postcode),
            formatedPostCode: finalValue,
            error: false,
            info: 'It is a valid postcode'
        };
    } catch (error) {
        return { error: true , info: 'Invalid post code has been entered!'};
    }
};
valid_postcode('GU348RR')
result => {isValid: true, formatedPostCode: "GU34 8RR", error: false, info: "It is a valid postcode"}
valid_postcode('sdasd4746asd')
result => {error: true, info: "Invalid post code has been entered!"}
valid_postcode('787898523')
result => {error: true, info: "Invalid post code has been entered!"}

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

How do I count unique items in field in Access query?

Access-Engine does not support

SELECT count(DISTINCT....) FROM ...

You have to do it like this:

SELECT count(*) 
FROM
(SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

How to install latest version of git on CentOS 7.x/6.x

I found this nice and easy-to-follow guide on how to download the GIT source and compile it yourself (and install it). If the accepted answer does not give you the version you want, try the following instructions:

http://tecadmin.net/install-git-2-0-on-centos-rhel-fedora/

(And pasted/reformatted from above source in case it is removed later)

Step 1: Install Required Packages

Firstly we need to make sure that we have installed required packages on your system. Use following command to install required packages before compiling Git source.

# yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel
# yum install  gcc perl-ExtUtils-MakeMaker

Step 2: Uninstall old Git RPM

Now remove any prior installation of Git through RPM file or Yum package manager. If your older version is also compiled through source, then skip this step.

# yum remove git

Step 3: Download and Compile Git Source

Download git source code from kernel git or simply use following command to download Git 2.5.3.

# cd /usr/src
# wget https://www.kernel.org/pub/software/scm/git/git-2.5.3.tar.gz
# tar xzf git-2.5.3.tar.gz

After downloading and extracting Git source code, Use following command to compile source code.

# cd git-2.5.3
# make prefix=/usr/local/git all
# make prefix=/usr/local/git install
# echo 'pathmunge /usr/local/git/bin/' > /etc/profile.d/git.sh 
# chmod +x /etc/profile.d/git.sh
# source /etc/bashrc

Step 4. Check Git Version

On completion of above steps, you have successfully install Git in your system. Use the following command to check the git version

# git --version

git version 2.5.3

I also wanted to add that the "Getting Started" guide at the GIT website also includes instructions on how to download and compile it yourself:

http://git-scm.com/book/en/v2/Getting-Started-Installing-Git

c# how to add byte to byte array

As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:

var mahByteArray = new ArrayList<byte>();

If you have a byte array from elsewhere, you can use the AddRange function.

mahByteArray.AddRange(mahOldByteArray);

Then you can use Add() and Insert() to add elements.

mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.

Need it back in an array? .ToArray() has you covered!

mahOldByteArray = mahByteArray.ToArray();

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

Angular2 change detection: ngOnChanges not firing for nested object

I had to create a hack for it -

I created a Boolean Input variable and toggled it whenever array changed, which triggered change detection in the child component, hence achieving the purpose

Database, Table and Column Naming Conventions?

Here's a link that offers a few choices. I was searching for a simple spec I could follow rather than having to rely on a partially defined one.

http://justinsomnia.org/writings/naming_conventions.html

XML element with attribute and content using JAXB

Annotate type and gender properties with @XmlAttribute and the description property with @XmlValue:

package org.example.sport;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Sport {

    @XmlAttribute
    protected String type;

    @XmlAttribute
    protected String gender;

    @XmlValue;
    protected String description;

}

For More Information

finished with non zero exit value

look the compileSdkVersion at android/biuld.gradle ,and compileSdkVersion in all other packages should be the same.

Better way to check variable for null or empty string?

Use PHP's empty() function. The following things are considered to be empty

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

For more details check empty function

how to configure config.inc.php to have a loginform in phpmyadmin

First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php) will display an identification form, asking for a login and password.

To get that form, you should not use :

$cfg['Servers'][$i]['auth_type'] = 'config';

But you should use :

$cfg['Servers'][$i]['auth_type'] = 'cookie';

(At least, that's what I have on a server which prompts for login/password, using a form)


For more informations, you can take a look at the documentation :

'config' authentication ($auth_type = 'config') is the plain old way: username and password are stored in config.inc.php.

'cookie' authentication mode ($auth_type = 'cookie') as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

How can we stop a running java process through Windows cmd?

In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.

wmic Path win32_process Where "CommandLine Like '%YourJarName.jar%'" Call Terminate

Else taskkill /im java.exe will work to kill all java processes

How to setup Main class in manifest file in jar produced by NetBeans project

Adding manifest.file=manifest.mf into project.properties and creating manifest.mf file in the project directory works fine in NB 6.9 and should work also in NB 6.8.

How can I update my ADT in Eclipse?

In my case opening 'Help' >> "Install New Software" had no entries for any URLs (previous url's were not there) - so I Manually added 'em. And updated ... and Voilaaaa !! Above posts have been very helpful in resolving this issue for me.

CodeIgniter - Correct way to link to another page in a view

you can also use PHP short tag to make it shorter. here's an example

<a href="<?= site_url('controller/function'); ?>Contacts</a>

or use the built in anchor function of CI.

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

for converting dd/mm/yyyy to mm/dd/yyyy

=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))

Binary Data in JSON String. Something better than Base64

yEnc might work for you:

http://en.wikipedia.org/wiki/Yenc

"yEnc is a binary-to-text encoding scheme for transferring binary files in [text]. It reduces the overhead over previous US-ASCII-based encoding methods by using an 8-bit Extended ASCII encoding method. yEnc's overhead is often (if each byte value appears approximately with the same frequency on average) as little as 1–2%, compared to 33%–40% overhead for 6-bit encoding methods like uuencode and Base64. ... By 2003 yEnc became the de facto standard encoding system for binary files on Usenet."

However, yEnc is an 8-bit encoding, so storing it in a JSON string has the same problems as storing the original binary data — doing it the naïve way means about a 100% expansion, which is worse than base64.

Echo off but messages are displayed

"echo off" is not ignored. "echo off" means that you do not want the commands echoed, it does not say anything about the errors produced by the commands.

The lines you showed us look okay, so the problem is probably not there. So, please show us more lines. Also, please show us the exact value of INSTALL_PATH.

Does Python have a ternary conditional operator?

<expression 1> if <condition> else <expression 2>

a = 1
b = 2

1 if a > b else -1 
# Output is -1

1 if a > b else -1 if a < b else 0
# Output is -1

Is there a way to get rid of accents and convert a whole string to regular letters?

I think the best solution is converting each char to HEX and replace it with another HEX. It's because there are 2 Unicode typing:

Composite Unicode
Precomposed Unicode

For example "Ô`" written by Composite Unicode is different from "?" written by Precomposed Unicode. You can copy my sample chars and convert them to see the difference.

In Composite Unicode, "Ô`" is combined from 2 char: Ô (U+00d4) and ` (U+0300)
In Precomposed Unicode, "?" is single char (U+1ED2)

I have developed this feature for some banks to convert the info before sending it to core-bank (usually don't support Unicode) and faced this issue when the end-users use multiple Unicode typing to input the data. So I think, converting to HEX and replace it is the most reliable way.

Save a list to a .txt file

Try this, if it helps you

values = ['1', '2', '3']

with open("file.txt", "w") as output:
    output.write(str(values))

Read remote file with node.js (http.get)

I'd use request for this:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var csv = body;
        // Continue with your processing here.
    }
});

etc.

How to hide the Google Invisible reCAPTCHA badge

A slight variant of Matthew Dowell's post which avoids the short flash, but displays whenever the contact form 7 form is visible:

div.grecaptcha-badge{
    width:0 !important;
}

div.grecaptcha-badge.show{
    width:256px !important; 
}

I then added the following to the header.php in my child theme:

<script>
jQuery( window ).load(function () { 
    if( jQuery( '.wpcf7' ).length ){ 
        jQuery( '.grecaptcha-badge' ).addClass( 'show' );
    }
});
</script>

How to print (using cout) a number in binary form?

#include <iostream> 
#include <cmath>       // in order to use pow() function
using namespace std; 

string show_binary(unsigned int u, int num_of_bits);

int main() 
{ 

  cout << show_binary(128, 8) << endl;   // should print 10000000
  cout << show_binary(128, 5) << endl;   // should print 00000
  cout << show_binary(128, 10) << endl;  // should print 0010000000

  return 0; 
}

string show_binary(unsigned int u, int num_of_bits) 
{ 
  string a = "";

  int t = pow(2, num_of_bits);   // t is the max number that can be represented

  for(t; t>0; t = t/2)           // t iterates through powers of 2
      if(u >= t){                // check if u can be represented by current value of t
          u -= t;
          a += "1";               // if so, add a 1
      }
      else {
          a += "0";               // if not, add a 0
      }

  return a ;                     // returns string
}

How can I correctly format currency using jquery?

Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.

Sample Output:
$5.23
-$5.23

function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

How to initialize an array of custom objects

Given the data above, this is how I would do it:

# initialize the array
[PsObject[]]$people = @()

# populate the array with each object
$people += [PsObject]@{ Name = "Joe"; Age = 32; Info = "something about him" }
$people += [PsObject]@{ Name = "Sue"; Age = 29; Info = "something about her" }
$people += [PsObject]@{ Name = "Cat"; Age = 12; Info = "something else" }

The below code will work even if you only have 1 item after a Where-Object:

# display all people
Write-Host "People:"
foreach($person in $people) {
    Write-Host "  - Name: '$($person.Name)', Age: $($person.Age), Info: '$($person.Info)'"
}

# display with just 1 person (length will be empty if using 'PSCustomObject', so you have to wrap any results in a '@()' as described by Andrew Savinykh in his updated answer)
$youngerPeople = $people | Where-Object { $_.Age -lt 20 }
Write-Host "People younger than 20: $($youngerPeople.Length)"
foreach($youngerPerson in $youngerPeople) {
    Write-Host "  - Name: '$($youngerPerson.Name)'"
}

Result:

People:
  - Name: 'Joe', Age: 32, Info: 'something about him'
  - Name: 'Sue', Age: 29, Info: 'something about her'
  - Name: 'Cat', Age: 12, Info: 'something else'
People younger than 20: 1
  - Name: 'Cat'

How to elegantly check if a number is within a range?

In production code I would simply write

1 <= x && x <= 100

This is easy to understand and very readable.

Starting with C#9.0 we can write

x is >= 1 and <= 100   // Note that we must write x only once.
                       // "is" introduces a pattern matching expression.
                       // "and" is part of the pattern matching unlike the logical "&&".
                       // With "&&" we would have to write: x is >= 1 && x is <= 100

Here is a clever method that reduces the number of comparisons from two to one by using some math. The idea is that one of the two factors becomes negative if the number lies outside of the range and zero if the number is equal to one of the bounds:

If the bounds are inclusive:

(x - 1) * (100 - x) >= 0

or

(x - min) * (max - x) >= 0

If the bounds are exclusive:

(x - 1) * (100 - x) > 0

or

(x - min) * (max - x) > 0

What's the difference between utf8_general_ci and utf8_unicode_ci?

Some details (PL)

As we can read here (Peter Gulutzan) there is difference on sorting/comparing polish letter "L" (L with stroke - html esc: &#321;) (lower case: "l" - html esc: &#322;) - we have following assumption:

utf8_polish_ci      L greater than L and less than M
utf8_unicode_ci     L greater than L and less than M
utf8_unicode_520_ci L equal to L
utf8_general_ci     L greater than Z

In polish language letter L is after letter L and before M. No one of this coding is better or worse - it depends of your needs.

How do multiple clients connect simultaneously to one port, say 80, on a server?

Important:

I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.

First remember below two rules:

  1. Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL} not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT} - Protocol is an important part of a socket's definition.

  2. OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.

Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP} and socket2{SRC-B, 100, DEST-X,80, TCP}. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.

To answer the original question of the post:

Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.

To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.

A bit more for completeness:

Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.

Server Types - single & multiple:

When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).

Suggested Books and rest of the two volumes if you can.

A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')

Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.