Programs & Examples On #Bitmapsource

Bitmapsource represents a single, constant set of pixels at a certain size and resolution.

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

What's the C# equivalent to the With statement in VB?

The closest thing in C# 3.0, is that you can use a constructor to initialize properties:

Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}

Border color on default input style

whats actually wrong with:

input { border: 1px solid #f00; }

do you only want it on inputs with errors? in that case give the input a class of error...

input.error { border: 1px solid #f00; }

Remove x-axis label/text in chart.js

(this question is a duplicate of In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?) They added the option, 2.1.4 (and maybe a little earlier) has it

var myLineChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    display: false
                }
            }]
        }
    }
}

Stratified Train/Test-split in scikit-learn

You can simply do it with train_test_split() method available in Scikit learn:

from sklearn.model_selection import train_test_split 
train, test = train_test_split(X, test_size=0.25, stratify=X['YOUR_COLUMN_LABEL']) 

I have also prepared a short GitHub Gist which shows how stratify option works:

https://gist.github.com/SHi-ON/63839f3a3647051a180cb03af0f7d0d9

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

Make sure you import csv file using Pandas

import pandas as pd

condition = pd.isnull(data[i][j])

When should null values of Boolean be used?

For all the good answers above, I'm just going to give a concrete example in Java servlet HttpSession class. Hope this example helps to clarify some question you may still have.

If you need to store and retrieve values for a session, you use setAttribute(String, Object), and getAttribute(String, Object) method. So for a boolean value, you are forced to use the Boolean class if you want to store it in an http session.

HttpSession sess = request.getSession(false);
Boolean isAdmin = (Boolean) sess.getAttribute("admin");
if (! isAdmin) ...

The last line will cause a NullPointerException if the attribute values is not set. (which is the reason led me to this post). So the 3 logic state is here to stay, whether you prefer to use it or not.

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

Change Active Menu Item on Page Scroll?

If you want the accepted answer to work in JQuery 3 change the code like this:

var scrollItems = menuItems.map(function () {
    var id = $(this).attr("href");
    try {
        var item = $(id);
      if (item.length) {
        return item;
      }
    } catch {}
  });

I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)

Differences between key, superkey, minimal superkey, candidate key and primary key

Largely based on the accepted answer, but with a few tweaks to fit better the definitions taught in some courses:

  • Key: A set of = 1 columns.
  • Superkey: A key that ? a candidate key.
    • Therefore, a superkey must contain > 1 columns.
    • Minimal Super key = Candidate Key: A key that can uniquely identify each row in a table.
    • Primary Key: The chosen Candidate Key for doing that.
    • Secondary key / Alternate key: A Candidate Key not chosen for doing that.
  • Search Key: A key used for locating records.
  • Composite key or concatenate key: A key with > 1 columns.
    • Usually implies "composite primary key", although "composite alternate key" is also a thing.
  • Sort or control key: A key used to physically sequence the stored data.
  • Foreign Key A key in one table that matches the Primary Key of another table.
    • The table in which foreign key resides is called as dependent table.
    • The table to which foreign key refers is known as parent table.

Get most recent file in a directory on Linux

If you want to get the most recent changed file also including any subdirectories you can do it with this little oneliner:

find . -type f -exec stat -c '%Y %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done

If you want to do the same not for changed files, but for accessed files you simple have to change the

%Y parameter from the stat command to %X. And your command for most recent accessed files looks like this:

find . -type f -exec stat -c '%X %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done

For both commands you also can change the var="1" parameter if you want to list more than just one file.

How to round a Double to the nearest Int in swift?

Swift 3

var myNum = 8.09
myNum.rounded() // result = 8 and leaves myNum unmodified

Rounding to 2 decimal places in SQL

you may try the TO_CHAR function to convert the result

e.g.

SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL

SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL

Hope it helps

Differences between action and actionListener

TL;DR:

The ActionListeners (there can be multiple) execute in the order they were registered BEFORE the action

Long Answer:

A business action typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view if that is not what you are doing an actionListener is more appropriate i.e. for when the user interacts with the components, such as h:commandButton or h:link they can be handled by passing the name of the managed bean method in actionListener attribute of a UI Component or to implement an ActionListener interface and pass the implementation class name to actionListener attribute of a UI Component.

How to add one day to a date?

you want after days find date this code try..

public Date getToDateAfterDays(Integer day) {
        Date nowdate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(nowdate);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }

Vertically aligning a checkbox

This works reliably for me. Cell borders and height added for effect and clarity:

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td style="text-align:right; border: thin solid; height:50px">Some label:</td>_x000D_
    <td style="border: thin solid;">_x000D_
      <input type="checkbox" checked="checked" id="chk1" style="cursor:pointer; "><label for="chk1" style="margin-top:auto; margin-left:5px; margin-bottom:auto; cursor:pointer;">Check Me</label>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to export all collections in MongoDB?

#mongodump using sh script 
#!/bin/bash
TIMESTAMP=`date +%F-%H%M`
APP_NAME="folder_name"
BACKUPS_DIR="/xxxx/tst_file_bcup/$APP_NAME"
BACKUP_NAME="$APP_NAME-$TIMESTAMP"
/usr/bin/mongodump -h 127.0.0.1 -d <dbname> -o $BACKUPS_DIR/$APP_NAME/$BACKUP_NAME
tar -zcvf $BACKUPS_DIR/$BACKUP_NAME.tgz $BACKUPS_DIR/$APP_NAME/$BACKUP_NAME
rm -rf /home/wowza_analytics_bcup/wowza_analytics/wowza_analytics
### 7 days old backup delete automaticaly using given command

find /home/wowza_analytics_bcup/wowza_analytics/ -mindepth 1 -mtime +7 -delete

Grouping functions (tapply, by, aggregate) and the *apply family

On the side note, here is how the various plyr functions correspond to the base *apply functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)

Base function   Input   Output   plyr function 
---------------------------------------
aggregate        d       d       ddply + colwise 
apply            a       a/l     aaply / alply 
by               d       l       dlply 
lapply           l       l       llply  
mapply           a       a/l     maply / mlply 
replicate        r       a/l     raply / rlply 
sapply           l       a       laply 

One of the goals of plyr is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply() is easily passable to ldply() to produce useful output, etc.

Conceptually, learning plyr is no more difficult than understanding the base *apply functions.

plyr and reshape functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:

Related functions tapply and sweep have no corresponding function in plyr, and remain useful. merge is useful for combining summaries with the original data.

What's the purpose of SQL keyword "AS"?

The AS in this case is an optional keyword defined in ANSI SQL 92 to define a <<correlation name> ,commonly known as alias for a table.

<table reference> ::=
            <table name> [ [ AS ] <correlation name>
                [ <left paren> <derived column list> <right paren> ] ]
          | <derived table> [ AS ] <correlation name>
                [ <left paren> <derived column list> <right paren> ]
          | <joined table>

     <derived table> ::= <table subquery>

     <derived column list> ::= <column name list>

     <column name list> ::=
          <column name> [ { <comma> <column name> }... ]


     Syntax Rules

     1) A <correlation name> immediately contained in a <table refer-
        ence> TR is exposed by TR. A <table name> immediately contained
        in a <table reference> TR is exposed by TR if and only if TR
        does not specify a <correlation name>.

It seems a best practice NOT to use the AS keyword for table aliases as it is not supported by a number of commonly used databases.

Merge 2 DataTables and store in a new one

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.

@Autowired - No qualifying bean of type found for dependency

This may help you:

I have the same exception in my project. After searching while I found that I am missing the @Service annotation to the class where I am implementing the interface which I want to @Autowired.

In your code you can add the @Service annotation to MailManager class.

@Transactional
@Service
public class MailManager extends AbstractManager implements IMailManager {

What is the most efficient way to create HTML elements using jQuery?

One point is that it may be easier to do:

$("<div class=foo id=bar style='color:white;bgcolor:blue;font-size:12pt'></div>")

Then to do all of that with jquery calls.

Automatically run %matplotlib inline in IPython Notebook

In your ipython_config.py file, search for the following lines

# c.InteractiveShellApp.matplotlib = None

and

# c.InteractiveShellApp.pylab = None

and uncomment them. Then, change None to the backend that you're using (I use 'qt4') and save the file. Restart IPython, and matplotlib and pylab should be loaded - you can use the dir() command to verify which modules are in the global namespace.

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

jQuery trigger file input

this worked for me:

JS:

$('#fileinput').trigger('click'); 

HTML:

<div class="hiddenfile">
  <input name="upload" type="file" id="fileinput"/>
</div>

CSS:

.hiddenfile {
 width: 0px;
 height: 0px;
 overflow: hidden;
}

>>>Another one that works Cross-Browser:<<<

The Idea is that you overlay an invisible huge "Browse" button over your custom button. So when the user clicks your custom button, he's actually clicking on the "Browse" button of the native input field.

JS Fiddle: http://jsfiddle.net/5Rh7b/

HTML:

<div id="mybutton">
  <input type="file" id="myfile" name="upload"/>
  Click Me!
</div>

CSS:

div#mybutton {

  /* IMPORTANT STUFF */
  overflow: hidden;
  position: relative;   

  /* SOME STYLING */
  width:  50px;
  height: 28px;
  border: 1px solid green;
  font-weight: bold
  background: red;
}

div#mybutton:hover {
  background: green;
}

input#myfile {
  height: 30px;
  cursor: pointer;
  position: absolute;
  top: 0px;
  right: 0px;
  font-size: 100px;
  z-index: 2;

  opacity: 0.0; /* Standard: FF gt 1.5, Opera, Safari */
  filter: alpha(opacity=0); /* IE lt 8 */
  -ms-filter: "alpha(opacity=0)"; /* IE 8 */
  -khtml-opacity: 0.0; /* Safari 1.x */
  -moz-opacity: 0.0; /* FF lt 1.5, Netscape */
}

JavaScript:

$(document).ready(function() {
    $('#myfile').change(function(evt) {
        alert($(this).val());
    });
});

Retrieving Property name from lambda expression

I found another way you can do it was to have the source and property strongly typed and explicitly infer the input for the lambda. Not sure if that is correct terminology but here is the result.

public static RouteValueDictionary GetInfo<T,P>(this HtmlHelper html, Expression<Func<T, P>> action) where T : class
{
    var expression = (MemberExpression)action.Body;
    string name = expression.Member.Name;

    return GetInfo(html, name);
}

And then call it like so.

GetInfo((User u) => u.UserId);

and voila it works.

slideToggle JQuery right to left

Try this:

$(this).hide("slide", { direction: "left" }, 1000);

$(this).show("slide", { direction: "left" }, 1000);

Where to find the win32api module for Python?

There is a a new option as well: get it via pip! There is a package pypiwin32 with wheels available, so you can just install with: pip install pypiwin32!

Edit: Per comment from @movermeyer, the main project now publishes wheels at pywin32, and so can be installed with pip install pywin32

How to turn off magic quotes on shared hosting?

  1. Does it work if you remove the AddType line? I'm not quite sure why that's relevant to turning magic quotes off.

  2. If PHP isn't running under mod_php, htaccess won't work. Does it work as a CGI?

This is one for your hosting company really.

Change Project Namespace in Visual Studio

First)

  1. Goto menu: Project -> WindowsFormsApplication16 Properties/
  2. write MyName in Assembly name and Default namespace textbox, then save.

Second)

  1. open one old .cs file ( a class or a form)
  2. right click on WindowsFormsApplication16 in front of namespace, goto Refactor -> Rename .
  3. write MyName in New name textbox, in Rename Message Box.
  4. press Ok, then Apply

Convert pyQt UI to python

I'm not sure if PyQt does have a script like this, but after you install PySide there is a script in pythons script directory "uic.py". You can use this script to convert a .ui file to a .py file:

python uic.py input.ui -o output.py -x

How to calculate the intersection of two sets?

Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

