Programs & Examples On #Appindicator

Application indicators appear in Ubuntu's notification area.

How to echo print statements while executing a sql script

You can use print -p -- in the script to do this example :

#!/bin/ksh
mysql -u username -ppassword -D dbname -ss -n -q |&
print -p -- "select count(*) from some_table;"
read -p get_row_count1
print -p -- "select count(*) from some_other_table;"
read -p get_row_count2
print -p exit ;
#
echo $get_row_count1
echo $get_row_count2
#
exit

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

What does += mean in Python?

Google 'python += operator' leads you to http://docs.python.org/library/operator.html

Search for += once the page loads up for a more detailed answer.

What are best practices that you use when writing Objective-C and Cocoa?

All these comments are great, but I'm really surprised nobody mentioned Google's Objective-C Style Guide that was published a while back. I think they have done a very thorough job.

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
    {
        return null;
    }

Then when you click on the button -

enter image description here

Datatable select with multiple conditions

    protected void FindCsv()
    {
        string strToFind = "2";

        importFolder = @"C:\Documents and Settings\gmendez\Desktop\";

        fileName = "CSVFile.csv";

        connectionString= @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+importFolder+";Extended Properties=Text;HDR=No;FMT=Delimited";
        conn = new OdbcConnection(connectionString);

        System.Data.Odbc.OdbcDataAdapter  da = new OdbcDataAdapter("select * from [" + fileName + "]", conn);
        DataTable dt = new DataTable();
        da.Fill(dt);

        dt.Columns[0].ColumnName = "id";

        DataRow[] dr = dt.Select("id=" + strToFind);

        Response.Write(dr[0][0].ToString() + dr[0][1].ToString() + dr[0][2].ToString() + dr[0][3].ToString() + dr[0][4].ToString() + dr[0][5].ToString());
    }

sql server Get the FULL month name from a date

Most answers are a bit more complicated than necessary, or don't provide the exact format requested.

select Format(getdate(), 'MMMM dd yyyy') --returns 'October 01 2020', note the leading zero
select Format(getdate(), 'MMMM d yyyy') --returns the desired format with out the leading zero: 'October 1 2020'

If you want a comma, as you normally would, use:

select Format(getdate(), 'MMMM d, yyyy') --returns 'October 1, 2020'

Note: even though there is only one 'd' for the day, it will become a 2 digit day when needed.

The type arguments for method cannot be inferred from the usage

For those who are wondering why this works in Java but not C#, consider what happens if some doof wrote this class:

public class Trololol : ISignatur<bool>, ISignatur<int>{
    Type ISignatur<bool>.Type => typeof(bool);
    Type ISignatur<int>.Type => typeof(int);
}

How is the compiler supposed to resolve var access = service.Get(new Trololol())? Both int and bool are valid.

The reason this implicit resolution works in Java likely has to do with Erasure and how Java will throw a fit if you try to implement an interface with two or more different type arguments. Such a class is simply not allowed in Java, but is just fine in C#.

Why do you need to invoke an anonymous function on the same line?

This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:

alert(
    {foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"

Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:

Function.prototype.foo = function () {
    return function () {
        alert("foo");
    };
};

var bar = (function () {}).foo();

bar(); // alerts foo

And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.

var x = function () {} (); // this function is executed but does nothing

function () {} (); // syntax error

One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:

var obj = new function () {
    this.foo = "bar";
};

var obj = {
    foo : "bar"
};

How can I solve ORA-00911: invalid character error?

Remove the semicolon ( ; ).

In oracle, you can use semicolon or not when u ran query directly on DB. But when u using java to ran a oracle query, u have to remove semicolon at the end.

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

Web scraping with Python

Use urllib2 in combination with the brilliant BeautifulSoup library:

import urllib2
from BeautifulSoup import BeautifulSoup
# or if you're using BeautifulSoup4:
# from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://example.com').read())

for row in soup('table', {'class': 'spad'})[0].tbody('tr'):
    tds = row('td')
    print tds[0].string, tds[1].string
    # will print date and sunrise

How do I create a dynamic key to be added to a JavaScript object variable

Associative Arrays in JavaScript don't really work the same as they do in other languages. for each statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push method:

jsArr = []; 

for (var i = 1; i <= 10; i++) { 
    jsArr.push('example ' + 1); 
} 

Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].

How do I use this JavaScript variable in HTML?

The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.

The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.

There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).

Examples for both options:

_x000D_
_x000D_
<script>_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
</script>_x000D_
<body>_x000D_
  <p id="a"></p>_x000D_
  <p id="b"></p>_x000D_
  <script>_x000D_
    document.getElementById('a').innerHTML = name;_x000D_
document.querySelector('#b').innerHTML = name.length;</script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to grep, excluding some patterns?

-v is the "inverted match" flag, so piping is a very good way:

grep "loom" ~/projects/**/trunk/src/**/*.@(h|cpp)| grep -v "gloom"

How to tell if a string contains a certain character in JavaScript?

With ES6 MDN docs .includes()

"FooBar".includes("oo"); // true

"FooBar".includes("foo"); // false

"FooBar".includes("oo", 2); // false

E: Not suported by IE - instead you can use the Tilde opperator ~ (Bitwise NOT) with .indexOf()

~"FooBar".indexOf("oo"); // -2 -> true

~"FooBar".indexOf("foo"); // 0 -> false

~"FooBar".indexOf("oo", 2); // 0 -> false

Used with a number, the Tilde operator effective does ~N => -(N+1). Use it with double negation !! (Logical NOT) to convert the numbers in bools:

!!~"FooBar".indexOf("oo"); // true

!!~"FooBar".indexOf("foo"); // false

!!~"FooBar".indexOf("oo", 2); // false

 

How to clone a Date object?

This is the cleanest approach

_x000D_
_x000D_
let dat = new Date() _x000D_
let copyOf = new Date(dat.valueOf())_x000D_
_x000D_
console.log(dat);_x000D_
console.log(copyOf);
_x000D_
_x000D_
_x000D_

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Open file /etc/mysql/my.cnf: change below parameter from