All implementation for topViewController here are not fully supporting cases when you have UINavigationController or UITabBarController, for those two you need a bit different handling:

For UITabBarController and UINavigationController you need a different implementation.

Here is code I'm using to get topMostViewController:

protocol TopUIViewController {
    func topUIViewController() -> UIViewController?
}

extension UIWindow : TopUIViewController {
    func topUIViewController() -> UIViewController? {
        if let rootViewController = self.rootViewController {
            return self.recursiveTopUIViewController(from: rootViewController)
        }

        return nil
    }

    private func recursiveTopUIViewController(from: UIViewController?) -> UIViewController? {
        if let topVC = from?.topUIViewController() { return recursiveTopUIViewController(from: topVC) ?? from }
        return from
    }
}

extension UIViewController : TopUIViewController {
    @objc open func topUIViewController() -> UIViewController? {
        return self.presentedViewController
    }
}

extension UINavigationController {
    override open func topUIViewController() -> UIViewController? {
        return self.visibleViewController
    }
}

extension UITabBarController {
    override open func topUIViewController() -> UIViewController? {
        return self.selectedViewController ?? presentedViewController
    }
}

how to append a css class to an element by javascript?

You should be able to set the className property of the element. You could do a += to append it.

How to insert text with single quotation sql server 2005

Escape single quote with an additional single as Kirtan pointed out
And if you are trying to execute a dynamic sql (which is not a good idea in the first place) via sp_executesql then the below code would work for you