`bind-address = 127.0.0.1

to

bind-address = 0.0.0.0 #this allows all systems to connect

Run below command in mysql for specific IP Address->

grant all privileges on dbname.* to dbusername@'192.168.0.3' IDENTIFIED BY 'dbpassword';                      

If you want to give access to all IP Address, run below command:

grant all privileges on dbname.* to dbusername@'%' IDENTIFIED BY 'dbpassword'; 

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

How can I add a variable to console.log?

You can also use printf style of formatting arguments. It is available in at least Chrome, Firefox/Firebug and node.js.

var name = prompt("what is your name?");

console.log("story %s story", name);

It also supports %d for formatting numbers

Different font size of strings in the same TextView

Use a Spannable String

 String s= "Hello Everyone";
 SpannableString ss1=  new SpannableString(s);
 ss1.setSpan(new RelativeSizeSpan(2f), 0,5, 0); // set size
 ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);// set color
 TextView tv= (TextView) findViewById(R.id.textview);
 tv.setText(ss1); 

Snap shot

enter image description here

You can split string using space and add span to the string you require.

 String s= "Hello Everyone";  
 String[] each = s.split(" ");

Now apply span to the string and add the same to textview.

How can I pass parameters to a partial view in mvc 4

Here is an extension method that will convert an object to a ViewDataDictionary.

public static ViewDataDictionary ToViewDataDictionary(this object values)
{
    var dictionary = new ViewDataDictionary();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(values))
    {
        dictionary.Add(property.Name, property.GetValue(values));
    }
    return dictionary;
}

You can then use it in your view like so:

@Html.Partial("_MyPartial", new
{
    Property1 = "Value1",
    Property2 = "Value2"
}.ToViewDataDictionary())

Which is much nicer than the new ViewDataDictionary { { "Property1", "Value1" } , { "Property2", "Value2" }} syntax.

Then in your partial view, you can use ViewBag to access the properties from a dynamic object rather than indexed properties, e.g.

<p>@ViewBag.Property1</p>
<p>@ViewBag.Property2</p>

Disable browser's back button

The problem with Yossi Shasho's Code is that the page is scrolling to the top every 50 ms. So I have modified that code. Now its working fine on all modern browsers, IE8 and above

var storedHash = window.location.hash;
function changeHashOnLoad() {
    window.location.href += "#";
    setTimeout("changeHashAgain()", "50");
}

function changeHashAgain() {
    window.location.href += "1";
}

function restoreHash() {
    if (window.location.hash != storedHash) {
        window.location.hash = storedHash;
    }
}

if (window.addEventListener) {
    window.addEventListener("hashchange", function () {
        restoreHash();
    }, false);
}
else if (window.attachEvent) {
    window.attachEvent("onhashchange", function () {
        restoreHash();
    });
}
$(window).load(function () { changeHashOnLoad(); });

vertical alignment of text element in SVG

According to SVG spec, alignment-baseline only applies to <tspan>, <textPath>, <tref> and <altGlyph>. My understanding is that it is used to offset those from the <text> object above them. I think what you are looking for is dominant-baseline.

Possible values of dominant-baseline are:

auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge | inherit

Check the W3C recommendation for the dominant-baseline property for more information about each possible value.

How do I find the width & height of a terminal window?

Inspired by @pixelbeat's answer, here's a horizontal bar brought to existence by tput, slight misuse of printf padding/filling and tr

printf "%0$(tput cols)d" 0|tr '0' '='

How to determine the longest increasing subsequence using dynamic programming?

This can be solved in O(n^2) using dynamic programming.

Process the input elements in order and maintain a list of tuples for each element. Each tuple (A,B), for the element i will denotes, A = length of longest increasing sub-sequence ending at i and B = index of predecessor of list[i] in the longest increasing sub-sequence ending at list[i].

Start from element 1, the list of tuple for element 1 will be [(1,0)] for element i, scan the list 0..i and find element list[k] such that list[k] < list[i], the value of A for element i, Ai will be Ak + 1 and Bi will be k. If there are multiple such elements, add them to the list of tuples for element i.

In the end, find all the elements with max value of A (length of LIS ending at element) and backtrack using the tuples to get the list.

I have shared the code for same at http://www.edufyme.com/code/?id=66f041e16a60928b05a7e228a89c3799

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

I find this one pretty useful:

public static class PaulaBean
{
    private static String paula = "Brillant";
    public static String GetPaula<T>(this T obj) {
        return paula;
    }
}

You may use it on CodePlex.

Convert Swift string to array

An easy way to do this is to map the variable and return each Character as a String:

let someText = "hello"

let array = someText.map({ String($0) }) // [String]

The output should be ["h", "e", "l", "l", "o"].

pip install from git repo branch

Just to add an extra, if you want to install it in your pip file it can be added like this:

-e git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6#egg=django-oscar-paypal

It will be saved as an egg though.

Remove a folder from git tracking

From the git documentation:

Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your .gitignore file and accidentally staged it, like a large log file or a bunch of .a compiled files. To do this, use the --cached option:

$ git rm --cached readme.txt

So maybe don't include the "-r"?

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

Array functions in jQuery

There's a plugin for jQuery called 'rich array' discussed in Rich Array jQuery plugin .

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

You are doing all well. Just you have to check different SMTP ports like 465 and others that works on your system. Another thing to keep in mind to allow access to the less secure apps by google account otherwise it throws the same error.
I have gone through it for a whole day and the only thing I am doing wrong is the port no., I just changed the port no. and it works.

Unsupported method: BaseConfig.getApplicationIdSuffix()

I also faced the same issue and got a solution very similar:

  1. Changing the classpath to classpath 'com.android.tools.build:gradle:2.3.2'

    Image after adding the classpath

  2. A new message indicating to Update Build Tool version, so just click that message to update. Update

SQLAlchemy default DateTime

The default keyword parameter should be given to the Column object.

Example:

Column(u'timestamp', TIMESTAMP(timezone=True), primary_key=False, nullable=False, default=time_now),

The default value can be a callable, which here I defined like the following.

from pytz import timezone
from datetime import datetime

UTC = timezone('UTC')

def time_now():
    return datetime.now(UTC)

Sleep Command in T-SQL?

Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.SqlClient;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = "localhost";
      builder.IntegratedSecurity = true;
      builder.InitialCatalog = "master";

      var connectionString = builder.ConnectionString;

      using (var connection = new SqlConnection(connectionString))
      {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
          command.CommandText = "WAITFOR DELAY '00:00:02'";
          command.CommandTimeout = 1;

          command.ExecuteNonQuery();
        }
      }
    }
  }
}

AngularJS - Animate ng-view transitions

Angularjs 1.1.4 has now introduced the ng-animate directive to help animating different elements, in particular ng-view.

You can also watch the video about this new featue

UPDATE as of angularjs 1.2, the way animations work has changed drastically, most of it is now controlled with CSS, without having to setup javascript callbacks, etc.. You can check the updated tutorial on Year Of Moo. @dfsq pointed out in the comments a nice set of examples.

How do I resolve a HTTP 414 "Request URI too long" error?

An excerpt from the RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1:

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  • Annotation of existing resources;
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])

Use a LIKE statement on SQL Server XML Datatype

Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.

SELECT * 
FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'

I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.

EDIT: As Cliff mentions it, you could use:

...nvarchar if there's characters that don't convert to varchar

Reverse each individual word of "Hello World" string with Java

public String reverse(String arg) {
    char[] s = arg.toCharArray();
    StringBuilder sb = new StringBuilder();
    boolean reverse = false;
    boolean isChar = false;
    int insertPos = 0;

    for (int i = 0; i < s.length; i++) {
        isChar = Character.isAlphabetic(s[i]);
        if (!reverse && isChar) {
            sb.append(s[i]);
            insertPos = i;
            reverse = true;
        } else if (reverse && isChar) {
            sb.insert(insertPos, s[i]);
        } else if (!reverse && !isChar) {
            sb.append(s[i]);
        } else if (reverse && !isChar) {
            reverse = false;
            sb.append(s[i]);
        }
    }

    return sb.toString();
}

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

How to use Redirect in the new react-router-dom of Reactjs

I found that place to put the redirect complent of react-router is in the method render, but if you want to redirect after some validation, by example, the best way to redirect is using the old reliable, window.location.href, i.e.:

evalSuccessResponse(data){
   if(data.code===200){
    window.location.href = urlOneSignHome;
   }else{
     //TODO Something
   }    
}

When you are programming React Native never will need to go outside of the app, and the mechanism to open another app is completely different.

SQL not a single-group group function

Maybe you find this simpler

select * from (
    select ssn, sum(time) from downloads
    group by ssn
    order by sum(time) desc
) where rownum <= 10 --top 10 downloaders

Regards
K

Is "else if" faster than "switch() case"?

Switch is generally faster than a long list of ifs because the compiler can generate a jump table. The longer the list, the better a switch statement is over a series of if statements.

Git Cherry-Pick and Conflicts

Also, to complete what @claudio said, when cherry-picking you can also use a merging strategy.

So you could something like this git cherry-pick --strategy=recursive -X theirs commit or git cherry-pick --strategy=recursive -X ours commit

Encoding URL query parameters in Java

if you have only space problem in url. I have used below code and it work fine

String url;
URL myUrl = new URL(url.replace(" ","%20"));

example : url is

www.xyz.com?para=hello sir

then output of muUrl is

www.xyz.com?para=hello%20sir

Set Google Maps Container DIV width and height 100%

This Work for me.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css"> 

#cont{
    position: relative;
    width: 300px;
    height: 300px;
}
#map_canvas{
    overflow: hidden;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
</style> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=APIKEY"></script>
<script type="text/javascript">
function initialize() {
    console.log("Initializing...");
  var latlng = new google.maps.LatLng(LAT, LNG);
    var myOptions = {
      zoom: 10,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
}
</script>
</head>

<body onload="initialize()">
<div id="cont">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</div>
</body>
</html>

How to pass multiple arguments in processStartInfo?

Remember to include System.Diagnostics

ProcessStartInfo startInfo = new ProcessStartInfo("myfile.exe");        // exe file
startInfo.WorkingDirectory = @"C:\..\MyFile\bin\Debug\netcoreapp3.1\"; // exe folder

//here you add your arguments
startInfo.ArgumentList.Add("arg0");       // First argument          
startInfo.ArgumentList.Add("arg2");       // second argument
startInfo.ArgumentList.Add("arg3");       // third argument
Process.Start(startInfo);                 

C# using streams

To expand a little on other answers here, and help explain a lot of the example code you'll see dotted about, most of the time you don't read and write to a stream directly. Streams are a low-level means to transfer data.

You'll notice that the functions for reading and writing are all byte orientated, e.g. WriteByte(). There are no functions for dealing with integers, strings etc. This makes the stream very general-purpose, but less simple to work with if, say, you just want to transfer text.

However, .NET provides classes that convert between native types and the low-level stream interface, and transfers the data to or from the stream for you. Some notable such classes are:

StreamWriter // Badly named. Should be TextWriter.
StreamReader // Badly named. Should be TextReader.
BinaryWriter
BinaryReader

To use these, first you acquire your stream, then you create one of the above classes and associate it with the stream. E.g.

MemoryStream memoryStream = new MemoryStream();
StreamWriter myStreamWriter = new StreamWriter(memoryStream);

StreamReader and StreamWriter convert between native types and their string representations then transfer the strings to and from the stream as bytes. So

myStreamWriter.Write(123);

will write "123" (three characters '1', '2' then '3') to the stream. If you're dealing with text files (e.g. html), StreamReader and StreamWriter are the classes you would use.

Whereas

myBinaryWriter.Write(123);

will write four bytes representing the 32-bit integer value 123 (0x7B, 0x00, 0x00, 0x00). If you're dealing with binary files or network protocols BinaryReader and BinaryWriter are what you might use. (If you're exchanging data with networks or other systems, you need to be mindful of endianness, but that's another post.)

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Add the annotation

@JsonManagedReference

For example:

@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "autorizacoes_usuario", joinColumns = { @JoinColumn(name = "fk_usuario") }, inverseJoinColumns = { @JoinColumn(name = "fk_autorizacoes") })
@JsonManagedReference
public List<AutorizacoesUsuario> getAutorizacoes() {
    return this.autorizacoes;
}

cd into directory without having permission

I know this post is old, but what i had to do in the case of the above answers on Linux machine was:

sudo chmod +x directory

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

How to ORDER BY a SUM() in MySQL?

You could try this:

SELECT * 
FROM table 
ORDER BY (c_counts+f_counts) 
LIMIT 20

Changing the child element's CSS when the parent is hovered

Use toggleClass().

$('.parent').hover(function(){
$(this).find('.child').toggleClass('color')
});

where color is the class. You can style the class as you like to achieve the behavior you want. The example demonstrates how class is added and removed upon mouse in and out.

Check Working example here.

ANTLR: Is there a simple example?

For Antlr 4 the java code generation process is below:-

java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g

Update your jar name in classpath accordingly.

How do getters and setters work?

In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':

class Dummy
{
    private String name;

    public Dummy() {}

    public Dummy(String name) {
        this.name = name;
    }

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

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

The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

Generating random numbers with Swift

After some investigation I wrote this:

import Foundation

struct Math {
   private static var seeded = false

   static func randomFractional() -> CGFloat {

      if !Math.seeded {
         let time = Int(NSDate().timeIntervalSinceReferenceDate)
         srand48(time)
         Math.seeded = true
      }

      return CGFloat(drand48())
   }
}

Now you can just do Math.randomFraction() to get random numbers [0..1[ without having to remember seeding first. Hope this helps someone :o)

Get value when selected ng-option changes

I had the same issue and found a unique solution. This is not best practice, but it may prove simple/helpful for someone. Just use jquery on the id or class or your select tag and you then have access to both the text and the value in the change function. In my case I'm passing in option values via sails/ejs:

    <select id="projectSelector" class="form-control" ng-model="ticket.project.id" ng-change="projectChange(ticket)">
      <% _.each(projects, function(project) { %>
        <option value="<%= project.id %>"><%= project.title %></option>
        <% }) %>
    </select>

Then in my Angular controller my ng-change function looks like this:

    $scope.projectChange = function($scope) {
         $scope.project.title=$("#projectSelector option:selected").text();
     };

Java math function to convert positive int to negative and negative to positive?

The easiest thing to do is 0- the value

for instance if int i = 5;

0-i would give you -5

and if i was -6;

0- i would give you 6

Using onBackPressed() in Android Fragments

You can try to override onCreateAnimation, parameter and catch enter==false. This will fire before every back press.

@Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {            
        if(!enter){
            //leaving fragment
            Log.d(TAG,"leaving fragment");
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

How to create text file and insert data to that file on Android

Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the code :

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.

Environment.getExternalStorageState()

Address already in use: JVM_Bind

This problem mostly occurs because there could be another istance of the code running, from some previous tests you did most probably. Find out and close any other instance or if it is ok, try restarting the server.

In Git, how do I figure out what my current revision is?

What do you mean by "version number"? It is quite common to tag a commit with a version number and then use

$ git describe --tags

to identify the current HEAD w.r.t. any tags. If you mean you want to know the hash of the current HEAD, you probably want:

$ git rev-parse HEAD

or for the short revision hash:

$ git rev-parse --short HEAD

It is often sufficient to do:

$ cat .git/refs/heads/${branch-master}

but this is not reliable as the ref may be packed.

How do I check if a list is empty?

Here are a few ways you can check if a list is empty:

a = [] #the list

1) The pretty simple pythonic way:

if not a:
    print("a is empty")

In Python, empty containers such as lists,tuples,sets,dicts,variables etc are seen as False. One could simply treat the list as a predicate (returning a Boolean value). And a True value would indicate that it's non-empty.

2) A much explicit way: using the len() to find the length and check if it equals to 0:

if len(a) == 0:
    print("a is empty")

3) Or comparing it to an anonymous empty list:

if a == []:
    print("a is empty")

4) Another yet silly way to do is using exception and iter():

try:
    next(iter(a))
    # list has elements
except StopIteration:
    print("Error: a is empty")

How to create an 2D ArrayList in java?

This can be achieve by creating object of List data structure, as follows

List list = new ArrayList();

For more information refer this link

How to create a Multidimensional ArrayList in Java?

Using $window or $location to Redirect in AngularJS

You have to put:

<html ng-app="urlApp" ng-controller="urlCtrl">

This way the angular function can access into "window" object

"Cannot update paths and switch to branch at the same time"

'origin/master' which can not be resolved as commit

Strange: you need to check your remotes:

git remote -v

And make sure origin is fetched:

git fetch origin

Then:

git branch -avv

(to see if you do have fetched an origin/master branch)

Finally, use git switch instead of the confusing git checkout, with Git 2.23+ (August 2019).

git switch -c test --track origin/master

How do you log content of a JSON object in Node.js?

To have an output more similar to the raw console.log(obj) I usually do use console.log('Status: ' + util.inspect(obj)) (JSON is slightly different).

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

Single Line Nested For Loops

Below code for best examples for nested loops, while using two for loops please remember the output of the first loop is input for the second loop. Loop termination also important while using the nested loops

for x in range(1, 10, 1):
     for y in range(1,x):
             print y,
        print
OutPut :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

DataSet panel (Report Data) in SSRS designer is gone

For future people CTRL+ALT+D or just view > report data in ancient ssrs 2008 VS BI. In newer 2017 SSRS, it's still the same. Funny how they change a bunch of things around, yet kept this the same.

Convert byte slice to io.Reader

r := strings(byteData)

This also works to turn []byte into io.Reader

Read data from SqlDataReader

For a single result:

if (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

For multiple results:

while (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

How to print a specific row of a pandas DataFrame?

If you want to display at row=159220

row=159220

#To display in a table format
display(res.loc[row:row])
display(res.iloc[row:row+1])

#To display in print format
display(res.loc[row])
display(res.iloc[row])

Using cURL with a username and password?

You can use command like,

curl -u user-name -p http://www.example.com/path-to-file/file-name.ext > new-file-name.ext

Then HTTP password will be triggered.

Reference: http://www.asempt.com/article/how-use-curl-http-password-protected-site

Why doesn't Git ignore my specified file?

I run into this, it's an old question, but I want that file to be tracked but to not track it on certain working copies, to do that you can run

git update-index --assume-unchanged sites/default/settings.php

Sticky Header after scrolling down

I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.

    $('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
    if (e.currentTarget.scrollTop >= 130) {
        $('.results-label').addClass('fixedSimilarLabel');
    }
    else {      
        $('.results-label').removeClass('fixedSimilarLabel');
    }
});

http://codepen.io/franklynroth/pen/pjEzeK

Array.sort() doesn't sort numbers correctly

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

Each for object?

for(var key in object) {
   console.log(object[key]);
}

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

This issue can even occur when you try to run your project from controller page. Run your project from the jsp page. Go to your jsp page; right-click->Run As->Run on Server. I faced the same issue.I was running my project from the controller page. Run your project from jsp page.

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

I had the same issue and in my case I was setting the date to new DateTime() instead of DateTime.Now

Vertically align text next to an image?

Write these span properties

span{
    display:inline-block;
    vertical-align:middle;
}

Use display:inline-block; When you use vertical-align property.Those are assosiated properties

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

No, the errors occurs only after the Intelephense extension is automatically updated.

To solve the problem, you can downgrade it to the previous version by click "Install another version" in the Intelephense extension. There are no errors on version 1.2.3.

Turning off auto indent when pasting text into vim

Another answer I did not see until now:

:se paste noai

If statement in aspx page

C#

  if (condition)
    statement;
  else
    statement;

vb.net

  If [Condition] Then
    Statement
  Else
    Statement
  End If

If else examples with source code... If..else in Asp.Net

Patter

How do I remove a substring from the end of a string in Python?

A broader solution, adding the possibility to replace the suffix (you can remove by replacing with the empty string) and to set the maximum number of replacements:

def replacesuffix(s,old,new='',limit=1):
    """
    String suffix replace; if the string ends with the suffix given by parameter `old`, such suffix is replaced with the string given by parameter `new`. The number of replacements is limited by parameter `limit`, unless `limit` is negative (meaning no limit).

    :param s: the input string
    :param old: the suffix to be replaced
    :param new: the replacement string. Default value the empty string (suffix is removed without replacement).
    :param limit: the maximum number of replacements allowed. Default value 1.
    :returns: the input string with a certain number (depending on parameter `limit`) of the rightmost occurrences of string given by parameter `old` replaced by string given by parameter `new`
    """
    if s[len(s)-len(old):] == old and limit != 0:
        return replacesuffix(s[:len(s)-len(old)],old,new,limit-1) + new
    else:
        return s

In your case, given the default arguments, the desired result is obtained with:

replacesuffix('abcdc.com','.com')
>>> 'abcdc'

Some more general examples:

replacesuffix('whatever-qweqweqwe','qwe','N',2)
>>> 'whatever-qweNN'

replacesuffix('whatever-qweqweqwe','qwe','N',-1)
>>> 'whatever-NNN'

replacesuffix('12.53000','0',' ',-1)
>>> '12.53   '

Printing prime numbers from 1 through 100

Using Sieve of Eratosthenes logic, I am able to achieve the same results with much faster speed.

My code demo VS accepted answer.

Comparing the count, my code takes significantly lesser iteration to finish the job. Checkout the results for different N values in the end.

Why this code performs better than already accepted ones:

- the even numbers are not checked even once throughout the process.

- both inner and outer loops are checking only within possible limits. No extraneous checks.

Code:

int N = 1000; //Print primes number from 1 to N
vector<bool> primes(N, true);
for(int i = 3; i*i < N; i += 2){    //Jump of 2
    for(int j = 3; j*i < N; j+=2){  //Again, jump of 2
        primes[j*i] = false;
    }
}
if(N >= 2) cout << "2 ";
for(int i = 3; i < N; i+=2){        //Again, jump of 2
    if(primes[i] == true) cout << i << " "; 
}

For N = 1000, my code takes 1166 iterations, accepted answer takes 5287 (4.5 times slower)

For N = 10000, my code takes 14637 iterations, accepted answer takes 117526 (8 times slower)

For N = 100000, my code takes 175491 iterations, accepted answer takes 2745693 (15.6 times slower)

Merge PDF files with PHP

myokyawhtun's solution worked best for me (using PHP 5.4)

You will still get an error though - I resolved using the following:

Line 269 of fpdf_tpl.php - changed the function parameters to:

function Image($file, $x=null, $y=null, $w=0, $h=0, $type='', $link='',$align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0) { 

I also made this same change on line 898 of fpdf.php

how to make a jquery "$.post" request synchronous

From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function(node,targetNode,type,to) {
    jQuery.ajax({
         url:    url,
         success: function(result) {
                      if(result.isOk == false)
                          alert(result.message);
                  },
         async:   false
    });          
}

this is because $.ajax is the only request type that you can set the asynchronousity for

Internal vs. Private Access Modifiers

Internal will allow you to reference, say, a Data Access static class (for thread safety) between multiple business logic classes, while not subscribing them to inherit that class/trip over each other in connection pools, and to ultimately avoid allowing a DAL class to promote access at the public level. This has countless backings in design and best practices.

Entity Framework makes good use of this type of access

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

How do I get a UTC Timestamp in JavaScript?

The easiest way of getting UTC time in a conventional format is as follows:

new Date().toISOString()
"2016-06-03T23:15:33.008Z"

Disable developer mode extensions pop up in Chrome

(In reply to Antony Hatchkins)

This is the current, literally official way to set Chrome policies: https://support.google.com/chrome/a/answer/187202?hl=en

The Windows and Linux templates, as well as common policy documentation for all operating systems, can be found here: https://dl.google.com/dl/edgedl/chrome/policy/policy_templates.zip (Zip file of Google Chrome templates and documentation)

Instructions for Windows (with my additions):

Open the ADM or ADMX template you downloaded:

  • Extract "chrome.adm" in the language of your choice from the "policy_templates.zip" downloaded earlier (e.g. "policy_templates.zip\windows\adm\en-US\chrome.adm").
  • Navigate to Start > Run: gpedit.msc.
  • Navigate to Local Computer Policy > Computer / User Configuration > Administrative Templates.
  • Right-click Administrative Templates, and select Add/Remove Templates.
  • Add the "chrome.adm" template via the dialog.
  • Once complete, Classic Administrative Templates (ADM) / Google / Google Chrome folder will appear under Administrative Templates.
  • No matter whether you add the template under Computer Configuration or User Configuration, the settings will appear in both places, so you can configure Chrome at a machine or a user level.

Once you're done with this, continue from step 5 of Antony Hatchkins' answer. After you have added the extension ID(s), you can check that the policy is working in Chrome by opening chrome://policy (search for ExtensionInstallWhitelist).

CSS div element - how to show horizontal scroll bars only?

I also had to add white-space: nowrap; to the style, otherwise elements would wrap down into the area that we're removing the ability to scroll to.

How to redirect single url in nginx?

If you need to duplicate more than a few redirects, you might consider using a map:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

Remove large .pack file created by git

this is more of a handy solution than a coding one. zip the file. Open the zip in file view format (different from unzipping). Delete the .pack file. Unzip and replace the folder. Works like a charm!

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

There is another tricky way. The main idea is to double the section number, and first one only shows the headerView while the second one shows the real cells.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return sectionCount * 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section%2 == 0) {
        return 0;
    }
    return _rowCount;
}

What need to do then is to implement the headerInSection delegates:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section%2 == 0) {
        //return headerview;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section%2 == 0) {
        //return headerheight;
    }
    return 0;
}

This approach also has little impact on your datasources:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    int real_section = (int)indexPath.section / 2;
    //your code
}

Comparing with other approaches, this way is safe while not changing the frame or contentInsets of the tableview. Hope this may help.

Return values from the row above to the current row

Easier way for me is to switch to R1C1 notation and just use R[-1]C1 and switch back when done.

Curl Command to Repeat URL Request

If you want to add an interval before executing the cron the next time you can add a sleep

for i in {1..100}; do echo $i && curl "http://URL" >> /tmp/output.log && sleep 120; done

Mathematical functions in Swift

For the Swift way of doing things, you can try and make use of the tools available in the Swift Standard Library. These should work on any platform that is able to run Swift.

Instead of floor(), round() and the rest of the rounding routines you can use rounded(_:):

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

These are currently available on Float and Double and it should be easy enough to convert to a CGFloat for example.

Instead of sqrt() there's the squareRoot() method on the FloatingPoint protocol. Again, both Float and Double conform to the FloatingPoint protocol:

let x = 4.0
let y = x.squareRoot()

For the trigonometric functions, the standard library can't help, so you're best off importing Darwin on the Apple platforms or Glibc on Linux. Fingers-crossed they'll be a neater way in the future.

#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

let x = 1.571
print(sin(x))
// Prints "~1.0"

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I had the same problem in docker and these steps worked for me:

apt update

then:

apt install libsm6 libxext6 libxrender-dev

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

In my case the problem was caused by a syntax error in the arguments being passed. I had a space between the key & value when using '-D'

i.e.

-DMyArg= MyValue

instead of

-DMyArg=MyValue

Angular2 @Input to a property with get/set

@Paul Cavacas, I had the same issue and I solved by setting the Input() decorator above the getter.

  @Input('allowDays')
  get in(): any {
    return this._allowDays;
  }

  //@Input('allowDays')
  // not working
  set in(val) {
    console.log('allowDays = '+val);
    this._allowDays = val;
  }

See this plunker: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview

How do I change the owner of a SQL Server database?

to change the object owner try the following

EXEC sp_changedbowner 'sa'

that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that

How do you run `apt-get` in a dockerfile behind a proxy?

A slight alternative to the answer provided by @Reza Farshi (which works better in my case) is to write the proxy settings out to /etc/apt/apt.conf using echo via the Dockerfile e.g.:

FROM ubuntu:16.04

RUN echo "Acquire::http::proxy \"$HTTP_PROXY\";\nAcquire::https::proxy \"$HTTPS_PROXY\";" > /etc/apt/apt.conf

# Test that we can now retrieve packages via 'apt-get'
RUN apt-get update

The advantage of this approach is that the proxy addresses can be passed in dynamically at image build time, rather than having to copy the settings file over from the host.

e.g.

docker build --build-arg HTTP_PROXY=http://<host>:<port> --build-arg HTTPS_PROXY=http://<host>:<port> .

as per docker build docs.

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

I got it to work by Enabling 32 bit applications in the Application Pool advanced settings. Right click on the application pool and choose advanced settings - enable 32 bit applications. This may help someone out there.

How can I print variable and string on same line in Python?

Just use , (comma) in between.

See this code for better understanding:

# Weight converter pounds to kg

weight_lbs = input("Enter your weight in pounds: ")

weight_kg = 0.45 * int(weight_lbs)

print("You are ", weight_kg, " kg")

Generate preview image from Video file?

I recommend php-ffmpeg library.

Extracting image

You can extract a frame at any timecode using the FFMpeg\Media\Video::frame method.

This code returns a FFMpeg\Media\Frame instance corresponding to the second 42. You can pass any FFMpeg\Coordinate\TimeCode as argument, see dedicated documentation below for more information.

$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');

If you want to extract multiple images from the video, you can use the following filter:

$video
    ->filters()
    ->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
    ->synchronize();

$video
    ->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');

By default, this will save the frames as jpg images.

You are able to override this using setFrameFileType to save the frames in another format:

$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);

$video->addFilter($filter);

user authentication libraries for node.js?

Quick simple example using mongo, for an API that provides user auth for ie Angular client

in app.js

var express = require('express');
var MongoStore = require('connect-mongo')(express);

// ...

app.use(express.cookieParser());
// obviously change db settings to suit
app.use(express.session({
    secret: 'blah1234',
    store: new MongoStore({
        db: 'dbname',
        host: 'localhost',
        port: 27017
    })
}));

app.use(app.router);

for your route something like this:

// (mongo connection stuff)

exports.login = function(req, res) {

    var email = req.body.email;
    // use bcrypt in production for password hashing
    var password = req.body.password;

    db.collection('users', function(err, collection) {
        collection.findOne({'email': email, 'password': password}, function(err, user) {
            if (err) {
                res.send(500);
            } else {
                if(user !== null) {
                    req.session.user = user;
                    res.send(200);
                } else {
                    res.send(401);
                }
            }
        });
    });
};

Then in your routes that require auth you can just check for the user session:

if (!req.session.user) {
    res.send(403);
}

How do I access the HTTP request header fields via JavaScript?

Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.

It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.

What's the advantage of a Java enum versus a class with public static final fields?

There are many advantages of enums that are posted here, and I am creating such enums right now as asked in the question. But I have an enum with 5-6 fields.

enum Planet{
EARTH(1000000, 312312321,31232131, "some text", "", 12),
....
other planets
....

In these kinds of cases, when you have multiple fields in enums, it is much difficult to understand which value belongs to which field as you need to see constructor and eye-ball.

Class with static final constants and using Builder pattern to create such objects makes it more readable. But, you would lose all other advantages of using an enum, if you need them. One disadvantage of such classes is, you need to add the Planet objects manually to the list/set of Planets.

I still prefer enum over such class, as values() comes in handy and you never know if you need them to use in switch or EnumSet or EnumMap in future :)

OSError: [Errno 8] Exec format error

Have you tried this?

Out = subprocess.Popen('/usr/local/bin/script hostname = actual_server_name -p LONGLIST'.split(), shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 

Edited per the apt comment from @J.F.Sebastian

How to update single value inside specific array item in redux

Very late to the party but here is a generic solution that works with every index value.

  1. You create and spread new array from the old array up to the index you want to change.

  2. Add the data you want.

  3. Create and spread new array from the index you wanted to change to the end of the array

let index=1;// probabbly action.payload.id
case 'SOME_ACTION':
   return { 
       ...state, 
       contents: [
          ...state.contents.slice(0,index),
          {title: "some other title", text: "some other text"},
         ...state.contents.slice(index+1)
         ]
    }

Update:

I have made a small module to simplify the code, so you just need to call a function:

case 'SOME_ACTION':
   return {
       ...state,
       contents: insertIntoArray(state.contents,index, {title: "some title", text: "some text"})
    }

For more examples, take a look at the repository

function signature:

insertIntoArray(originalArray,insertionIndex,newData)

How to backup Sql Database Programmatically in C#

It's a good practice to use a config file like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=MyDB; Integrated Security=SSPI" ;Timeout=30"/>
  </connectionStrings>
  <appSettings>
    <add key="BackupFolder" value="C:/temp/"/>
  </appSettings>
</configuration> 

Your C# code will be something like this:

// read connectionstring from config file
var connectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; 

// read backup folder from config file ("C:/temp/")
var backupFolder = ConfigurationManager.AppSettings["BackupFolder"];

var sqlConStrBuilder = new SqlConnectionStringBuilder(connectionString);

// set backupfilename (you will get something like: "C:/temp/MyDatabase-2013-12-07.bak")
var backupFileName = String.Format("{0}{1}-{2}.bak", 
    backupFolder, sqlConStrBuilder.InitialCatalog, 
    DateTime.Now.ToString("yyyy-MM-dd"));

using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
{
    var query = String.Format("BACKUP DATABASE {0} TO DISK='{1}'", 
        sqlConStrBuilder.InitialCatalog, backupFileName);

    using (var command = new SqlCommand(query, connection))
    {
        connection.Open();
        command.ExecuteNonQuery();
    }
}

ReactJS: "Uncaught SyntaxError: Unexpected token <"

UPDATE -- use this instead:

<script type="text/babel" src="./lander.js"></script>

Add type="text/jsx" as an attribute of the script tag used to include the JavaScript file that must be transformed by JSX Transformer, like that:

<script type="text/jsx" src="./lander.js"></script>

Then you can use MAMP or some other service to host the page on localhost so that all of the inclusions work, as discussed here.

Thanks for all the help everyone!

Git's famous "ERROR: Permission to .git denied to user"

On Mac, if you have multiple GitHub logins and are not using SSH, force the correct login by using:

git remote set-url origin https://[email protected]/username/repo-name.git

This also works if you're having issues pushing to a private repository.

jQuery counting elements by class - what is the best way to implement this?

Getting a count of the number of elements that refer to the same class is as simple as this

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                alert( $(".red").length );
            });

        </script>
    </head>
    <body>

        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
    </body>
</html>

How to export the Html Tables data into PDF using Jspdf

Here is an example I think that will help you

<!DOCTYPE html>
<html>
<head>
<script src="js/min.js"></script>
<script src="js/pdf.js"></script>
<script>
    $(function(){
         var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

   $('#cmd').click(function () {

        var table = tableToJson($('#StudentInfoListTable').get(0))
        var doc = new jsPDF('p','pt', 'a4', true);
        doc.cellInitialize();
        $.each(table, function (i, row){
            console.debug(row);
            $.each(row, function (j, cell){
                doc.cell(10, 50,120, 50, cell, i);  // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
            })
        })


        doc.save('sample-file.pdf');
    });
    function tableToJson(table) {
    var data = [];

    // first row needs to be headers
    var headers = [];
    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }


    // go through cells
    for (var i=0; i<table.rows.length; i++) {

        var tableRow = table.rows[i];
        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {

            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

        }

        data.push(rowData);
    }       

    return data;
}
});
</script>
</head>
<body>
<div id="table">
<table id="StudentInfoListTable">
                <thead>
                    <tr>    
                        <th>Name</th>
                        <th>Email</th>
                        <th>Track</th>
                        <th>S.S.C Roll</th>
                        <th>S.S.C Division</th>
                        <th>H.S.C Roll</th>
                        <th>H.S.C Division</th>
                        <th>District</th>

                    </tr>
                </thead>
                <tbody>

                        <tr>
                            <td>alimon  </td>
                            <td>Email</td>
                            <td>1</td>
                            <td>2222</td>
                            <td>as</td>
                            <td>3333</td>
                            <td>dd</td>
                            <td>33</td>
                        </tr>               
                </tbody>
            </table>
<button id="cmd">Submit</button>
</body>
</html>

Here the output

enter image description here

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

MySQL and PHP - insert NULL rather than empty string

For some reason, radhoo's solution wouldn't work for me. When I used the following expression:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')?"NULL":("'".$val1."'")) . ", ".
    (($val2=='')?"NULL":("'".$val2."'")) . 
    ")";

'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')? :("'".$val1."'")) . ", ".
    (($val2=='')? :("'".$val2."'")) . 
    ")";

The blank resulted in the correct null (unquoted) being inserted into the query.

Artisan, creating tables in database

In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......

What is the purpose and use of **kwargs?

Keyword Arguments are often shortened to kwargs in Python. In computer programming,

keyword arguments refer to a computer language's support for function calls that clearly state the name of each parameter within the function call.

The usage of the two asterisk before the parameter name, **kwargs, is when one doesn't know how many keyword arguments will be passed into the function. When that's the case, it's called Arbitrary / Wildcard Keyword Arguments.

One example of this is Django's receiver functions.

def my_callback(sender, **kwargs):
    print("Request finished!")

Notice that the function takes a sender argument, along with wildcard keyword arguments (**kwargs); all signal handlers must take these arguments. All signals send keyword arguments, and may change those keyword arguments at any time. In the case of request_finished, it’s documented as sending no arguments, which means we might be tempted to write our signal handling as my_callback(sender).

This would be wrong – in fact, Django will throw an error if you do so. That’s because at any point arguments could get added to the signal and your receiver must be able to handle those new arguments.

Note that it doesn't have to be called kwargs, but it needs to have ** (the name kwargs is a convention).

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

NOTE: This is true for the version mentioned in the question, 4.1.1.RELEASE.

Spring MVC handles a ResponseEntity return value through HttpEntityMethodProcessor.

When the ResponseEntity value doesn't have a body set, as is the case in your snippet, HttpEntityMethodProcessor tries to determine a content type for the response body from the parameterization of the ResponseEntity return type in the signature of the @RequestMapping handler method.

So for

public ResponseEntity<Void> taxonomyPackageExists( @PathVariable final String key ) {

that type will be Void. HttpEntityMethodProcessor will then loop through all its registered HttpMessageConverter instances and find one that can write a body for a Void type. Depending on your configuration, it may or may not find any.

If it does find any, it still needs to make sure that the corresponding body will be written with a Content-Type that matches the type(s) provided in the request's Accept header, application/xml in your case.

If after all these checks, no such HttpMessageConverter exists, Spring MVC will decide that it cannot produce an acceptable response and therefore return a 406 Not Acceptable HTTP response.

With ResponseEntity<String>, Spring will use String as the response body and find StringHttpMessageConverter as a handler. And since StringHttpMessageHandler can produce content for any media type (provided in the Accept header), it will be able to handle the application/xml that your client is requesting.

Spring MVC has since been changed to only return 406 if the body in the ResponseEntity is NOT null. You won't see the behavior in the original question if you're using a more recent version of Spring MVC.


In iddy85's solution, which seems to suggest ResponseEntity<?>, the type for the body will be inferred as Object. If you have the correct libraries in your classpath, ie. Jackson (version > 2.5.0) and its XML extension, Spring MVC will have access to MappingJackson2XmlHttpMessageConverter which it can use to produce application/xml for the type Object. Their solution only works under these conditions. Otherwise, it will fail for the same reason I've described above.

Can Console.Clear be used to only clear a line instead of whole console?

We could simply write the following method

public static void ClearLine()
{
    Console.SetCursorPosition(0, Console.CursorTop - 1);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

and then call it when needed like this

Console.WriteLine("Test");
ClearLine();

It works fine for me.

gridview data export to excel in asp.net

I think it will help you

string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
        if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
            filename = GRIDVIEWNAME.Page.Title + ".xls";

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);


        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Charset = "";

        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);



        System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
        GRIDVIEWNAME.Parent.Controls.Add(form);
        form.Controls.Add(GRIDVIEWNAME);
        form.RenderControl(htmlWriter);

        HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        HttpContext.Current.Response.Write(stringWriter.ToString());
        HttpContext.Current.Response.End();

How to gracefully handle the SIGKILL signal in Java

It is impossible for any program, in any language, to handle a SIGKILL. This is so it is always possible to terminate a program, even if the program is buggy or malicious. But SIGKILL is not the only means for terminating a program. The other is to use a SIGTERM. Programs can handle that signal. The program should handle the signal by doing a controlled, but rapid, shutdown. When a computer shuts down, the final stage of the shutdown process sends every remaining process a SIGTERM, gives those processes a few seconds grace, then sends them a SIGKILL.

The way to handle this for anything other than kill -9 would be to register a shutdown hook. If you can use (SIGTERM) kill -15 the shutdown hook will work. (SIGINT) kill -2 DOES cause the program to gracefully exit and run the shutdown hooks.

Registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

I tried the following test program on OSX 10.6.3 and on kill -9 it did NOT run the shutdown hook, as expected. On a kill -15 it DOES run the shutdown hook every time.

public class TestShutdownHook
{
    public static void main(String[] args) throws InterruptedException
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Shutdown hook ran!");
            }
        });

        while (true)
        {
            Thread.sleep(1000);
        }
    }
}

There isn't any way to really gracefully handle a kill -9 in any program.

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.

The only real option to handle a kill -9 is to have another watcher program watch for your main program to go away or use a wrapper script. You could do with this with a shell script that polled the ps command looking for your program in the list and act accordingly when it disappeared.

#!/usr/bin/env bash

java TestShutdownHook
wait
# notify your other app that you quit
echo "TestShutdownHook quit"

Swift's guard keyword

There are really two big benefits to guard. One is avoiding the pyramid of doom, as others have mentioned – lots of annoying if let statements nested inside each other moving further and further to the right.

The other benefit is often the logic you want to implement is more "if not let” than "if let { } else".

Here’s an example: suppose you want to implement accumulate – a cross between map and reduce where it gives you back an array of running reduces. Here it is with guard:

extension Sliceable where SubSlice.Generator.Element == Generator.Element {

    func accumulate(combine: (Generator.Element,Generator.Element)->Generator.Element) -> [Generator.Element] {
        // if there are no elements, I just want to bail out and
        // return an empty array
        guard var running = self.first else { return [] }

        // running will now be an unwrapped non-optional
        var result = [running]

        // dropFirst is safe because the collection
        // must have at least one element at this point
        for x in dropFirst(self) {
            running = combine(running, x)
            result.append(running)
        }
        return result
    }

}


let a = [1,2,3].accumulate(+)  // [1,3,6]
let b = [Int]().accumulate(+)  // []

How would you write it without guard, but still using first that returns an optional? Something like this:

extension Sliceable where SubSlice.Generator.Element == Generator.Element {

    func accumulate(combine: (Generator.Element,Generator.Element)->Generator.Element) -> [Generator.Element] {

        if var running = self.first  {
            var result = [running]

            for x in dropFirst(self) {
                running = combine(running, x)
                result.append(running)
            }
            return result
        }
        else {
            return []
        }
    }

}

The extra nesting is annoying, but also, it’s not as logical to have the if and the else so far apart. It’s much more readable to have the early exit for the empty case, and then continue with the rest of the function as if that wasn’t a possibility.

Binding Combobox Using Dictionary as the Datasource

If this doesn't work why not simply do a foreach loop over the dictionary adding all the items to the combobox?

foreach(var item in userCache)
{
    userListComboBox.Items.Add(new ListItem(item.Key, item.Value));
}

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

C Macro definition to determine big endian or little endian machine?

Use an inline function rather than a macro. Besides, you need to store something in memory which is a not-so-nice side effect of a macro.

You could convert it to a short macro using a static or global variable, like this:

static int s_endianess = 0;
#define ENDIANESS() ((s_endianess = 1), (*(unsigned char*) &s_endianess) == 0)

python - checking odd/even numbers and changing outputs on number size

My solution basically we have two string and with the & we get the right index:

res = ["Even", "Odd"]
print(res[x & 1])

Please note that it seems slower than other alternatives:

#!/usr/bin/env python3
import math
import random
from timeit import timeit

res = ["Even", "Odd"]

def foo(x):
    return res[x & 1]

def bar(x):
    if x & 1:
        return "Odd"
    return "Even"

la = lambda x : "Even" if not x % 2 else "Odd"

iter = 10000000

time = timeit('bar(random.randint(1, 1000))', "from __main__ import bar, random", number=iter)
print(time)
time = timeit('la(random.randint(1, 1000))', "from __main__ import la, random", number=iter)
print(time)
time = timeit('foo(random.randint(1, 1000))', "from __main__ import foo, random", number=iter)
print(time)

output:
8.05739480999182
8.170479692984372
8.892275177990086

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

You can't, as far as I know, make the entire OS understand an http:+domain URL. You can only register new schemes (I use x-darkslide: in my app). If the app is installed, Mobile Safari will launch the app correctly.

However, you would have to handle the case where the app isn't installed with a "Still here? Click this link to download the app from iTunes." in your web page.

Defining a HTML template to append using JQuery

Other alternative: Pure

I use it and it has helped me a lot. An example shown on their website:

HTML

<div class="who">
</div>

JSON

{
  "who": "Hello Wrrrld"
}

Result

<div class="who">
  Hello Wrrrld
</div>

Percentage width in a RelativeLayout

Interestingly enough, building on the answer from @olefevre, one can not only do 50/50 layouts with "invisible struts", but all sorts of layouts involving powers of two.

For example, here is a layout that cuts the width into four equal parts (actually three, with weights of 1, 1, 2):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <View
        android:id="@+id/strut"
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:background="#000000" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/strut" >

        <View
            android:id="@+id/left_strut"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:layout_toLeftOf="@+id/strut"
            android:layout_centerHorizontal="true"
            android:background="#000000" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignRight="@+id/left_strut"
            android:text="Far Left" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_toRightOf="@+id/left_strut"
            android:text="Near Left" />
    </RelativeLayout>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/strut"
            android:layout_alignParentRight="true"
            android:text="Right" />

</RelativeLayout>

How can I pass a file argument to my bash script using a Terminal command in Linux?

It'll be easier (and more "proper", see below) if you just run your script as

myprogram /path/to/file

Then you can access the path within the script as $1 (for argument #1, similarly $2 is argument #2, etc.)

file="$1"
externalprogram "$file" [other parameters]

Or just

externalprogram "$1" [otherparameters]

If you want to extract the path from something like --file=/path/to/file, that's usually done with the getopts shell function. But that's more complicated than just referencing $1, and besides, switches like --file= are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.

How do I commit case-sensitive only filename changes in Git?

I've faced this issue several times on MacOS. Git is case sensitive but Mac is only case preserving.

Someone commit a file: Foobar.java and after a few days decides to rename it to FooBar.java. When you pull the latest code it fails with The following untracked working tree files would be overwritten by checkout...

The only reliable way that I've seen that fixes this is:

  1. git rm Foobar.java
  2. Commit it with a message that you cannot miss git commit -m 'TEMP COMMIT!!'
  3. Pull
  4. This will pop up a conflict forcing you to merge the conflict - because your change deleted it, but the other change renamed (hence the problem) it
    1. Accept your change which is the 'deletion'
    2. git rebase --continue
  5. Now drop your workaround git rebase -i HEAD~2 and drop the TEMP COMMIT!!
  6. Confirm that the file is now called FooBar.java

How can you debug a CORS request with cURL?

Here's how you can debug CORS requests using curl.

Sending a regular CORS request using cUrl:

curl -H "Origin: http://example.com" --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

The -H "Origin: http://example.com" flag is the third party domain making the request. Substitute in whatever your domain is.

The --verbose flag prints out the entire response so you can see the request and response headers.

The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.

The response should include the Access-Control-Allow-Origin header.

Sending a preflight request using cUrl:

curl -H "Origin: http://example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

This looks similar to the regular CORS request with a few additions:

The -H flags send additional preflight request headers to the server

The -X OPTIONS flag indicates that this is an HTTP OPTIONS request.

If the preflight request is successful, the response should include the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.

You can also specify additional headers, such as User-Agent, by using the -H flag.

How do I see the extensions loaded by PHP?

You asked where do you see loaded extensions in phpinfo() output.

Answer:

They are listed towards the bottom as separate sections/tables and ONLY if they are loaded. Here is an example of extension Curl loaded.

enter image description here ...

... enter image description here

I installed it on Linux Debian with

sudo apt-get install php7.4-curl

How do I copy an object in Java?

Alternative to egaga's constructor method of copy. You probably already have a POJO, so just add another method copy() which returns a copy of the initialized object.

class DummyBean {
    private String dummyStr;
    private int dummyInt;

    public DummyBean(String dummyStr, int dummyInt) {
        this.dummyStr = dummyStr;
        this.dummyInt = dummyInt;
    }

    public DummyBean copy() {
        return new DummyBean(dummyStr, dummyInt);
    }

    //... Getters & Setters
}

If you already have a DummyBean and want a copy:

DummyBean bean1 = new DummyBean("peet", 2);
DummyBean bean2 = bean1.copy(); // <-- Create copy of bean1 

System.out.println("bean1: " + bean1.getDummyStr() + " " + bean1.getDummyInt());
System.out.println("bean2: " + bean2.getDummyStr() + " " + bean2.getDummyInt());

//Change bean1
bean1.setDummyStr("koos");
bean1.setDummyInt(88);

System.out.println("bean1: " + bean1.getDummyStr() + " " + bean1.getDummyInt());
System.out.println("bean2: " + bean2.getDummyStr() + " " + bean2.getDummyInt());

Output:

bean1: peet 2
bean2: peet 2

bean1: koos 88
bean2: peet 2

But both works well, it is ultimately up to you...

Python send POST with header

Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.

import requests
import json

url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
    "Host": "www.mywbsite.fr",
    "Connection": "keep-alive",
    "Content-Length": 129,
    "Origin": "https://www.mywbsite.fr",
    "X-Requested-With": "XMLHttpRequest",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
    "Content-Type": "application/json",
    "Accept": "*/*",
    "Referer": "https://www.mywbsite.fr/data/mult.aspx",
    "Accept-Encoding": "gzip,deflate,sdch",
    "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
    "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
    "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)

Evenly space multiple views within a container view

Building on Ben Dolman's answer, this distributes the views more evenly (with padding, etc):

+(NSArray *)constraintsForEvenDistributionOfItems:(NSArray *)views
                           relativeToCenterOfItem:(id)toView vertically:(BOOL)vertically
{
    NSMutableArray *constraints = [NSMutableArray new];
    NSLayoutAttribute attr = vertically ? NSLayoutAttributeCenterY : NSLayoutAttributeCenterX;

    CGFloat min = 0.25;
    CGFloat max = 1.75;
    CGFloat d = (max-min) / ([views count] - 1);
    for (NSUInteger i = 0; i < [views count]; i++) {
        id view = views[i];
        CGFloat multiplier = i * d + min;
        NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:view
                                                                      attribute:attr
                                                                      relatedBy:NSLayoutRelationEqual
                                                                         toItem:toView
                                                                      attribute:attr
                                                                     multiplier:multiplier
                                                                       constant:0];
        [constraints addObject:constraint];
    }

    return constraints;
}

What is the difference between MOV and LEA?

None of the previous answers quite got to the bottom of my own confusion, so I'd like to add my own.

What I was missing is that lea operations treat the use of parentheses different than how mov does.

Think of C. Let's say I have an array of long that I call array. Now the expression array[i] performs a dereference, loading the value from memory at the address array + i * sizeof(long) [1].

On the other hand, consider the expression &array[i]. This still contains the sub-expression array[i], but no dereferencing is performed! The meaning of array[i] has changed. It no longer means to perform a deference but instead acts as a kind of a specification, telling & what memory address we're looking for. If you like, you could alternatively think of the & as "cancelling out" the dereference.

Because the two use-cases are similar in many ways, they share the syntax array[i], but the existence or absence of a & changes how that syntax is interpreted. Without &, it's a dereference and actually reads from the array. With &, it's not. The value array + i * sizeof(long) is still calculated, but it is not dereferenced.

The situation is very similar with mov and lea. With mov, a dereference occurs that does not happen with lea. This is despite the use of parentheses that occurs in both. For instance, movq (%r8), %r9 and leaq (%r8), %r9. With mov, these parentheses mean "dereference"; with lea, they don't. This is similar to how array[i] only means "dereference" when there is no &.

An example is in order.

Consider the code

movq (%rdi, %rsi, 8), %rbp

This loads the value at the memory location %rdi + %rsi * 8 into the register %rbp. That is: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Find the value at this location and place it into the register %rbp.

This code corresponds to the C line x = array[i];, where array becomes %rdi and i becomes %rsi and x becomes %rbp. The 8 is the length of the data type contained in the array.

Now consider similar code that uses lea:

leaq (%rdi, %rsi, 8), %rbp

Just as the use of movq corresponded to dereferencing, the use of leaq here corresponds to not dereferencing. This line of assembly corresponds to the C line x = &array[i];. Recall that & changes the meaning of array[i] from dereferencing to simply specifying a location. Likewise, the use of leaq changes the meaning of (%rdi, %rsi, 8) from dereferencing to specifying a location.

The semantics of this line of code are as follows: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Place this value into the register %rbp. No load from memory is involved, just arithmetic operations [2].

Note that the only difference between my descriptions of leaq and movq is that movq does a dereference, and leaq doesn't. In fact, to write the leaq description, I basically copy+pasted the description of movq, and then removed "Find the value at this location".

To summarize: movq vs. leaq is tricky because they treat the use of parentheses, as in (%rsi) and (%rdi, %rsi, 8), differently. In movq (and all other instruction except lea), these parentheses denote a genuine dereference, whereas in leaq they do not and are purely convenient syntax.


[1] I've said that when array is an array of long, the expression array[i] loads the value from the address array + i * sizeof(long). This is true, but there's a subtlety that should be addressed. If I write the C code

long x = array[5];

this is not the same as typing

long x = *(array + 5 * sizeof(long));

It seems that it should be based on my previous statements, but it's not.

What's going on is that C pointer addition has a trick to it. Say I have a pointer p pointing to values of type T. The expression p + i does not mean "the position at p plus i bytes". Instead, the expression p + i actually means "the position at p plus i * sizeof(T) bytes".

The convenience of this is that to get "the next value" we just have to write p + 1 instead of p + 1 * sizeof(T).

This means that the C code long x = array[5]; is actually equivalent to

long x = *(array + 5)

because C will automatically multiply the 5 by sizeof(long).

So in the context of this StackOverflow question, how is this all relevant? It means that when I say "the address array + i * sizeof(long)", I do not mean for "array + i * sizeof(long)" to be interpreted as a C expression. I am doing the multiplication by sizeof(long) myself in order to make my answer more explicit, but understand that due to that, this expression should not be read as C. Just as normal math that uses C syntax.

[2] Side note: because all lea does is arithmetic operations, its arguments don't actually have to refer to valid addresses. For this reason, it's often used to perform pure arithmetic on values that may not be intended to be dereferenced. For instance, cc with -O2 optimization translates

long f(long x) {
  return x * 5;
}

into the following (irrelevant lines removed):

f:
  leaq (%rdi, %rdi, 4), %rax  # set %rax to %rdi + %rdi * 4
  ret

How to find the most recent file in a directory using .NET, and without looping?

I do this is a bunch of my apps and I use a statement like this:

  var inputDirectory = new DirectoryInfo("\\Directory_Path_here");
  var myFile = inputDirectory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();

From here you will have the filename for the most recently saved/added/updated file in the Directory of the "inputDirectory" variable. Now you can access it and do what you want with it.

Hope that helps.

javascript regular expression to check for IP addresses

Try this one.. Source from here.

"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

Global variables in R

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value

Convert String to Calendar Object in Java

No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();

(I can't comment yet, that's why I created a new answer)

How to find the unclosed div tag

I made an online tool called Unclosed Tag Finder which will do what you need.

Paste in your HTML, and it will give you output like "Closing tag on line 188 does not match open tag on line 62."

Update: The new location of the Unclosed Tag Finder is https://jonaquino.blogspot.com/2013/05/unclosed-tag-finder.html

What's the difference between VARCHAR and CHAR?

CHAR is a fixed length field; VARCHAR is a variable length field. If you are storing strings with a wildly variable length such as names, then use a VARCHAR, if the length is always the same, then use a CHAR because it is slightly more size-efficient, and also slightly faster.

JPA: how do I persist a String into a database field, type MYSQL Text

for mysql 'text':

@Column(columnDefinition = "TEXT")
private String description;

for mysql 'longtext':

@Lob
private String description;

int to hex string

Previous answer is not good for negative numbers. Use a short type instead of int

        short iValue = -1400;
        string sResult = iValue.ToString("X2");
        Console.WriteLine("Value={0} Result={1}", iValue, sResult);

Now result is FA88

How to convert CSV file to multiline JSON?

You can try this

import csvmapper

# how does the object look
mapper = csvmapper.DictMapper([ 
  [ 
     { 'name' : 'FirstName'},
     { 'name' : 'LastName' },
     { 'name' : 'IDNumber', 'type':'int' },
     { 'name' : 'Messages' }
  ]
 ])

# parser instance
parser = csvmapper.CSVParser('sample.csv', mapper)
# conversion service
converter = csvmapper.JSONConverter(parser)

print converter.doConvert(pretty=True)

Edit:

Simpler approach

import csvmapper

fields = ('FirstName', 'LastName', 'IDNumber', 'Messages')
parser = CSVParser('sample.csv', csvmapper.FieldMapper(fields))

converter = csvmapper.JSONConverter(parser)

print converter.doConvert(pretty=True)

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

There are two ways to achieve that:

  • Use -rpath linker option:

gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib

  • Use LD_LIBRARY_PATH environment variable - put this line in your ~/.bashrc file:

    export LD_LIBRARY_PATH=/home/user/.usr/lib

This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.

For a quick test, you can also do (in bash at least):

LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out

which has the advantage of not changing your library path for everything else.

How do I find duplicate values in a table in Oracle?

Another way:

SELECT *
FROM TABLE A
WHERE EXISTS (
  SELECT 1 FROM TABLE
  WHERE COLUMN_NAME = A.COLUMN_NAME
  AND ROWID < A.ROWID
)

Works fine (quick enough) when there is index on column_name. And it's better way to delete or update duplicate rows.

Same font except its weight seems different on different browsers

Try text-rendering: geometricPrecision;.

Different from text-rendering: optimizeLegibility;, it takes care of kerning problems when scaling fonts, while the last enables kerning and ligatures.

MySQL string replace

In addition to gmaggio's answer if you need to dynamically REPLACE and UPDATE according to another column you can do for example:

UPDATE your_table t1
INNER JOIN other_table t2
ON t1.field_id = t2.field_id
SET t1.your_field = IF(LOCATE('articles/updates/', t1.your_field) > 0, 
REPLACE(t1.your_field, 'articles/updates/', t2.new_folder), t1.your_field) 
WHERE...

In my example the string articles/news/ is stored in other_table t2 and there is no need to use LIKE in the WHERE clause.

How to check type of variable in Java?

I hit this question as I was trying to get something similar working using Generics. Taking some of the answers and adding getClass().isArray() I get the following that seems to work.

public class TypeTester <T extends Number>{

<T extends Object> String tester(T ToTest){

    if (ToTest instanceof Integer) return ("Integer");
    else if(ToTest instanceof Double) return ("Double");
    else if(ToTest instanceof Float) return ("Float");
    else if(ToTest instanceof String) return ("String");
    else if(ToTest.getClass().isArray()) return ("Array");
    else return ("Unsure");
}
}

I call it with this where the myArray part was simply to get an Array into callFunction.tester() to test it.

public class Generics {
public static void main(String[] args) {
    int [] myArray = new int [10];

    TypeTester<Integer> callFunction = new TypeTester<Integer>();
    System.out.println(callFunction.tester(myArray));
}
}

You can swap out the myArray in the final line for say 10.2F to test Float etc

Can I use library that used android support with Androidx projects.

I added below two lines in gradle.properties file

android.useAndroidX=true
android.enableJetifier=true

then I got the following error

error: package android.support.v7.app does not exist
import android.support.v7.app.AlertDialog;
                         ^
                         

I have removed the imports and added below line

import static android.app.AlertDialog.*;

And the classes which are extended from AppCompactActivity, added the below line. (For these errors you just need to press alt+enter in android studio which will import the correct library for you. Like this you can resolve all the errors)

import androidx.appcompat.app.AppCompatActivity;

In your xml file if you have used any

<android.support.v7.widget.Toolbar 

replace it with androidx.appcompat.widget.Toolbar

then in your java code

import androidx.appcompat.widget.Toolbar;

SQL : BETWEEN vs <= and >=

They are identical: BETWEEN is a shorthand for the longer syntax in the question.

Use an alternative longer syntax where BETWEEN doesn't work e.g.

Select EventId,EventName from EventMaster
where EventDate >= '10/15/2009' and EventDate < '10/19/2009'

(Note < rather than <= in second condition.)

Unable to find valid certification path to requested target - error even after cert imported

In my case I was facing the problem because in my tomcat process specific keystore was given using

-Djavax.net.ssl.trustStore=/pathtosomeselfsignedstore/truststore.jks

Wheras I was importing the certificate to the cacert of JRE/lib/security and the changes were not reflecting. Then I did below command where /tmp/cert1.test contains the certificate of the target server

keytool -import -trustcacerts -keystore /pathtosomeselfsignedstore/truststore.jks -storepass password123 -noprompt -alias rapidssl-myserver -file /tmp/cert1.test

We can double check if the certificate import is successful

keytool -list -v -keystore /pathtosomeselfsignedstore/truststore.jks

and see if your taget server is found against alias rapidssl-myserver

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

Get response from PHP file using AJAX

The good practice is to use like this:

$.ajax({
    type: "POST",
    url: "/ajax/request.html",
    data: {action: 'test'},
    dataType:'JSON', 
    success: function(response){
        console.log(response.blablabla);
        // put on console what server sent back...
    }
});

and the php part is:

<?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        echo json_encode(array("blablabla"=>$variable));
    }
?>

Image size (Python, OpenCV)

I believe simply img.shape[-1::-1] would be nicer.

Failed binder transaction when putting an bitmap dynamically in a widget

The right approach is to use setImageViewUri() (slower) or the setImageViewBitmap() and recreating RemoteViews every time you update the notification.

How do I duplicate a line or selection within Visual Studio Code?

If you coming from Sublime Text and do not want to relearn new key binding, you can use this extension for Visual Code Studio.

Sublime Text Keymap for VS Code

This extension ports the most popular Sublime Text keyboard shortcuts to Visual Studio Code. After installing the extension and restarting VS Code your favorite keyboard shortcuts from Sublime Text are now available.

https://marketplace.visualstudio.com/items?itemName=ms-vscode.sublime-keybindings

Toad for Oracle..How to execute multiple statements?

You can either go for f5 it will execute all the scrips on the tab.

Or

You can create a sql file and put all the insert statements in it and than give the file path in sql plus and execute.

Visual Studio can't build due to rc.exe

If you really need to use the SDK Windows 10 with Visual Studio 2015, you have to download an older version on sdk-archive. Newer version of the SDK changed the place of the rc executable and MSBuild of Visual Studio 2015 update 3 (latest version) can't locate it. At least the version 10.0.14393.795 of the SDK Windows is still compatible with Visual Studio 2015.

How to get Android application id?

If your are looking for the value defined by applicationId in gradle, you can simply use

BuildConfig.APPLICATION_ID 

Add a custom attribute to a Laravel / Eloquent model on load?

I had something simular: I have an attribute picture in my model, this contains the location of the file in the Storage folder. The image must be returned base64 encoded

//Add extra attribute
protected $attributes = ['picture_data'];

//Make it available in the json response
protected $appends = ['picture_data'];

//implement the attribute
public function getPictureDataAttribute()
{
    $file = Storage::get($this->picture);
    $type = Storage::mimeType($this->picture);
    return "data:" . $type . ";base64," . base64_encode($file);
}

How to deep merge instead of shallow merge?

I know there's a lot of answers already and as many comments arguing they won't work. The only consensus is that it's so complicated that nobody made a standard for it. However, most of accepted answers in SO expose "simple tricks" that are widely used. So, for all of us like me who are no experts but want to write safer code by grasping a little more about javascript's complexity, I'll try to shed some light.

Before getting our hands dirty, let me clarify 2 points:

  • [DISCLAIMER] I propose a function below that tackles how we deep loop into javascript objects for copy and illustrates what is generally too shortly commented. It is not production-ready. For sake of clarity, I have purposedly left aside other considerations like circular objects (track by a set or unconflicting symbol property), copying reference value or deep clone, immutable destination object (deep clone again?), case-by-case study of each type of objects, get/set properties via accessors... Also, I did not test performance -although it's important- because it's not the point here either.
  • I'll use copy or assign terms instead of merge. Because in my mind a merge is conservative and should fail upon conflicts. Here, when conflicting, we want the source to overwrite the destination. Like Object.assign does.

Answers with for..in or Object.keys are misleading

Making a deep copy seems so basic and common practice that we expect to find a one-liner or, at least, a quick win via simple recursion. We don't expect we should need a library or write a custom function of 100 lines.

When I first read Salakar's answer, I genuinely thought I could do better and simpler (you can compare it with Object.assign on x={a:1}, y={a:{b:1}}). Then I read the8472's answer and I thought... there is no getting away so easily, improving already given answers won't get us far.

Let's let deep copy and recursive aside an instant. Just consider how (wrongly) people parse properties to copy a very simple object.

const y = Object.create(
    { proto : 1 },
    { a: { enumerable: true, value: 1},
      [Symbol('b')] : { enumerable: true, value: 1} } )

Object.assign({},y)
> { 'a': 1, Symbol(b): 1 } // All (enumerable) properties are copied

((x,y) => Object.keys(y).reduce((acc,k) => Object.assign(acc, { [k]: y[k] }), x))({},y)
> { 'a': 1 } // Missing a property!

((x,y) => {for (let k in y) x[k]=y[k];return x})({},y)
> { 'a': 1, 'proto': 1 } // Missing a property! Prototype's property is copied too!

Object.keys will omit own non-enumerable properties, own symbol-keyed properties and all prototype's properties. It may be fine if your objects don't have any of those. But keep it mind that Object.assign handles own symbol-keyed enumerable properties. So your custom copy lost its bloom.

for..in will provide properties of the source, of its prototype and of the full prototype chain without you wanting it (or knowing it). Your target may end up with too many properties, mixing up prototype properties and own properties.

If you're writing a general purpose function and you're not using Object.getOwnPropertyDescriptors, Object.getOwnPropertyNames, Object.getOwnPropertySymbols or Object.getPrototypeOf, you're most probably doing it wrong.

Things to consider before writing your function

First, make sure you understand what a Javascript object is. In Javascript, an object is made of its own properties and a (parent) prototype object. The prototype object in turn is made of its own properties and a prototype object. And so on, defining a prototype chain.

A property is a pair of key (string or symbol) and descriptor (value or get/set accessor, and attributes like enumerable).

Finally, there are many types of objects. You may want to handle differently an object Object from an object Date or an object Function.

So, writing your deep copy, you should answer at least those questions:

  1. What do I consider deep (proper for recursive look up) or flat?
  2. What properties do I want to copy? (enumerable/non-enumerable, string-keyed/symbol-keyed, own properties/prototype's own properties, values/descriptors...)

For my example, I consider that only the object Objects are deep, because other objects created by other constructors may not be proper for an in-depth look. Customized from this SO.

function toType(a) {
    // Get fine type (object, array, function, null, error, date ...)
    return ({}).toString.call(a).match(/([a-z]+)(:?\])/i)[1];
}

function isDeepObject(obj) {
    return "Object" === toType(obj);
}

And I made an options object to choose what to copy (for demo purpose).

const options = {nonEnum:true, symbols:true, descriptors: true, proto:true};

Proposed function

You can test it in this plunker.

function deepAssign(options) {
    return function deepAssignWithOptions (target, ...sources) {
        sources.forEach( (source) => {

            if (!isDeepObject(source) || !isDeepObject(target))
                return;

            // Copy source's own properties into target's own properties
            function copyProperty(property) {
                const descriptor = Object.getOwnPropertyDescriptor(source, property);
                //default: omit non-enumerable properties
                if (descriptor.enumerable || options.nonEnum) {
                    // Copy in-depth first
                    if (isDeepObject(source[property]) && isDeepObject(target[property]))
                        descriptor.value = deepAssign(options)(target[property], source[property]);
                    //default: omit descriptors
                    if (options.descriptors)
                        Object.defineProperty(target, property, descriptor); // shallow copy descriptor
                    else
                        target[property] = descriptor.value; // shallow copy value only
                }
            }

            // Copy string-keyed properties
            Object.getOwnPropertyNames(source).forEach(copyProperty);

            //default: omit symbol-keyed properties
            if (options.symbols)
                Object.getOwnPropertySymbols(source).forEach(copyProperty);

            //default: omit prototype's own properties
            if (options.proto)
                // Copy souce prototype's own properties into target prototype's own properties
                deepAssign(Object.assign({},options,{proto:false})) (// Prevent deeper copy of the prototype chain
                    Object.getPrototypeOf(target),
                    Object.getPrototypeOf(source)
                );

        });
        return target;
    }
}

That can be used like this:

const x = { a: { a: 1 } },
      y = { a: { b: 1 } };
deepAssign(options)(x,y); // { a: { a: 1, b: 1 } }

Clone private git repo with dockerfile

Another option is to use a multi-stage docker build to ensure that your SSH keys are not included in the final image.

As described in my post you can prepare your intermediate image with the required dependencies to git clone and then COPY the required files into your final image.

Additionally if we LABEL our intermediate layers, we can even delete them from the machine when finished.

# Choose and name our temporary image.
FROM alpine as intermediate
# Add metadata identifying these images as our build containers (this will be useful later!)
LABEL stage=intermediate

# Take an SSH key as a build argument.
ARG SSH_KEY

# Install dependencies required to git clone.
RUN apk update && \
    apk add --update git && \
    apk add --update openssh

# 1. Create the SSH directory.
# 2. Populate the private key file.
# 3. Set the required permissions.
# 4. Add github to our list of known hosts for ssh.
RUN mkdir -p /root/.ssh/ && \
    echo "$SSH_KEY" > /root/.ssh/id_rsa && \
    chmod -R 600 /root/.ssh/ && \
    ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

# Clone a repository (my website in this case)
RUN git clone [email protected]:janakerman/janakerman.git

# Choose the base image for our final image
FROM alpine

# Copy across the files from our `intermediate` container
RUN mkdir files
COPY --from=intermediate /janakerman/README.md /files/README.md

We can then build:

MY_KEY=$(cat ~/.ssh/id_rsa)
docker build --build-arg SSH_KEY="$MY_KEY" --tag clone-example .

Prove our SSH keys are gone:

docker run -ti --rm clone-example cat /root/.ssh/id_rsa

Clean intermediate images from the build machine:

docker rmi -f $(docker images -q --filter label=stage=intermediate)

How can I manually generate a .pyc file from a .py file

You can use compileall in the terminal. The following command will go recursively into sub directories and make pyc files for all the python files it finds. The compileall module is part of the python standard library, so you don't need to install anything extra to use it. This works exactly the same way for python2 and python3.

python -m compileall .

ASP.NET MVC DropDownListFor with model of type List<string>

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

@model List<string>
@Html.DropDownList(
    "Foo", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    )
)

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

<select name="Foo" id="Foo">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
    ...
</select>

This being said a far better view model for a drop down list is the following:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then:

@model MyListModel
@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

CodeIgniter Disallowed Key Characters

I got this error when sending data from a rich text editor where I had included an ampersand. Replacing the ampersand with %26 - the URL encoding of ampersand - solved the problem. I also found that a jQuery ajax request configured like this magically solves the problem:

request = $.ajax({
        "url": url,
        type: "PUT",
        dataType: "json",
        data: json
    });

where the object json is, surprise, surprise, a JSON object containing a property with a value that contains an ampersand.

How do I concatenate two lists in Python?

If you want to merge the two lists in sorted form, you can use the merge function from the heapq library.

from heapq import merge

a = [1, 2, 4]
b = [2, 4, 6, 7]

print list(merge(a, b))

How to find keys of a hash?

I wanted to use the top rated answer above

Object.prototype.keys = function () ...

However when using in conjunction with the google maps API v3, google maps is non-functional.

for (var key in h) ...

works well.

How to scroll table's "tbody" independent of "thead"?

I saw this post about a month ago when I was having similar problems. I needed y-axis scrolling for a table inside of a ui dialog (yes, you heard me right). I was lucky, in that a working solution presented itself fairly quickly. However, it wasn't long before the solution took on a life of its own, but more on that later.

The problem with just setting the top level elements (thead, tfoot, and tbody) to display block, is that browser synchronization of the column sizes between the various components is quickly lost and everything packs to the smallest permissible size. Setting the widths of the columns seems like the best course of action, but without setting the widths of all the internal table components to match the total of these columns, even with a fixed table layout, there is a slight divergence between the headers and body when a scroll bar is present.

The solution for me was to set all the widths, check if a scroll bar was present, and then take the scaled widths the browser had actually decided on, and copy those to the header and footer adjusting the last column width for the size of the scroll bar. Doing this provides some fluidity to the column widths. If changes to the table's width occur, most major browsers will auto-scale the tbody column widths accordingly. All that's left is to set the header and footer column widths from their respective tbody sizes.

$table.find("> thead,> tfoot").find("> tr:first-child")
    .each(function(i,e) {
        $(e).children().each(function(i,e) {
            if (i != column_scaled_widths.length - 1) {
                $(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()));
            } else {
                $(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()) + $.position.scrollbarWidth());
            }
        });
    });

This fiddle illustrates these notions: http://jsfiddle.net/borgboyone/gbkbhngq/.

Note that a table wrapper or additional tables are not needed for y-axis scrolling alone. (X-axis scrolling does require a wrapping table.) Synchronization between the column sizes for the body and header will still be lost if the minimum pack size for either the header or body columns is encountered. A mechanism for minimum widths should be provided if resizing is an option or small table widths are expected.

The ultimate culmination from this starting point is fully realized here: http://borgboyone.github.io/jquery-ui-table/

A.

Remove trailing zeros from decimal in SQL Server

try this.

select CAST(123.456700 as float),cast(cast(123.4567 as DECIMAL(9,6)) as float)

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

While there might be a way I would tend to keep that kind of logic out of the Model. I agree that you shouldn't put that in the view (keep it skinny) but unless the model is returning a url as a piece of data to the controller, the routing stuff should be in the controller.

C# importing class into another class doesn't work

MyClass is a class not a namespace. So this code is wrong:

using MyClass //THIS CODE IS NOT CORRECT

You should check the namespace of the MyClass (e.g: MyNamespace). Then call it in a proper way:

MyNamespace.MyClass myClass =new MyNamespace.MyClass();

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

Little Edit

Try adding

return new JavascriptResult() { Script = "alert('Successfully registered');" };

in place of

return RedirectToAction("Index");

Parse date without timezone javascript

Since it is really a formatting issue when displaying the date (e.g. displays in local time), I like to use the new(ish) Intl.DateTimeFormat object to perform the formatting as it is more explicit and provides more output options:

const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };

const dateFormatter = new Intl.DateTimeFormat('en-US', dateOptions);
const dateAsFormattedString = dateFormatter.format(new Date('2019-06-01T00:00:00.000+00:00'));

console.log(dateAsFormattedString) // "June 1, 2019"

As shown, by setting the timeZone to 'UTC' it will not perform local conversions. As a bonus, it also allows you to create more polished outputs. You can read more about the Intl.DateTimeFormat object from Mozilla - Intl.DateTimeFormat.

Edit:

The same functionality can be achieved without creating a new Intl.DateTimeFormat object. Simply pass the locale and date options directly into the toLocaleDateString() function.

const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
const myDate = new Date('2019-06-01T00:00:00.000+00:00');
today.toLocaleDateString('en-US', dateOptions); // "June 1, 2019"

Ruby: Can I write multi-line string with no concatenation?

You can also use double quotes

x = """
this is 
a multiline
string
"""

2.3.3 :012 > x
 => "\nthis is\na multiline\nstring\n"

If needed to remove line breaks "\n" use backslash "\" at the end of each line

How do I exclude Weekend days in a SQL Server query?

SELECT date_created
FROM your_table
WHERE DATENAME(dw, date_created) NOT IN ('Saturday', 'Sunday')

Make git automatically remove trailing whitespace before committing

the for-loop for files uses the $IFS shell variable. in the given script, filenames with a character in them that also is in the $IFS-variable will be seen as two different files in the for-loop. This script fixes it: multiline-mode modifier as given sed-manual doesn't seem to work by default on my ubuntu box, so i sought for a different implemenation and found this with an iterating label, essentially it will only start substitution on the last line of the file if i've understood it correctly.

#!/bin/sh
#

# A git hook script to find and fix trailing whitespace
# in your commits. Bypass it with the --no-verify option
# to git-commit
#

if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

SAVEIFS="$IFS"
# only use new-line character as seperator, introduces EOL-bug?
IFS='
'
# Find files with trailing whitespace
for FILE in $(
    git diff-index --check --cached $against -- \
    | sed '/^[+-]/d' \
    | ( sed -r 's/:[0-9]+:.*//' || sed -E 's/:[0-9]+:.*//' ) \
    | uniq \
)
do
# replace whitespace-characters with nothing
# if first execution of sed-command fails, try second one( MacOSx-version)
    (
        sed -i ':a;N;$!ba;s/\n\+$//' "$FILE" > /dev/null 2>&1 \
        || \
        sed -i '' -E ':a;N;$!ba;s/\n\+$//' "$FILE" \
    ) \
    && \
# (re-)add files that have been altered to git commit-tree
#   when change was a [:space:]-character @EOL|EOF git-history becomes weird...
    git add "$FILE"
done
# restore $IFS
IFS="$SAVEIFS"

# exit script with the exit-code of git's check for whitespace-characters
exec git diff-index --check --cached $against --

[1] sed-subsition pattern: How can I replace a newline (\n) using sed? .

Field 'browser' doesn't contain a valid alias configuration

In my case I was using invalid templateUrl.By correcting it problem solved.

@Component({
        selector: 'app-edit-feather-object',
        templateUrl: ''
    })

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

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

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

from scipy.signal import butter, lfilter


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


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


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

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

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

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

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

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

    plt.show()

Here are the plots that are generated by this script:

Frequency response for several filter orders

enter image description here

Why is HttpClient BaseAddress not working?

Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.

i.e.

var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
                inventory = inventoryId
            });

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"