sp_executesql N'INSERT INTO SomeTable (SomeColumn) VALUES (''John''''s'')'

How can I check if character in a string is a letter? (Python)

I found a good way to do this with using a function and basic code. This is a code that accepts a string and counts the number of capital letters, lowercase letters and also 'other'. Other is classed as a space, punctuation mark or even Japanese and Chinese characters.

def check(count):

    lowercase = 0
    uppercase = 0
    other = 0

    low = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
    upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'



    for n in count:
        if n in low:
            lowercase += 1
        elif n in upper:
            uppercase += 1
        else:
            other += 1

    print("There are " + str(lowercase) + " lowercase letters.")
    print("There are " + str(uppercase) + " uppercase letters.")
    print("There are " + str(other) + " other elements to this sentence.")

Label encoding across multiple columns in scikit-learn

You can easily do this though,

df.apply(LabelEncoder().fit_transform)

EDIT2:

In scikit-learn 0.20, the recommended way is

OneHotEncoder().fit_transform(df)

as the OneHotEncoder now supports string input. Applying OneHotEncoder only to certain columns is possible with the ColumnTransformer.

EDIT3:

Since this answer is over a year ago, and generated many upvotes (including a bounty), I should probably extend this further.

For inverse_transform and transform, you have to do a little bit of hack.

from collections import defaultdict
d = defaultdict(LabelEncoder)

With this, you now retain all columns LabelEncoder as dictionary.

# Encoding the variable
fit = df.apply(lambda x: d[x.name].fit_transform(x))

# Inverse the encoded
fit.apply(lambda x: d[x.name].inverse_transform(x))

# Using the dictionary to label future data
df.apply(lambda x: d[x.name].transform(x))

MOAR EDIT:

Using Neuraxle's FlattenForEach step, it's possible to do this as well to use the same LabelEncoder on all the flattened data at once:

FlattenForEach(LabelEncoder(), then_unflatten=True).fit_transform(df)

For using separate LabelEncoders depending for your columns of data, or if only some of your columns of data needs to be label-encoded and not others, then using a ColumnTransformer is a solution that allows for more control on your column selection and your LabelEncoder instances.

When and why to 'return false' in JavaScript?

You use return false to prevent something from happening. So if you have a script running on submit then return false will prevent the submit from working.

Export query result to .csv file in SQL Server 2008

If you don't want to use Powershell, this answer is a variation on 8kb's great answer. The only difference is that instead of selecting CSV as the output format, select Tab Delimited. This way if there are commas in your data, it won't skip cells in Excel. Also, if you have Excel's default delimiter set to tabs, you can simply do a copy-all of the SSMS query results (CTRL-A, CTRL-C) and paste into Excel (no need to save as a file and import to Excel):

  • In SSMS Go to Tools > Options > Query Results > SQL Server > Results To Text
  • Change output format on far right to Tab Delimited
  • Click OK

Now you can execute your query, then do a CTRL-A to select all the results, then CTRL-C to copy to clipboard, then switch to Excel 2013 (may work in 2007 too, not sure) and paste -- assuming Excel's default delimiter is set to tab.

Image of SSMS Query Options Screen

What is tempuri.org?

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

tempuri.org is the default namespace URI used by Microsoft development products, like Visual Studio.

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

Best way to get application folder path

If you know to get the root directory:

string rootPath = Path.GetPathRoot(Application.StartupPath)

Pandas read in table without headers

Make sure you specify pass header=None and add usecols=[3,6] for the 4th and 7th columns.

Add leading zeroes/0's to existing Excel values to certain length

Even this will work nicely

REPT(0,2-LEN(F2)&F2

where 2 is total number of digits, for 0 ~ 9 -> it will display 00 to 09 rest nothing will be added.

Javascript reduce() on Object

1:

[{value:5}, {value:10}].reduce((previousValue, currentValue) => { return {value: previousValue.value + currentValue.value}})

>> Object {value: 15}

2:

[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })

>> 15

3:

[{value:5}, {value:10}].reduce(function (previousValue, currentValue) {
      return {value: previousValue.value + currentValue.value};
})

>> Object {value: 15}

How to split a string between letters and digits (or between digits and letters)?

You could try to split on (?<=\D)(?=\d)|(?<=\d)(?=\D), like:

str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

It matches positions between a number and not-a-number (in any order).

  • (?<=\D)(?=\d) - matches a position between a non-digit (\D) and a digit (\d)
  • (?<=\d)(?=\D) - matches a position between a digit and a non-digit.

Calling a javascript function in another js file

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

A function cannot be called unless it is in the same or greater scope then the one trying to call it.

You declare function fn1 in first.js, and then in second you can just have fn1();

1.js:

function fn1 () {
    alert();
}

2.js:

fn1();

index.html :

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

Understanding ibeacon distancing

Distances to the source of iBeacon-formatted advertisement packets are estimated from the signal path attenuation calculated by comparing the measured received signal strength to the claimed transmit power which the transmitter is supposed to encode in the advertising data.

A path loss based scheme like this is only approximate and is subject to variation with things like antenna angles, intervening objects, and presumably a noisy RF environment. In comparison, systems really designed for distance measurement (GPS, Radar, etc) rely on precise measurements of propagation time, in same cases even examining the phase of the signal.

As Jiaru points out, 160 ft is probably beyond the intended range, but that doesn't necessarily mean that a packet will never get through, only that one shouldn't expect it to work at that distance.

event.preventDefault() function not working in IE

preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:

if (typeof Event.prototype.preventDefault === 'undefined') {
    Event.prototype.preventDefault = function (e, callback) {
        this.returnValue = false;
    };
}

This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.

Passing an array as a function parameter in JavaScript

Why don't you pass the entire array and process it as needed inside the function?

var x = [ 'p0', 'p1', 'p2' ]; 
call_me(x);

function call_me(params) {
  for (i=0; i<params.length; i++) {
    alert(params[i])
  }
}

How to set DialogFragment's width and height?

This will work perfectly.

@Override
public void onResume() {
    super.onResume();
    Window window = getDialog().getWindow();
    if(window == null) return;
    WindowManager.LayoutParams params = window.getAttributes();
    params.width = 400;
    params.height = 400;
    window.setAttributes(params);
}

Exposing a port on a live Docker container

I wrote a blog post that explains how to access an unpublished port of a container In different ways depending on the needs:

  • by committing a new image and running a new container,
  • by using socat to avoid restarting the container.

The post also goes through a brief introduction of both how port mapping works, the difference between exposing and publishing a port, and what is socat.

Here’s the link: https://lmcaraig.com/accessing-an-unpublished-port-of-a-running-docker-container

Access Database opens as read only

on my pc I had the same problem and it was because in properties -> security I didn't have the ownership of the file...

Input jQuery get old value before onchange and get value after on change

If you only need a current value and above options don't work, you can use it this way.

$('#input').on('change', () => {
  const current = document.getElementById('input').value;
}

How to use a findBy method with comparative criteria

I like to use such static methods:

$result = $purchases_repository->matching(
    Criteria::create()->where(
        Criteria::expr()->gt('prize', 200)
    )
);

Of course, you can push logic when it is 1 condition, but when you have more conditions it is better to divide it into fragments, configure and pass it to the method:

$expr = Criteria::expr();

$criteria = Criteria::create();
$criteria->where($expr->gt('prize', 200));
$criteria->orderBy(['prize' => Criteria::DESC]);

$result = $purchases_repository->matching($criteria);

Show data on mouseover of circle

A really good way to make a tooltip is described here: Simple D3 tooltip example

You have to append a div

var tooltip = d3.select("body")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    .style("visibility", "hidden")
    .text("a simple tooltip");

Then you can just toggle it using

.on("mouseover", function(){return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top",
    (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});

d3.event.pageX / d3.event.pageY is the current mouse coordinate.

If you want to change the text you can use tooltip.text("my tooltip text");

Working Example

Date Comparison using Java

Date long getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}

How do I revert my changes to a git submodule?

Since Git 2.14 (Q3 2017), you don't have to go into each submodule to do a git reset (as in git submodule foreach git reset --hard)

That is because git reset itself knows now how to recursively go into submodules.

See commit 35b96d1 (21 Apr 2017), and commit f2d4899, commit 823bab0, commit cd279e2 (18 Apr 2017) by Stefan Beller (stefanbeller).
(Merged by Junio C Hamano -- gitster -- in commit 5f074ca, 29 May 2017)

builtin/reset: add --recurse-submodules switch

git-reset is yet another working tree manipulator, which should be taught about submodules.

When a user uses git-reset and requests to recurse into submodules, this will reset the submodules to the object name as recorded in the superproject, detaching the HEADs.

Warning: the difference between:

  • git reset --hard --recurse-submodule and
  • git submodule foreach git reset --hard

is that the former will also reset your main parent repo working tree, as the latter would only reset the submodules working tree.
So use with caution.

AngularJS Directive Restrict A vs E

Element is not supported in IE8 out of the box you have to do some work to make IE8 accept custom tags.

One advantage of using an attribute over an element is that you can apply multiple directives to the same DOM node. This is particularly handy for things like form controls where you can highlight, disable, or add labels etc. with additional attributes without having to wrap the element in a bunch of tags.

Why does Java's hashCode() in String use 31 as a multiplier?

Actually, 37 would work pretty well! z := 37 * x can be computed as y := x + 8 * x; z := x + 4 * y. Both steps correspond to one LEA x86 instructions, so this is extremely fast.

In fact, multiplication with the even-larger prime 73 could be done at the same speed by setting y := x + 8 * x; z := x + 8 * y.

Using 73 or 37 (instead of 31) might be better, because it leads to denser code: The two LEA instructions only take 6 bytes vs. the 7 bytes for move+shift+subtract for the multiplication by 31. One possible caveat is that the 3-argument LEA instructions used here became slower on Intel's Sandy bridge architecture, with an increased latency of 3 cycles.

Moreover, 73 is Sheldon Cooper's favorite number.

plot a circle with pyplot

If you aim to have the "circle" maintain a visual aspect ratio of 1 no matter what the data coordinates are, you could use the scatter() method. http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.scatter

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
r = [100, 80, 60, 40, 20] # in points, not data units
fig, ax = plt.subplots(1, 1)
ax.scatter(x, y, s=r)
fig.show()

Image is a scatter plot. Five circles along the line y=10x have decreasing radii from bottom left to top right. Although the graph is square-shaped, the y-axis has 10 times the range of the x-axis. Even so, the aspect ratio of the circles is 1 on the screen.

Creating temporary files in bash

Is there any advantage in creating a temporary file in a more careful way

The temporary files are usually created in the temporary directory (such as /tmp) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren't unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).


You could use the following approach to create the temporary directory:

TMPDIR=".${0##*/}-$$" && mkdir -v "$TMPDIR"

or temporary file:

TMPFILE=".${0##*/}-$$" && touch "$TMPFILE"

However it is still predictable and not considered safe.

As per man mktemp, we can read:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.

So to be safe, it is recommended to use mktemp command to create unique temporary file or directory (-d).

How to wait until WebBrowser is completely loaded in VB.NET?

Technically, there are two issues with the code posted by BGM:

  1. the adding of the handlers in the WaitForPageLoad method is potentially too late. The navigation is initiated before the handlers are added which means that in very rare cases where the browser already has the page it may complete before the handlers are added in which case you will miss the event and sit forever waiting.

    The solution is to add the handlers before the navigation starts and remove them after the navigation completed

    This means the WaitForPageLoad method needs to be split into two methods. One is called before initiating the navigation. It should set the handlers. The second part does the ReadyState monitoring and cleans up when 'Ready'.

  2. good programming practices is to add a timeout so that a lost (or crashed, or looping) browser doesn't make your code wait forever for the document completed even

How do I find files with a path length greater than 260 characters in Windows?

For paths greater than 260:
you can use:

Get-ChildItem | Where-Object {$_.FullName.Length -gt 260}

Example on 14 chars:
To view the paths lengths:

Get-ChildItem | Select-Object -Property FullName, @{Name="FullNameLength";Expression={($_.FullName.Length)}

Get paths greater than 14:

Get-ChildItem | Where-Object {$_.FullName.Length -gt 14}  

Screenshot:
enter image description here

For filenames greater than 10:

Get-ChildItem | Where-Object {$_.PSChildName.Length -gt 10}

Screenshot:
enter image description here

How to escape single quotes within single quoted strings

Here are my two cents -- in the case if one wants to be sh-portable, not just bash-specific ( the solution is not too efficient, though, as it starts an external program -- sed ):

  • put this in quote.sh ( or just quote ) somewhere on your PATH :
# this works with standard input (stdin)
quote() {
  echo -n "'" ;
  sed 's/\(['"'"']['"'"']*\)/'"'"'"\1"'"'"'/g' ;
  echo -n "'"
}

case "$1" in
 -) quote ;;
 *) echo "usage: cat ... | quote - # single-quotes input for Bourne shell" 2>&1 ;;
esac

An example:

$ echo -n "G'day, mate!" | ./quote.sh -
'G'"'"'day, mate!'

And, of course, that converts back:

$ echo 'G'"'"'day, mate!'
G'day, mate!

Explanation: basically we have to enclose the input with quotes ', and then also replace any single quote within with this micro-monster: '"'"' ( end the opening quote with a pairing ', escape the found single quote by wrapping it with double quotes -- "'", and then finally issue a new opening single quote ', or in pseudo-notation : ' + "'" + ' == '"'"' )

One standard way to do that would be to use sed with the following substitution command:

s/\(['][']*\)/'"\1"'/g 

One small problem, though, is that in order to use that in shell one needs to escape all these single quote characters in the sed expression itself -- what leads to something like

sed 's/\(['"'"']['"'"']*\)/'"'"'"\1"'"'"'/g' 

( and one good way to build this result is to feed the original expression s/\(['][']*\)/'"\1"'/g to Kyle Rose' or George V. Reilly's scripts ).

Finally, it kind of makes sense to expect the input to come from stdin -- since passing it through command-line arguments could be already too much trouble.

( Oh, and may be we want to add a small help message so that the script does not hang when someone just runs it as ./quote.sh --help wondering what it does. )

Update GCC on OSX

in /usr/bin type

sudo ln -s -f g++-4.2 g++

sudo ln -s -f gcc-4.2 gcc

That should do it.

Is there a way to specify which pytest tests to run from a file?

If you have the same method name in two different classes and you just want to run one of them, this works:

pytest tests.py -k 'TestClassName and test_method_name'

Linux / Bash, using ps -o to get process by specific name?

This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:

ps -o pid -C bash

EDIT: Dependening on the sort of output you expect, pgrep would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:

pgrep bash

How to create EditText with rounded corners?

There is an easier way than the one written by CommonsWare. Just create a drawable resource that specifies the way the EditText will be drawn:

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" 
    android:padding="10dp">

    <solid android:color="#FFFFFF" />
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

Then, just reference this drawable in your layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <EditText  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:padding="5dip"
        android:background="@drawable/rounded_edittext" />
</LinearLayout>

You will get something like:

alt text

Edit

Based on Mark's comment, I want to add the way you can create different states for your EditText:

<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext_states.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_pressed="true" 
        android:state_enabled="true"
        android:drawable="@drawable/rounded_focused" />
    <item 
        android:state_focused="true" 
        android:state_enabled="true"
        android:drawable="@drawable/rounded_focused" />
    <item 
        android:state_enabled="true"
        android:drawable="@drawable/rounded_edittext" />
</selector>

These are the states:

<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext_focused.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">

    <solid android:color="#FFFFFF"/>
    <stroke android:width="2dp" android:color="#FF0000" />
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

And... now, the EditText should look like:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <EditText  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello"
        android:background="@drawable/rounded_edittext_states"
        android:padding="5dip" />
</LinearLayout>

How to vertically align elements in a div?

All of them need to be vertically aligned within the div

Aligned how? Tops of the images aligned with the top of the text?

One of the images needs to be absolute positioned within the div.

Absolutely positioned relative to the DIV? Perhaps you could sketch out what you're looking for...?

fd has described the steps for absolute positioning, as well as adjusting the display of the H1 element such that images will appear inline with it. To that, i'll add that you can align the images by use of the vertical-align style:

#header h1 { display: inline; }
#header img { vertical-align: middle; }

...this would put the header and images together, with top edges aligned. Other alignment options exist; see the documentation. You might also find it beneficial to drop the DIV and move the images inside the H1 element - this provides semantic value to the container, and removes the need to adjust the display of the H1:

<h1 id=header">
   <img src=".." ></img>
   testing...
   <img src="..."></img>
</h1>

How do I get the application exit code from a Windows command line?

Testing ErrorLevel works for console applications, but as hinted at by dmihailescu, this won't work if you're trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.

Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt's START /WAIT command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel.

start /wait something.exe
echo %errorlevel%

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

Fast Bitmap Blur For Android SDK

I used this before..

public static Bitmap myblur(Bitmap image, Context context) {
            final float BITMAP_SCALE = 0.4f;
            final float BLUR_RADIUS = 7.5f;
            int width = Math.round(image.getWidth() * BITMAP_SCALE);
            int height = Math.round(image.getHeight() * BITMAP_SCALE);
            Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
            Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
            RenderScript rs = RenderScript.create(context);
            ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
            Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
            Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
            theIntrinsic.setRadius(BLUR_RADIUS);
            theIntrinsic.setInput(tmpIn);
            theIntrinsic.forEach(tmpOut);
            tmpOut.copyTo(outputBitmap);
            return outputBitmap;
        }

Pass element ID to Javascript function

you can use this.

<html>
    <head>
        <title>Demo</title>
        <script>
            function passBtnID(id) {
                alert("You Pressed:  " + id);
            }
        </script>
    </head>
    <body>
        <button id="mybtn1" onclick="passBtnID('mybtn1')">Press me</button><br><br>
        <button id="mybtn2" onclick="passBtnID('mybtn2')">Press me</button>
    </body>
</html>

How to decode viewstate

Here's an online ViewState decoder:

http://ignatu.co.uk/ViewStateDecoder.aspx

Edit: Unfortunatey, the above link is dead - here's another ViewState decoder (from the comments):

http://viewstatedecoder.azurewebsites.net/

Creating a segue programmatically

First of, suppose you have two different views in storyboard, and you want to navigate from one screen to another, so follow this steps:

1). Define all your views with class file and also storyboard id in identity inspector.

2). Make sure you add a navigation controller to the first view. Select it in the Storyboard and then Editor >Embed In > Navigation Controller

3). In your first class, import the "secondClass.h"

#import "ViewController.h
#import "secondController.h"

4). Add this command in the IBAction that has to perform the segue

secondController *next=[self.storyboard instantiateViewControllerWithIdentifier:@"second"];
[self.navigationController pushViewController:next animated:YES];

5). @"second" is secondview controller class, storyboard id.

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

It's not necessary to rewrite everything. I recommend doing this instead:

Post this inside your .m file of your custom cell.

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(0,0,32,32);
}

This should do the trick nicely. :]

Running a single test from unittest.TestCase via the command line

If you organize your test cases, that is, follow the same organization like the actual code and also use relative imports for modules in the same package, you can also use the following command format:

python -m unittest mypkg.tests.test_module.TestClass.test_method

# In your case, this would be:
python -m unittest testMyCase.MyCase.testItIsHot

Python 3 documentation for this: Command-Line Interface

Passing a String by Reference in Java?

For someone who are more curious

class Testt {
    static void Display(String s , String varname){
        System.out.println(varname + " variable data = "+ s + " :: address hashmap =  " + s.hashCode());
    }

    static void changeto(String s , String t){
        System.out.println("entered function");
        Display(s , "s");
        s = t ;
        Display(s,"s");
        System.out.println("exiting function");
    }

    public static void main(String args[]){
        String s =  "hi" ;
        Display(s,"s");
        changeto(s,"bye");
        Display(s,"s");
    }
}

Now by running this above code you can see how address hashcodes change with String variable s . a new object is allocated to variable s in function changeto when s is changed

How to set the Default Page in ASP.NET?

I had done all the above solutions but it did not work.

My default page wasn't an aspx page, it was an html page.

This article solved the problem. https://weblog.west-wind.com/posts/2013/aug/15/iis-default-documents-vs-aspnet-mvc-routes

Basically, in my \App_Start\RouteConfig.cs file, I had to add a line:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("");   // This was the line I had to add here!

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Hope this helps someone, it took me a goodly while to find the answer.

1 = false and 0 = true?

It is common for comparison functions to return 0 on "equals", so that they can also return a negative number for "less than" and a positive number for "greater than". strcmp() and memcmp() work like this.

It is, however, idiomatic for zero to be false and nonzero to be true, because this is how the C flow control and logical boolean operators work. So it might be that the return values chosen for this function are fine, but it is the function's name that is in error (it should really just be called compare() or similar).

Run git pull over all subdirectories

I combined points from several comments and answers:

find . -maxdepth 1 -type d -name .git -execdir git pull \;

How do I set browser width and height in Selenium WebDriver?

Here is how I do it in Python with Selenium 2.48.0:

from selenium.webdriver import Firefox
driver = Firefox()
driver.set_window_position(0, 0)
driver.set_window_size(1024, 768)

How to set image to UIImage

may be:

UIImage *img = [[UIImage alloc] init];

and when you want to change the image:

img = [UIImage imageNamed:@"nameOfPng.png"];

but the object wasn't in the same place in the memory, but if you use the pointer, the same pointer will be point to the last image loaded.

wget/curl large file from google drive

ggID='put_googleID_here'  
ggURL='https://drive.google.com/uc?export=download'  
filename="$(curl -sc /tmp/gcokie "${ggURL}&id=${ggID}" | grep -o '="uc-name.*</span>' | sed 's/.*">//;s/<.a> .*//')"  
getcode="$(awk '/_warning_/ {print $NF}' /tmp/gcokie)"  
curl -Lb /tmp/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" -o "${filename}"  

How does it work?
Get cookie file and html code with curl.
Pipe html to grep and sed and search for file name.
Get confirm code from cookie file with awk.
Finally download file with cookie enabled, confirm code and filename.

curl -Lb /tmp/gcokie "https://drive.google.com/uc?export=download&confirm=Uq6r&id=0B5IRsLTwEO6CVXFURmpQZ1Jxc0U" -o "SomeBigFile.zip"

If you dont need filename variable curl can guess it
-L Follow redirects
-O Remote-name
-J Remote-header-name

curl -sc /tmp/gcokie "${ggURL}&id=${ggID}" >/dev/null  
getcode="$(awk '/_warning_/ {print $NF}' /tmp/gcokie)"  
curl -LOJb /tmp/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" 

To extract google file ID from URL you can use:

echo "gURL" | egrep -o '(\w|-){26,}'  
# match more than 26 word characters  

OR

echo "gURL" | sed 's/[^A-Za-z0-9_-]/\n/g' | sed -rn '/.{26}/p'  
# replace non-word characters with new line,   
# print only line with more than 26 word characters 

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

How to change Elasticsearch max memory size

If you installed ES using the RPM/DEB packages as provided (as you seem to have), you can adjust this by editing the init script (/etc/init.d/elasticsearch on RHEL/CentOS). If you have a look in the file you'll see a block with the following:

export ES_HEAP_SIZE
export ES_HEAP_NEWSIZE
export ES_DIRECT_SIZE
export ES_JAVA_OPTS
export JAVA_HOME

To adjust the size, simply change the ES_HEAP_SIZE line to the following:

export ES_HEAP_SIZE=xM/xG

(where x is the number of MB/GB of RAM that you would like to allocate)

Example:

export ES_HEAP_SIZE=1G

Would allocate 1GB.

Once you have edited the script, save and exit, then restart the service. You can check if it has been correctly set by running the following:

ps aux | grep elasticsearch

And checking for the -Xms and -Xmx flags in the java process that returns:

/usr/bin/java -Xms1G -Xmx1G

Hope this helps :)

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

If you want to pass a pointer-to-int into your function,

Declaration of function (if you need it):

void Fun(int *ptr);

Definition of function:

void Fun(int *ptr) {
    int *other_pointer = ptr;  // other_pointer points to the same thing as ptr
    *other_ptr = 3;            // manipulate the thing they both point to
}

Use of function:

int main() {
    int x = 2;
    printf("%d\n", x);
    Fun(&x);
    printf("%d\n", x);
}

Note as a general rule, that variables called Ptr or Pointer should never have type int, which is what you have then in your code. A pointer-to-int has type int *.

If I have a second pointer (int *oof), then:

bar = oof means: bar points to the oof pointer

It means "make bar point to the same thing oof points to".

bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself

That doesn't mean anything, it's invalid. bar is a pointer *oof is an int. You can't assign one to the other.

*bar = *oof means: change the value that bar points to to the value that oof points to

Yes.

&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to

Nope, that's invalid again. &bar is a pointer to the bar variable, but it is what's called an "rvalue", or "temporary", and it cannot be assigned to. It's like the result of an arithmetic calculation. You can't write x + 1 = 5.

It might help you to think of pointers as addresses. bar = oof means "make bar, which is an address, equal to oof, which is also an address". bar = &foo means "make bar, which is an address, equal to the address of foo". If bar = *oof meant anything, it would mean "make bar, which is an address, equal to *oof, which is an int". You can't.

Then, & is the address-of operator. It means "the address of the operand", so &foo is the address of foo (i.e, a pointer to foo). * is the dereference operator. It means "the thing at the address given by the operand". So having done bar = &foo, *bar is foo.

Downloading all maven dependencies to a directory NOT in repository?

Based on @Raghuram answer, I find a tutorial on Copying project dependencies, Just:

  1. Open your project pom.xml file and find this:

    <project>
      [...]
      <build>
        <plugins>
          ...
        </plugins>
      </build>
      [...]
    </project>
    
  2. Than replace the <plugins> ... </plugins> with:

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
              <overWriteReleases>false</overWriteReleases>
              <overWriteSnapshots>false</overWriteSnapshots>
              <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
    
  3. And call maven within the command line mvn dependency:copy-dependencies

After it finishes, it will create the folder target/dependency within all the jar's dependencies on the current directory where the pom.xml lives.

What exactly is the function of Application.CutCopyMode property in Excel

Normally, When you copy a cell you will find the below statement written down in the status bar (in the bottom of your sheet)

"Select destination and Press Enter or Choose Paste"

Then you press whether Enter or choose paste to paste the value of the cell.

If you didn't press Esc afterwards you will be able to paste the value of the cell several times

Application.CutCopyMode = False does the same like the Esc button, if you removed it from your code you will find that you are able to paste the cell value several times again.

And if you closed the Excel without pressing Esc you will get the warning 'There is a large amount of information on the Clipboard....'

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!

In the child pom, use something like this:

<modelVersion>4.0.0</modelVersion>

<parent>
  <groupId>org.felipe</groupId>
  <artifactId>tutorial_maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <relativePath>../pom.xml</relativePath>
</parent>

<artifactId>tutorial_maven_jar</artifactId>

Using properties like ${project.groupId} won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.

Declaring and initializing a string array in VB.NET

Public Function TestError() As String()
     Return {"foo", "bar"}
End Function

Works fine for me and should work for you, but you may need allow using implicit declarations in your project. I believe this is turning off Options strict in the Compile section of the program settings.

Since you are using VS 2008 (VB.NET 9.0) you have to declare create the new instance

New String() {"foo", "Bar"}

Regex to validate password strength

Another solution:

import re

passwordRegex = re.compile(r'''(
    ^(?=.*[A-Z].*[A-Z])                # at least two capital letters
    (?=.*[!@#$&*])                     # at least one of these special c-er
    (?=.*[0-9].*[0-9])                 # at least two numeric digits
    (?=.*[a-z].*[a-z].*[a-z])          # at least three lower case letters
    .{8,}                              # at least 8 total digits
    $
    )''', re.VERBOSE)

def userInputPasswordCheck():
    print('Enter a potential password:')
    while True:
        m = input()
        mo = passwordRegex.search(m) 
        if (not mo):
           print('''
Your password should have at least one special charachter,
two digits, two uppercase and three lowercase charachter. Length: 8+ ch-ers.

Enter another password:''')          
        else:
           print('Password is strong')
           return
userInputPasswordCheck()

What is the difference between state and props in React?

Some differences between “state” and “props” in react.

React controls and renders DOM based on state. There are two types of component states: props is the state that transfers between components, and state is internal state of components. Props is used for data transfer from the parent component to the child component. The components also have their own state inside: state which can only be modified inside the component.

Generally the state of certain component could be the props of the child component ,props will be passed to children which is stated inside the rendering method of the parent component

Add Favicon with React and Webpack

Browsers look for your favicon in /favicon.ico, so that's where it needs to be. You can double check if you've positioned it in the correct place by navigating to [address:port]/favicon.ico and seeing if your icon appears.

In dev mode, you are using historyApiFallback, so will need to configure webpack to explicitly return your icon for that route:

historyApiFallback: {
    index: '[path/to/index]',
    rewrites: [
        // shows favicon
        { from: /favicon.ico/, to: '[path/to/favicon]' }
    ]
}

In your server.js file, try explicitly rewriting the url:

app.configure(function() {
    app.use('/favicon.ico', express.static(__dirname + '[route/to/favicon]'));
});

(or however your setup prefers to rewrite urls)

I suggest generating a true .ico file rather than using a .png, since I've found that to be more reliable across browsers.

pop/remove items out of a python tuple

Maybe you want dictionaries?

d = dict( (i,value) for i,value in enumerate(tple))
while d:
    bla bla bla
    del b[x]

Dynamically access object property using variable

UPDATED

I have take comments below into consideration and agreed. Eval is to be avoided.

Accessing root properties in object is easily achieved with obj[variable], but getting nested complicates thing. Not to write already written code I suggest to use lodash.get.

Example

// Accessing root property
var rootProp = 'rootPropert';
_.get(object, rootProp, defaultValue);

// Accessing nested property
var listOfNestedProperties = [var1, var2];
_.get(object, listOfNestedProperties);

Lodash get can be used on different ways, here is link to the documentation lodash.get

Does "display:none" prevent an image from loading?

It seems browsers still download images even if the latter are directly or indirectly hidden with display: none property.

The only standard way to prevent this from happening I found, was using loading attribute of the img tag:

<img src="https://cdn.test/img.jpg" loading="lazy">

All latest browsers support it except Safari and Firefox Android.

MDN img element specification.

How to compress a String in Java?

If you know that your strings are mostly ASCII you could convert them to UTF-8.

byte[] bytes = string.getBytes("UTF-8");

This may reduce the memory size by about 50%. However, you will get a byte array out and not a string. If you are writing it to a file though, that should not be a problem.

To convert back to a String:

private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
...
String s = new String(bytes, UTF8_CHARSET);

concatenate char array in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *name = "hello";

int main(void) {
  char *ext = ".txt";
  int len   = strlen(name) + strlen(ext) + 1;
  char *n2  = malloc(len);
  char *n2a = malloc(len);

  if (n2 == NULL || n2a == NULL)
    abort();

  strlcpy(n2, name, len);
  strlcat(n2, ext, len);
  printf("%s\n", n2);

  /* or for conforming C99 ...  */
  strncpy(n2a, name, len);
  strncat(n2a, ext, len - strlen(n2a));
  printf("%s\n", n2a);

  return 0; // this exits, otherwise free n2 && n2a
}

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

how do I use an enum value on a switch statement in C++

You can use an enumerated value just like an integer:

myChoice c;

...

switch( c ) {
case EASY:
    DoStuff();
    break;
case MEDIUM:
    ...
}

When to use Comparable and Comparator

Comparator does everything that comparable does, plus more.

| | Comparable | Comparator ._______________________________________________________________________________ Is used to allow Collections.sort to work | yes | yes Can compare multiple fields | yes | yes Lives inside the class you’re comparing and serves | | as a “default” way to compare | yes | yes Can live outside the class you’re comparing | no | yes Can have multiple instances with different method names | no | yes Input arguments can be a list of | just Object| Any type Can use enums | no | yes

I found the best approach to use comparators as anonymous classes as follows:

private static void sortAccountsByPriority(List<AccountRecord> accounts) {
    Collections.sort(accounts, new Comparator<AccountRecord>() {

        @Override
        public int compare(AccountRecord a1, AccountRecord a2) {
            return a1.getRank().compareTo(a2.getRank());
        }
    });
}

You can create multiple versions of such methods right inside the class you’re planning to sort. So you can have:

  • sortAccountsByPriority
  • sortAccountsByType
  • sortAccountsByPriorityAndType

    etc...

Now, you can use these sort methods anywhere and get code reuse. This gives me everything a comparable would, plus more ... so I don’t see any reason to use comparable at all.

canvas.toDataURL() SecurityError

Just use the crossOrigin attribute and pass 'anonymous' as the second parameter

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

Combining node.js and Python

I'd consider also Apache Thrift http://thrift.apache.org/

It can bridge between several programming languages, is highly efficient and has support for async or sync calls. See full features here http://thrift.apache.org/docs/features/

The multi language can be useful for future plans, for example if you later want to do part of the computational task in C++ it's very easy to do add it to the mix using Thrift.

Git Stash vs Shelve in IntelliJ IDEA

Shelf is a JetBrains feature while Stash is a Git feature for same work. You can switch to different branch without commit and loss of work using either of features. My personal experience is to use Shelf.

How to change the Eclipse default workspace?

If you want to create a new workspace - simply enter a new path in the textfield at the "select workspace" dialog. Eclipse will create a new workspace at that location and switch to it.

Angular 2: How to style host element of the component?

There was a bug, but it was fixed in the meantime. :host { } works fine now.

Also supported are

  • :host(selector) { ... } for selector to match attributes, classes, ... on the host element
  • :host-context(selector) { ... } for selector to match elements, classes, ...on parent components

  • selector /deep/ selector (alias selector >>> selector doesn't work with SASS) for styles to match across element boundaries

    • UPDATE: SASS is deprecating /deep/.
      Angular (TS and Dart) added ::ng-deep as a replacement that's also compatible with SASS.

    • UPDATE2: ::slotted ::slotted is now supported by all new browsers and can be used with `ViewEncapsulation.ShadowDom
      https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

See also Load external css style into Angular 2 Component

/deep/ and >>> are not affected by the same selector combinators that in Chrome which are deprecated.
Angular emulates (rewrites) them, and therefore doesn't depend on browsers supporting them.

This is also why /deep/ and >>> don't work with ViewEncapsulation.Native which enables native shadow DOM and depends on browser support.

Difference between Console.Read() and Console.ReadLine()?

Console.Read()

=> reads only one character from the standard input

Console.ReadLine()

=> reads all characters in the line from the standard input

How do I tell Gradle to use specific JDK version?

As seen in Gradle (Eclipse plugin)

http://www.gradle.org/get-started

Gradle uses whichever JDK it finds in your path (to check, use java -version). Alternatively, you can set the JAVA_HOME environment variable to point to the install directory of the desired JDK.


If you are using this Eclipse plugin or Enide Studio 2014, alternative JAVA_HOME to use (set in Preferences) will be in version 0.15, see http://www.nodeclipse.org/history

Auto logout with Angularjs based on idle user

View Demo which is using angularjs and see your's browser log

<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>

<body>
</body>

<script>

var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {    
    console.log('starting run');

    // Timeout timer value
    var TimeOutTimerValue = 5000;

    // Start a timeout
    var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    var bodyElement = angular.element($document);

    /// Keyboard Events
    bodyElement.bind('keydown', function (e) { TimeOut_Resetter(e) });  
    bodyElement.bind('keyup', function (e) { TimeOut_Resetter(e) });    

    /// Mouse Events    
    bodyElement.bind('click', function (e) { TimeOut_Resetter(e) });
    bodyElement.bind('mousemove', function (e) { TimeOut_Resetter(e) });    
    bodyElement.bind('DOMMouseScroll', function (e) { TimeOut_Resetter(e) });
    bodyElement.bind('mousewheel', function (e) { TimeOut_Resetter(e) });   
    bodyElement.bind('mousedown', function (e) { TimeOut_Resetter(e) });        

    /// Touch Events
    bodyElement.bind('touchstart', function (e) { TimeOut_Resetter(e) });       
    bodyElement.bind('touchmove', function (e) { TimeOut_Resetter(e) });        

    /// Common Events
    bodyElement.bind('scroll', function (e) { TimeOut_Resetter(e) });       
    bodyElement.bind('focus', function (e) { TimeOut_Resetter(e) });    

    function LogoutByTimer()
    {
        console.log('Logout');

        ///////////////////////////////////////////////////
        /// redirect to another page(eg. Login.html) here
        ///////////////////////////////////////////////////
    }

    function TimeOut_Resetter(e)
    {
        console.log('' + e);

        /// Stop the pending timeout
        $timeout.cancel(TimeOut_Thread);

        /// Reset the timeout
        TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    }

})
</script>

</html>

Below code is pure javascript version

<html>
    <head>
        <script type="text/javascript">         
            function logout(){
                console.log('Logout');
            }

            function onInactive(millisecond, callback){
                var wait = setTimeout(callback, millisecond);               
                document.onmousemove = 
                document.mousedown = 
                document.mouseup = 
                document.onkeydown = 
                document.onkeyup = 
                document.focus = function(){
                    clearTimeout(wait);
                    wait = setTimeout(callback, millisecond);                       
                };
            }           
        </script>
    </head> 
    <body onload="onInactive(5000, logout);"></body>
</html>

UPDATE

I updated my solution as @Tom suggestion.

<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>

<body>
</body>

<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {    
    console.log('starting run');

    // Timeout timer value
    var TimeOutTimerValue = 5000;

    // Start a timeout
    var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    var bodyElement = angular.element($document);

    angular.forEach(['keydown', 'keyup', 'click', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'scroll', 'focus'], 
    function(EventName) {
         bodyElement.bind(EventName, function (e) { TimeOut_Resetter(e) });  
    });

    function LogoutByTimer(){
        console.log('Logout');
        ///////////////////////////////////////////////////
        /// redirect to another page(eg. Login.html) here
        ///////////////////////////////////////////////////
    }

    function TimeOut_Resetter(e){
        console.log(' ' + e);

        /// Stop the pending timeout
        $timeout.cancel(TimeOut_Thread);

        /// Reset the timeout
        TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    }

})
</script>
</html>

Click here to see at Plunker for updated version

Cannot open include file 'afxres.h' in VC2010 Express

Even I too faced similar issue,

fatal error RC1015: cannot open include file 'afxres.h'. from this code

Replacing afxres.h with Winresrc.h and declaring IDC_STATIC as -1 worked for me. (Using visual studio Premium 2012)

//#include "afxres.h"
#include "WinResrc.h"
#define IDC_STATIC  -1

Github: error cloning my private repository

I found a good solution for adding/updating the CA certificates on RHEL/CentOS 6 which is the root cause reported issue.

Since they become outdated distros, the cacert authorities in that system has not been updated until executing the command sudo yum update.

Didn't realize the issue until the GIT_CURL_VERBOSE mode shows the cacert path issue.

Java: How to set Precision for double value?

public static String setPrecision(String number, int decimal) {
    double nbr = Double.valueOf(number);
    int integer_Part = (int) nbr;
    double float_Part = nbr - integer_Part;
    int floating_point = (int) (Math.pow(10, decimal) * float_Part);
    String final_nbr = String.valueOf(integer_Part) + "." + String.valueOf(floating_point);
    return final_nbr;
}

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

Other than using the Navigator/Proj Explorer and choosing files and doing 'Compare With'->'Each other'... I prefer opening both files in Eclipse and using 'Compare With'->'Opened Editor'->(pick the opened tab)... You can get this feature via the AnyEdit eclipse plugin located here (you can use Install Software via Eclipse->Help->Install New Software screen): http://andrei.gmxhome.de/eclipse/

React Native Responsive Font Size

A slightly different approach worked for me :-

const normalize = (size: number): number => {
  const scale = screenWidth / 320;
  const newSize = size * scale;
  let calculatedSize = Math.round(PixelRatio.roundToNearestPixel(newSize))

  if (PixelRatio.get() < 3)
    return calculatedSize - 0.5
  return calculatedSize
};

Do refer Pixel Ratio as this allows you to better set up the function based on the device density.

nvarchar(max) still being truncated

Your first problem is a limitation of the PRINT statement. I'm not sure why sp_executesql is failing. It should support pretty much any length of input.

Perhaps the reason the query is malformed is something other than truncation.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Take a look at DATEDIFF, this should be what you're looking for. It takes the two dates you're comparing, and the date unit you want the difference in (days, months, seconds...)

Show a number to two decimal places

round_to_2dp is a user-defined function, and nothing can be done unless you posted the declaration of that function.

However, my guess is doing this: number_format($number, 2);

How to set a Timer in Java?

[Android] if someone looking to implement timer on android using java.

you need use UI thread like this to perform operations.

Timer timer = new Timer();
timer.schedule(new TimerTask() {
           @Override
            public void run() {
                ActivityName.this.runOnUiThread(new Runnable(){
                    @Override
                      public void run() {
                       // do something
                      }        
                });
            }
        }, 2000));

VHDL - How should I create a clock in a testbench?

How to use a clock and do assertions

This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.

The key idea is that the process blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.

library ieee;
use ieee.std_logic_1164.all;

entity counter_tb is
end counter_tb;

architecture behav of counter_tb is
    constant width : natural := 2;
    constant clk_period : time := 1 ns;

    signal clk : std_logic := '0';
    signal data : std_logic_vector(width-1 downto 0);
    signal count : std_logic_vector(width-1 downto 0);

    type io_t is record
        load : std_logic;
        data : std_logic_vector(width-1 downto 0);
        count : std_logic_vector(width-1 downto 0);
    end record;
    type ios_t is array (natural range <>) of io_t;
    constant ios : ios_t := (
        ('1', "00", "00"),
        ('0', "UU", "01"),
        ('0', "UU", "10"),
        ('0', "UU", "11"),

        ('1', "10", "10"),
        ('0', "UU", "11"),
        ('0', "UU", "00"),
        ('0', "UU", "01")
    );
begin
    counter_0: entity work.counter port map (clk, load, data, count);

    process
    begin
        for i in ios'range loop
            load <= ios(i).load;
            data <= ios(i).data;
            wait until falling_edge(clk);
            assert count = ios(i).count;
        end loop;
        wait;
    end process;

    process
    begin
        for i in 1 to 2 * ios'length loop
            wait for clk_period / 2;
            clk <= not clk;
        end loop;
        wait;
    end process;
end behav;

The counter would look like this:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned

entity counter is
    generic (
        width : in natural := 2
    );
    port (
        clk, load : in std_logic;
        data : in std_logic_vector(width-1 downto 0);
        count : out std_logic_vector(width-1 downto 0)
    );
end entity counter;

architecture rtl of counter is
    signal cnt : unsigned(width-1 downto 0);
begin
    process(clk) is
    begin
        if rising_edge(clk) then
            if load = '1' then
                cnt <= unsigned(data);
            else
                cnt <= cnt + 1;
            end if;
        end if;
    end process;
    count <= std_logic_vector(cnt);
end architecture rtl;

Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches

Removing a Fragment from the back stack

you show fragment in a container (with id= fragmentcontainer) so you remove fragment with:

 Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);
            fragmentTransaction.remove(fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

Jquery mouseenter() vs mouseover()

This example demonstrates the difference between the mousemove, mouseenter and mouseover events:

https://jsfiddle.net/z8g613yd/

HTML:

<div onmousemove="myMoveFunction()">
    <p>onmousemove: <br> <span id="demo">Mouse over me!</span></p>
</div>

<div onmouseenter="myEnterFunction()">
    <p>onmouseenter: <br> <span id="demo2">Mouse over me!</span></p>
</div>

<div onmouseover="myOverFunction()">
    <p>onmouseover: <br> <span id="demo3">Mouse over me!</span></p>
</div>

CSS:

div {
    width: 200px;
    height: 100px;
    border: 1px solid black;
    margin: 10px;
    float: left;
    padding: 30px;
    text-align: center;
    background-color: lightgray;
}

p {
    background-color: white;
    height: 50px;
}

p span {
    background-color: #86fcd4;
    padding: 0 20px;
}

JS:

var x = 0;
var y = 0;
var z = 0;

function myMoveFunction() {
    document.getElementById("demo").innerHTML = z += 1;
}

function myEnterFunction() {
    document.getElementById("demo2").innerHTML = x += 1;
}

function myOverFunction() {
    document.getElementById("demo3").innerHTML = y += 1;
}
  • onmousemove : occurs every time the mouse pointer is moved over the div element.
  • onmouseenter : only occurs when the mouse pointer enters the div element.
  • onmouseover : occurs when the mouse pointer enters the div element, and its child elements (p and span).

Redirecting to previous page after login? PHP

Since the login page is a separate page, I am assuming that you want to redirect to the page that the user reached the login page from.

$_SERVER['REQUEST_URI'] will simply hold the current page. What you want to do is use $_SERVER['HTTP_REFERER']

So save the HTTP_REFERER in a hidden element on your form <input type="hidden" name="referer" value="<?= $_SERVER['HTTP_REFERER'] ?>" /> but keep in mind that in the PHP that processes the form you will need some logic that redirects back to the login page if login fails but also to check that the referer is actually your website, if it isn't, then redirect back to the homepage.

Error: Uncaught SyntaxError: Unexpected token <

I too got this error, when developing a Backbone application using HTML5 push state in conjunction with an .htaccess which redirects any unknown files to index.html.

It turns out that when visiting a URL such as /something/5, my /index.html was effectively being served at /something/index.html (thanks to my .htaccess). This had the effect of breaking all the relative URLs to my JavaScript files (from inside the index.html ), which meant that they should have 404'd on me.

However, again due to my htaccess, instead of 404'ing when attempting to retrieve the JS files, they instead returned my index.html. Thus the browser was given an index.html for every JavaScript file it tried to pull in, and when it evaluated the HTML as if it were JavaScript, it returned a JS error due to the leading < (from my tag in index.html).

The fix in my case (as I was serving the site from inside a subdirectory) was to add a base tag in my html head.

<base href="/my-app/">

How to access your website through LAN in ASP.NET

If you use IIS Express via Visual Studio instead of the builtin ASP.net host, you can achieve this.

Binding IIS Express to an IP Address

Django Reverse with arguments '()' and keyword arguments '{}' not found

Resolve is also more straightforward

from django.urls import resolve

resolve('edit_project', project_id=4)

Documentation on this shortcut

Including a .js file within a .js file

There is no straight forward way of doing this.

What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).

Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript

My favorite is(not applicable always):

<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");

Google's closure also provides similar functionality.

c++ integer->std::string conversion. Simple function?

Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).

How to store a large (10 digits) integer?

You can store this in a long. A long can store a value from -9223372036854775808 to 9223372036854775807.

how to hide keyboard after typing in EditText in android?

You can see marked answer on top. But i used getDialog().getCurrentFocus() and working well. I post this answer cause i cant type "this" in my oncreatedialog.

So this is my answer. If you tried marked answer and not worked , you can simply try this:

InputMethodManager inputManager = (InputMethodManager) getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getDialog().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

How to close a JavaFX application on window close?

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        Platform.exit();
        System.exit(0);
    }
});

force line break in html table cell

I think what you're trying to do is wrap loooooooooooooong words or URLs so they don't push the size of the table out. (I've just been trying to do the same thing!)

You can do this easily with a DIV by giving it the style word-wrap: break-word (and you may need to set its width, too).

div {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
    width: 100%;
}

However, for tables, you must either wrap the content in a DIV (or other block tag) or apply: table-layout: fixed. This means the columns widths are no longer fluid, but are defined based on the widths of the columns in the first row only (or via specified widths). Read more here.

Sample code:

table {
    table-layout: fixed;
    width: 100%;
}

table td {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
}

Hope that helps somebody.

Run Python script at startup in Ubuntu

In similar situations, I've done well by putting something like the following into /etc/rc.local:

cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local  # check that rc.local ran

This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.

How to remove word wrap from textarea?

I found a way to make a textarea with all this working at the same time:

  • With horizontal scrollbar
  • Supporting multiline text
  • Text not wrapping

It works well on:

  • Chrome 15.0.874.120
  • Firefox 7.0.1
  • Opera 11.52 (1100)
  • Safari 5.1 (7534.50)
  • IE 8.0.6001.18702

Let me explain how i get to that: I was using Chrome inspector integrated tool and I saw values on CSS styles, so I try these values, instead of normal ones... trial & errors till I got it reduced to minimum and here it is for anyone that wants it.

In the CSS section I used just this for Chrome, Firefox, Opera and Safari:

textarea {
  white-space:nowrap;
  overflow:scroll;
}

In the CSS section I used just this for IE:

textarea {
  overflow:scroll;
}

It was a bit tricky, but there is the CSS.

An (x)HTML tag like this:

<textarea id="myTextarea" rows="10" cols="15"></textarea>

And at the end of the <head> section a JavaScript like this:

 window.onload=function(){
   document.getElementById("myTextarea").wrap='off';
 }

The JavaScript is for making the W3C validator passing XHTML 1.1 Strict, since the wrap attribute is not official and thus cannot be an (x)HTML tag directly, but most browsers handle it, so after loading the page it sets that attribute.

Hope this can be tested on more browsers and versions and help someone to improve it and makes it fully cross-browser for all versions.

Checking for empty or null List<string>

Try and use:

if(myList.Any())
{

}

Note: this assmumes myList is not null.

What key shortcuts are to comment and uncomment code?

I went to menu: ToolsOptions.

EnvironmentKeyboard.

Show command containing and searched: comment

I changed Edit.CommentSelection and assigned Ctrl+/ for commenting.

And I left Ctrl+K then U for the Edit.UncommentSelection.

These could be tweaked to the user's preference as to what key they would prefer for commenting/uncommenting.

What does '?' do in C++?

This is a ternary operator, it's basically an inline if statement

x ? y : z

works like

if(x) y else z

except, instead of statements you have expressions; so you can use it in the middle of a more complex statement.

It's useful for writing succinct code, but can be overused to create hard to maintain code.

How to find minimum value from vector?

template <class ForwardIterator>
ForwardIterator min_element ( ForwardIterator first, ForwardIterator last )
{
    ForwardIterator lowest = first;
    if (first == last) return last;
    while (++first != last)
    if (*first < *lowest) 
        lowest = first;
    return lowest;
}

Calling dynamic function with dynamic number of parameters

Your code only works for global functions, ie. members of the window object. To use it with arbitrary functions, pass the function itself instead of its name as a string:

function dispatch(fn, args) {
    fn = (typeof fn == "function") ? fn : window[fn];  // Allow fn to be a function object or the name of a global function
    return fn.apply(this, args || []);  // args is optional, use an empty array by default
}

function f1() {}

function f2() {
    var f = function() {};
    dispatch(f, [1, 2, 3]);
}

dispatch(f1, ["foobar"]);
dispatch("f1", ["foobar"]);

f2();  // calls inner-function "f" in "f2"
dispatch("f", [1, 2, 3]);  // doesn't work since "f" is local in "f2"

How to initialize log4j properly?

You can set up the log level by using setLevel().

The levels are useful to easily set the kind of informations you want the program to display.

For example:

Logger.getRootLogger().setLevel(Level.WARN); //will not show debug messages

The set of possible levels are:

TRACE,

DEBUG,

INFO,

WARN,

ERROR and

FATAL

According to Logging Services manual

new Date() is working in Chrome but not Firefox

You can't instantiate a date object any way you want. It has to be in a specific way. Here are some valid examples:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

or

d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)

Chrome must just be more flexible.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

From apsillers comment:

the EMCAScript specification requires exactly one date format (i.e., YYYY-MM-DDTHH:mm:ss.sssZ) but custom date formats may be freely supported by an implementation: "If the String does not conform to that [ECMAScript-defined] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats." Chrome and FF simply have different "implementation-specific date formats."

Cannot resolve symbol 'AppCompatActivity'

I updated my Gradle 2.3.3 to 4.4 and got an error on AppCompatActivity and also Cardview. I tried with clean project and rebuild project. It won't work, then I go to Project Folder -> .idea -> create backup of libraries folder and remove it -> then Rebuild Project that solved my issue.

Android Activity as a dialog

If you need Appcompat Version

style.xml

    <!-- Base application theme. -->
    <style name="AppDialogTheme" parent="Theme.AppCompat.Light.Dialog">
        <!-- Customize your theme here. -->
        <item name="windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
    </style>

yourmanifest.xml

    <activity
          android:name=".MyActivity"
          android:label="@string/title"
          android:theme="@style/AppDialogTheme">
    </activity>

Stack smashing detected

Minimal reproduction example with disassembly analysis

main.c

void myfunc(char *const src, int len) {
    int i;
    for (i = 0; i < len; ++i) {
        src[i] = 42;
    }
}

int main(void) {
    char arr[] = {'a', 'b', 'c', 'd'};
    int len = sizeof(arr);
    myfunc(arr, len + 1);
    return 0;
}

GitHub upstream.

Compile and run:

gcc -fstack-protector-all -g -O0 -std=c99 main.c
ulimit -c unlimited && rm -f core
./a.out

fails as desired:

*** stack smashing detected ***: terminated
Aborted (core dumped)

Tested on Ubuntu 20.04, GCC 10.2.0.

On Ubuntu 16.04, GCC 6.4.0, I could reproduce with -fstack-protector instead of -fstack-protector-all, but it stopped blowing up when I tested on GCC 10.2.0 as per Geng Jiawen's comment. man gcc clarifies that as suggested by the option name, the -all version adds checks more aggressively, and therefore presumably incurs a larger performance loss:

-fstack-protector

Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes functions that call "alloca", and functions with buffers larger than or equal to 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits. Only variables that are actually allocated on the stack are considered, optimized away variables or variables allocated in registers don't count.

-fstack-protector-all

Like -fstack-protector except that all functions are protected.

Disassembly

Now we look at the disassembly:

objdump -D a.out

which contains:

int main (void){
  400579:       55                      push   %rbp
  40057a:       48 89 e5                mov    %rsp,%rbp

  # Allocate 0x10 of stack space.
  40057d:       48 83 ec 10             sub    $0x10,%rsp

  # Put the 8 byte canary from %fs:0x28 to -0x8(%rbp),
  # which is right at the bottom of the stack.
  400581:       64 48 8b 04 25 28 00    mov    %fs:0x28,%rax
  400588:       00 00 
  40058a:       48 89 45 f8             mov    %rax,-0x8(%rbp)

  40058e:       31 c0                   xor    %eax,%eax
    char arr[] = {'a', 'b', 'c', 'd'};
  400590:       c6 45 f4 61             movb   $0x61,-0xc(%rbp)
  400594:       c6 45 f5 62             movb   $0x62,-0xb(%rbp)
  400598:       c6 45 f6 63             movb   $0x63,-0xa(%rbp)
  40059c:       c6 45 f7 64             movb   $0x64,-0x9(%rbp)
    int len = sizeof(arr);
  4005a0:       c7 45 f0 04 00 00 00    movl   $0x4,-0x10(%rbp)
    myfunc(arr, len + 1);
  4005a7:       8b 45 f0                mov    -0x10(%rbp),%eax
  4005aa:       8d 50 01                lea    0x1(%rax),%edx
  4005ad:       48 8d 45 f4             lea    -0xc(%rbp),%rax
  4005b1:       89 d6                   mov    %edx,%esi
  4005b3:       48 89 c7                mov    %rax,%rdi
  4005b6:       e8 8b ff ff ff          callq  400546 <myfunc>
    return 0;
  4005bb:       b8 00 00 00 00          mov    $0x0,%eax
}
  # Check that the canary at -0x8(%rbp) hasn't changed after calling myfunc.
  # If it has, jump to the failure point __stack_chk_fail.
  4005c0:       48 8b 4d f8             mov    -0x8(%rbp),%rcx
  4005c4:       64 48 33 0c 25 28 00    xor    %fs:0x28,%rcx
  4005cb:       00 00 
  4005cd:       74 05                   je     4005d4 <main+0x5b>
  4005cf:       e8 4c fe ff ff          callq  400420 <__stack_chk_fail@plt>

  # Otherwise, exit normally.
  4005d4:       c9                      leaveq 
  4005d5:       c3                      retq   
  4005d6:       66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)
  4005dd:       00 00 00 

Notice the handy comments automatically added by objdump's artificial intelligence module.

If you run this program multiple times through GDB, you will see that:

  • the canary gets a different random value every time
  • the last loop of myfunc is exactly what modifies the address of the canary

The canary randomized by setting it with %fs:0x28, which contains a random value as explained at:

Debug attempts

From now on, we modify the code:

    myfunc(arr, len + 1);

to be instead:

    myfunc(arr, len);
    myfunc(arr, len + 1); /* line 12 */
    myfunc(arr, len);

to be more interesting.

We will then try to see if we can pinpoint the culprit + 1 call with a method more automated than just reading and understanding the entire source code.

gcc -fsanitize=address to enable Google's Address Sanitizer (ASan)

If you recompile with this flag and run the program, it outputs:

#0 0x4008bf in myfunc /home/ciro/test/main.c:4
#1 0x40099b in main /home/ciro/test/main.c:12
#2 0x7fcd2e13d82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
#3 0x400798 in _start (/home/ciro/test/a.out+0x40079

followed by some more colored output.

This clearly pinpoints the problematic line 12.

The source code for this is at: https://github.com/google/sanitizers but as we saw from the example it is already upstreamed into GCC.

ASan can also detect other memory problems such as memory leaks: How to find memory leak in a C++ code/project?

Valgrind SGCheck

As mentioned by others, Valgrind is not good at solving this kind of problem.

It does have an experimental tool called SGCheck:

SGCheck is a tool for finding overruns of stack and global arrays. It works by using a heuristic approach derived from an observation about the likely forms of stack and global array accesses.

So I was not very surprised when it did not find the error:

valgrind --tool=exp-sgcheck ./a.out

The error message should look like this apparently: Valgrind missing error

GDB

An important observation is that if you run the program through GDB, or examine the core file after the fact:

gdb -nh -q a.out core

then, as we saw on the assembly, GDB should point you to the end of the function that did the canary check:

(gdb) bt
#0  0x00007f0f66e20428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1  0x00007f0f66e2202a in __GI_abort () at abort.c:89
#2  0x00007f0f66e627ea in __libc_message (do_abort=do_abort@entry=1, fmt=fmt@entry=0x7f0f66f7a49f "*** %s ***: %s terminated\n") at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007f0f66f0415c in __GI___fortify_fail (msg=<optimized out>, msg@entry=0x7f0f66f7a481 "stack smashing detected") at fortify_fail.c:37
#4  0x00007f0f66f04100 in __stack_chk_fail () at stack_chk_fail.c:28
#5  0x00000000004005f6 in main () at main.c:15
(gdb) f 5
#5  0x00000000004005f6 in main () at main.c:15
15      }
(gdb)

And therefore the problem is likely in one of the calls that this function made.

Next we try to pinpoint the exact failing call by first single stepping up just after the canary is set:

  400581:       64 48 8b 04 25 28 00    mov    %fs:0x28,%rax
  400588:       00 00 
  40058a:       48 89 45 f8             mov    %rax,-0x8(%rbp)

and watching the address:

(gdb) p $rbp - 0x8
$1 = (void *) 0x7fffffffcf18
(gdb) watch 0x7fffffffcf18
Hardware watchpoint 2: *0x7fffffffcf18
(gdb) c
Continuing.

Hardware watchpoint 2: *0x7fffffffcf18

Old value = 1800814336
New value = 1800814378
myfunc (src=0x7fffffffcf14 "*****?Vk\266", <incomplete sequence \355\216>, len=5) at main.c:3
3           for (i = 0; i < len; ++i) {
(gdb) p len
$2 = 5
(gdb) p i
$3 = 4
(gdb) bt
#0  myfunc (src=0x7fffffffcf14 "*****?Vk\266", <incomplete sequence \355\216>, len=5) at main.c:3
#1  0x00000000004005cc in main () at main.c:12

Now, this does leaves us at the right offending instruction: len = 5 and i = 4, and in this particular case, did point us to the culprit line 12.

However, the backtrace is corrupted, and contains some trash. A correct backtrace would look like:

#0  myfunc (src=0x7fffffffcf14 "abcd", len=4) at main.c:3
#1  0x00000000004005b8 in main () at main.c:11

so maybe this could corrupt the stack and prevent you from seeing the trace.

Also, this method requires knowing what is the last call of the canary checking function otherwise you will have false positives, which will not always be feasible, unless you use reverse debugging.

How to find text in a column and saving the row number where it is first found - Excel VBA

Alternatively you could use a loop, keep the row number (counter should be the row number) and stop the loop when you find the first "ProjTemp".
Then it should look something like this:

Sub find()
    Dim i As Integer
    Dim firstTime As Integer
    Dim bNotFound As Boolean

    i = 1
    bNotFound = True

      Do While bNotFound
        If Cells(i, 2).Value = "ProjTemp" Then
            firstTime = i
            bNotFound = false
        End If
        i = i + 1
    Loop
End Sub

How to specify a port to run a create-react-app based project?

You can specify a environment variable named PORT to specify the port on which the server will run.

$ export PORT=3005 #Linux
$ $env:PORT=3005 # Windows - Powershell

Is it possible to use "return" in stored procedure?

In Stored procedure, you return the values using OUT parameter ONLY. As you have defined two variables in your example:

   outstaticip OUT VARCHAR2, outcount OUT NUMBER

Just assign the return values to the out parameters i.e. outstaticip and outcount and access them back from calling location. What I mean here is: when you call the stored procedure, you will be passing those two variables as well. After the stored procedure call, the variables will be populated with return values.

If you want to have RETURN value as return from the PL/SQL call, then use FUNCTION. Please note that in case, you would be able to return only one variable as return variable.

Run a JAR file from the command line and specify classpath

You can do a Runtime.getRuntime.exec(command) to relaunch the jar including classpath with args.

How do I find out if the GPS of an Android device is enabled

Best way seems to be the following:

 final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();
    }

  private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                   startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
               }
           });
    final AlertDialog alert = builder.create();
    alert.show();
}

chai test array equality doesn't work as expected

For expect, .equal will compare objects rather than their data, and in your case it is two different arrays.

Use .eql in order to deeply compare values. Check out this link.
Or you could use .deep.equal in order to simulate same as .eql.
Or in your case you might want to check .members.

For asserts you can use .deepEqual, link.

How can I create 2 separate log files with one log4j config file?

Modify your log4j.properties file accordingly:

log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog

Change the log levels for each logger depending to your needs.

How do I import a pre-existing Java project into Eclipse and get up and running?

This assumes Eclipse and an appropriate JDK are installed on your system

  1. Open Eclipse and create a new Workspace by specifying an empty directory.
  2. Make sure you're in the Java perspective by selecting Window -> Open Perspective ..., select Other... and then Java
  3. Right click anywhere in the Package Explorer pane and select New -> Java Project
  4. In the dialog that opens give the project a name and then click the option that says "Crate project from existing sources."
  5. In the text box below the option you selected in Step 4 point to the root directory where you checked out the project. This should be the directory that contains "com"
  6. Click Finish. For this particular project you don't need to do any additional setup for your classpath since it only depends on classes that are part of the Java SE API.

Docker Networking - nginx: [emerg] host not found in upstream

this error appeared to me because my php-fpm image enabled cron, and I have no idea why

How do I set the default page of my application in IIS7?

I was trying do the same of making a particular file my default page, instead of directory structure. So in IIS server I had to go to Default Document, add the page that I want to make as default and at the same time, go to the Web.config file and update the defaultDocument header with "enabled=true". This worked for me. Hopefully it helps.

Design Patterns web based applications

IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.

How to make a round button?

Used the shape as oval. This makes the button oval

<item>
    <shape android:shape="oval" >
        <stroke
            android:height="1.0dip"
            android:width="1.0dip"
            android:color="#ffee82ee" />

        <solid android:color="#ffee82ee" />

        <corners
            android:bottomLeftRadius="12.0dip"
            android:bottomRightRadius="12.0dip"
            android:radius="12.0dip"
            android:topLeftRadius="12.0dip"
            android:topRightRadius="12.0dip" />
    </shape>
</item>

(13: Permission denied) while connecting to upstream:[nginx]

I have solved my problem by running my Nginx as the user I'm currently logged in with, mulagala.

By default the user as nginx is defined at the very top section of the nginx.conf file as seen below;

user nginx; # Default Nginx user

Change nginx to the name of your current user - here, mulagala.

user mulagala; # Custom Nginx user (as username of the current logged in user)

However, this may not address the actual problem and may actually have casual side effect(s).

For an effective solution, please refer to Joseph Barbere's solution.

PostgreSQL wildcard LIKE for any of a list of words

PostgreSQL also supports full POSIX regular expressions:

select * from table where value ~* 'foo|bar|baz';

The ~* is for a case insensitive match, ~ is case sensitive.

Another option is to use ANY:

select * from table where value  like any (array['%foo%', '%bar%', '%baz%']);
select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);

You can use ANY with any operator that yields a boolean. I suspect that the regex options would be quicker but ANY is a useful tool to have in your toolbox.

WCF error: The caller was not authenticated by the service

If you use basicHttpBinding, configure the endpoint security to "None" and transport clientCredintialType to "None."

<bindings>
    <basicHttpBinding>
        <binding name="MyBasicHttpBinding">
            <security mode="None">
                <transport clientCredentialType="None" />
            </security>
        </binding>
    </basicHttpBinding>
</bindings>
<services>
    <service behaviorConfiguration="MyServiceBehavior" name="MyService">
        <endpoint 
            binding="basicHttpBinding" 
            bindingConfiguration="MyBasicHttpBinding"
            name="basicEndPoint"    
            contract="IMyService" 
        />
</service>

Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Python exit commands - why so many and when should each be used?

The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported.

The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

Conclusion

  • Use exit() or quit() in the REPL.

  • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

  • Use os._exit() for child processes to exit after a call to os.fork().

All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

Footnotes

* Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

Angular 5 Service to read local .json file

Let’s create a JSON file, we name it navbar.json you can name it whatever you want!

navbar.json

[
  {
    "href": "#",
    "text": "Home",
    "icon": ""
  },
  {
    "href": "#",
    "text": "Bundles",
    "icon": "",
    "children": [
      {
        "href": "#national",
        "text": "National",
        "icon": "assets/images/national.svg"
      }
    ]
  }
]

Now we’ve created a JSON file with some menu data. We’ll go to app component file and paste the below code.

app.component.ts

import { Component } from '@angular/core';
import menudata from './navbar.json';

@Component({
  selector: 'lm-navbar',
  templateUrl: './navbar.component.html'
})
export class NavbarComponent {
    mainmenu:any = menudata;

}

Now your Angular 7 app is ready to serve the data from the local JSON file.

Go to app.component.html and paste the following code in it.

app.component.html

<ul class="navbar-nav ml-auto">
                  <li class="nav-item" *ngFor="let menu of mainmenu">
                  <a class="nav-link" href="{{menu.href}}">{{menu.icon}} {{menu.text}}</a>
                  <ul class="sub_menu" *ngIf="menu.children && menu.children.length > 0"> 
                            <li *ngFor="let sub_menu of menu.children"><a class="nav-link" href="{{sub_menu.href}}"><img src="{{sub_menu.icon}}" class="nav-img" /> {{sub_menu.text}}</a></li> 
                        </ul>
                  </li>
                  </ul>

How to remove listview all items

use any one of the bellow options which suites your requirement

listview.removeViews(1,listview.getChildCount());

or

listview.removeViewInLayout(your view);

How can I switch my signed in user in Visual Studio 2013?

Execute VSWinExpress /resetuserdata, located in C:\Program Files (x86)\Microsoft Visual Studio 12.0, to reset the user credentials for Visual Studio 2013 Express.

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

I used fake UserAgent.

How to use:

from fake_useragent import UserAgent
import requests
   

ua = UserAgent()
print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
print(header)
url = "https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp"
htmlContent = requests.get(url, headers=header)
print(htmlContent)

Output:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
{'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}
<Response [200]>

Run a script in Dockerfile

WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh 

how to use php DateTime() function in Laravel 5

If you just want to get the current UNIX timestamp I'd just use time()

$timestamp = time(); 

Using moment.js to convert date to string "MM/dd/yyyy"

Try this:

var momentObj = $("#start_ts").datepicker("getDate");

var yourDate = momentObj.format('L');

Crop image in android

hope you are doing well. you can use my code to crop image.you just have to make a class and use this class into your XMl and java classes. Crop image. you can crop your selected image into circle and square into many of option. hope fully it will works for you.because this is totally manageable for you and you can change it according to you.

enjoy your work :)

C# Creating an array of arrays

This loops vertically but might work for you.

int rtn = 0;    
foreach(int[] L in lists){
    for(int i = 0; i<L.Length;i++){
          rtn = L[i];
      //Do something with rtn
    }
}

R not finding package even after package installation

When you run

install.packages("whatever")

you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:

.libPaths()

If libPaths shows 2 locations, then paste into second one. Load library:

library(whatever)

Fixed.

MySQL > Table doesn't exist. But it does (or it should)

If there's a period in the table name, it will fail for SELECT * FROM poorly_named.table;

Use backticks to get it to find the table SELECT * FROM `poorly_named.table`;

Docker-compose: node_modules not present in a volume after npm install succeeds

There is also some simple solution without mapping node_module directory into another volume. It's about to move installing npm packages into final CMD command.

Disadvantage of this approach:

  • run npm install each time you run container (switching from npm to yarn might also speed up this process a bit).

worker/Dockerfile

FROM node:0.12
WORKDIR /worker
COPY package.json /worker/
COPY . /worker/
CMD /bin/bash -c 'npm install; npm start'

docker-compose.yml

redis:
    image: redis
worker:
    build: ./worker
    ports:
        - "9730:9730"
    volumes:
        - worker/:/worker/
    links:
        - redis

Get the item doubleclick event of listview

Use the ListView.HitTest method

    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var senderList  = (ListView) sender;
        var clickedItem = senderList.HitTest(e.Location).Item;
        if (clickedItem != null)
        {
            //do something
        }            
    }

Or the old way

    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var senderList  = (ListView) sender;                        
        if (senderList.SelectedItems.Count == 1 && IsInBound(e.Location, senderList.SelectedItems[0].Bounds))
        {
            //Do something
        }
    }

    public  bool IsInBound(Point location, Rectangle bound)
    {
        return (bound.Y <= location.Y && 
                bound.Y + bound.Height >= location.Y &&
                bound.X <= location.X && 
                bound.X + bound.Width >= location.X);
    }

How set the android:gravity to TextView from Java side in Android

Use this code

        TextView textView = new TextView(YourActivity.this);
        textView.setGravity(Gravity.CENTER | Gravity.TOP);
        textView.setText("some text");

Error in installation a R package

I had the same problem with e1071 package. Just close any other R sessions running parallelly and you will be good to go.

Unique random string generation

This has been asked for various languages. Here's one question about passwords which should be applicable here as well.

If you want to use the strings for URL shortening, you'll also need a Dictionary<> or database check to see whether a generated ID has already been used.

How do I pass options to the Selenium Chrome driver using Python?

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')

# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())

Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.

Sorting HashMap by values

package SortedSet;

import java.util.*;

public class HashMapValueSort {
public static void main(String[] args){
    final Map<Integer, String> map = new HashMap<Integer,String>();
    map.put(4,"Mango");
    map.put(3,"Apple");
    map.put(5,"Orange");
    map.put(8,"Fruits");
    map.put(23,"Vegetables");
    map.put(1,"Zebra");
    map.put(5,"Yellow");
    System.out.println(map);
    final HashMapValueSort sort = new HashMapValueSort();
    final Set<Map.Entry<Integer, String>> entry = map.entrySet();
    final Comparator<Map.Entry<Integer, String>> comparator = new Comparator<Map.Entry<Integer, String>>() {
        @Override
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
            String value1 = o1.getValue();
            String value2 = o2.getValue();
            return value1.compareTo(value2);
        }
    };
    final SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet(comparator);
    sortedSet.addAll(entry);
    final Map<Integer,String> sortedMap =  new LinkedHashMap<Integer, String>();
    for(Map.Entry<Integer, String> entry1 : sortedSet ){
        sortedMap.put(entry1.getKey(),entry1.getValue());
    }
    System.out.println(sortedMap);
}
}

HTTP POST with Json on Body - Flutter/Dart

In my case I forgot to enable

app.use(express.json());

in my NodeJs server.

Get Application Directory

I got this

String appPath = App.getApp().getApplicationContext().getFilesDir().getAbsolutePath();

from here:

How to parse JSON to receive a Date object in JavaScript?

The JSON.parse function accepts an optional DateTime reviver function. You can use a function like this:

dateTimeReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = /\/Date\((\d*)\)\//.exec(value);
        if (a) {
            return new Date(+a[1]);
        }
    }
    return value;
}

Then call

JSON.parse(somejsonstring, dateTimeReviver);

And your dates will come out right.

Date ticks and rotation in matplotlib

Another way to applyhorizontalalignment and rotation to each tick label is doing a for loop over the tick labels you want to change:

import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]
hours_value = np.random.random(len(hours))
days_value = np.random.random(len(days))

fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
axs[0].plot(hours,hours_value)
axs[1].plot(days,days_value)

for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
    label.set_rotation(30)
    label.set_horizontalalignment("right")

enter image description here

And here is an example if you want to control the location of major and minor ticks:

import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]

axs[0].plot(hours,np.random.random(len(hours)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.HourLocator(byhour = range(0,25,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[0].xaxis.set_major_locator(x_major_lct)
axs[0].xaxis.set_minor_locator(x_minor_lct)
axs[0].xaxis.set_major_formatter(x_fmt)
axs[0].set_xlabel("minor ticks set to every hour, major ticks start with 00:00")

axs[1].plot(days,np.random.random(len(days)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.DayLocator(bymonthday = range(0,32,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[1].xaxis.set_major_locator(x_major_lct)
axs[1].xaxis.set_minor_locator(x_minor_lct)
axs[1].xaxis.set_major_formatter(x_fmt)
axs[1].set_xlabel("minor ticks set to every day, major ticks show first day of month")
for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
    label.set_rotation(30)
    label.set_horizontalalignment("right")

enter image description here

JavaScript naming conventions

I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

i used the empty div solution, with this CSS:

#throbber {
    background-image: url(/Content/pictures/ajax-loader.gif);
    background-repeat: no-repeat;
    width: 48px;
    height: 48px;
    min-width: 48px;
    min-height: 48px;
}

HTML:

<div id="throbber"></div>

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result.

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

However, the code below allows spaces.

No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:

var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) === -1)
    { alert('invalid'); }
else
    { alert('valid'); }

Note that neither the - (in this instance) nor the _ need escaping.

what is <meta charset="utf-8">?

The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.

UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

Update Top 1 record in table sql server

Accepted answer of Kapil is flawed, it will update more than one record if there are 2 or more than one records available with same timestamps, not a true top 1 query.

    ;With cte as (
                    SELECT TOP(1) email_fk FROM abc WHERE id= 177 ORDER BY created DESC   
            )
    UPDATE cte SET email_fk = 10

Ref Remus Rusanu Ans:- SQL update top1 row query

Get started with Latex on Linux

It depends on your Linux distibution and your preference of editors etc. but I would recommend to start with Kile (a KDE app) as it is easy to learn and installing it should install most of the needed packages for LaTex and PDF generation. Just have a look at the screenshots.

Why number 9 in kill -9 command in unix?

First you need to know what are Signals in Unix-like systems (It'll take just few minutes).

Signals, are software interrupts sent to a (running) program to indicate that an important event has occurred.

The events can vary from user requests to illegal memory access errors. Some signals, such as the interrupt signal, indicate that a user has asked the program to do something that is not in the usual flow of control.

There are several types of Signals we can use - to get a full list of all the available/possible Signals use "$ kill -l" command: enter image description here

In the above output it's clearly visible, that each Signal has a 'signal number' (e.g. 1, 2, 3) and a 'signal name' (e.g. SIGUP, SIGINT, SIGQUIT) associated with it. For a detailed look up what each and every Signal does, visit this link.

Finally, coming to the question "Why number 9 in kill -9 command":

There are several methods of delivering signals to a program or script. One of commonly used method for sending signal is to use the kill command - the basic syntax is:

$ kill -signal pid

Where signal is either the number or name of the signal, followed by the process Id (pid) to which the signal will be sent.

For example - -SIGKILL (or -9), signal kills the process immediately.

$ kill -SIGKILL 1001

and

$ kill -9 1001

both command are one the same thing i.e. above we have used the 'signal name', and later we have used 'signal number'.

Verdict: One has an open choice to whether use the 'signal name' or 'signal number' with the kill command.

How to backup MySQL database in PHP?

From the answer of @DevWL, I got "Undefined offset ..." at

if ($j<($num_fields-1)) { $data.= ','; }

I made some changes to:

  • preserve relationships (foreign keys)
  • use Transactions
  • remove the uneedy $num_fields

class DBbackup {
 public $suffix;
 public $dirs;
 protected $dbInstance;
 public function __construct() {
   try{
    $this->dbInstance = new PDO("mysql:host=".$dbhost.";dbname=".$dbname, 
    $username, $password);
  } catch(Exception $e) {
    die("Error ".$e->getMessage());
  }
   $this->suffix = date('Ymd_His');
 }

 public function backup($tables = '*'){
   $output = "-- database backup - ".date('Y-m-d H:i:s').PHP_EOL;
   $output .= "SET NAMES utf8;".PHP_EOL;
   $output .= "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';".PHP_EOL;
   $output .= "SET foreign_key_checks = 0;".PHP_EOL;
   $output .= "SET AUTOCOMMIT = 0;".PHP_EOL;
   $output .= "START TRANSACTION;".PHP_EOL;
   //get all table names
   if($tables == '*') {
     $tables = [];
     $query = $this->dbInstance->prepare('SHOW TABLES');
     $query->execute();
     while($row = $query->fetch(PDO::FETCH_NUM)) {
       $tables[] = $row[0];
     }
     $query->closeCursor();
   }
   else {
     $tables = is_array($tables) ? $tables : explode(',',$tables);
   }

   foreach($tables as $table) {

     $query = $this->dbInstance->prepare("SELECT * FROM `$table`");
     $query->execute();
     $output .= "DROP TABLE IF EXISTS `$table`;".PHP_EOL;

     $query2 = $this->dbInstance->prepare("SHOW CREATE TABLE `$table`");
     $query2->execute();
     $row2 = $query2->fetch(PDO::FETCH_NUM);
     $query2->closeCursor();
     $output .= PHP_EOL.$row2[1].";".PHP_EOL;

       while($row = $query->fetch(PDO::FETCH_NUM)) {
         $output .= "INSERT INTO `$table` VALUES(";
         for($j=0; $j<count($row); $j++) {
           $row[$j] = addslashes($row[$j]);
           $row[$j] = str_replace("\n","\\n",$row[$j]);
           if (isset($row[$j]))
             $output .= "'".$row[$j]."'";
           else $output .= "''";
           if ($j<(count($row)-1))
            $output .= ',';
         }
         $output .= ");".PHP_EOL;
       }
     }
     $output .= PHP_EOL.PHP_EOL;

   $output .= "COMMIT;";
   //save filename

   $filename = 'db_backup_'.$this->suffix.'.sql';
   $this->writeUTF8filename($filename,$output);
 }


 private function writeUTF8filename($fn,$c){  /* save as utf8 encoding */
   $f=fopen($fn,"w+");
   # Now UTF-8 - Add byte order mark
   fwrite($f, pack("CCC",0xef,0xbb,0xbf));
   fwrite($f,$c);
   fclose($f);
 }

}

And usage example:

$Backup = new DBbackup();
$Backup->backup();

This works great on MySQL 10.1.34-MariaDB , PHP : 7.2.7

Plotting with C#

There is OxyPlot which I recommend. It has packages for WPF, Metro, Silverlight, Windows Forms, Avalonia UI, XWT. Besides graphics it can export to SVG, PDF, Open XML, etc. And it even supports Mono and Xamarin for Android and iOS. It is actively developed too.

There is also a new (at least for me) open source .NET plotting library called Live-Charts. The plots are pretty interactive. Library suports WPF, WinForms and UWP. Xamarin is planned. The design is made towards MV* patterns. But @Pawel Audionysos suggests not such a good performance of Live-Charts WPF.

How to retrieve records for last 30 minutes in MS SQL?

DATEADD only returned Function does not exist on MySQL 5.5.53 (I know it's old)

Instead, I found DatePlayed > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 30 minute) to produce the desired result