Programs & Examples On #E commerce

Electronic commerce, commonly known as e-commerce, eCommerce or e-comm, refers to the buying and selling of products or services over electronic systems such as the Internet.

How to remove index.php from URLs?

If the other solutions don't work for you, try this:

Step 1: (if your installation is in webroot)

Replace

    #RewriteBase /magento/

with

    RewriteBase /

Step 2:

Add following lines (inclusive exclude admin because backend needs index.php internally)

RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.yourdomain.com/$1 [R=301,L]
RewriteRule ^index.php/(admin|user)($|/) - [L]
RewriteRule ^index.php/(.*) $1 [R=301,QSA,L]

right after

RewriteRule .* index.php [L] 

This works for me

In case it is still not working, double check Magento configuration: System->Configuration->Web->Search Engine Optimization. Rewrites must be enabled.

Credit card expiration dates - Inclusive or exclusive?

It took me a couple of minutes to find a site that I could source for this.

The card is valid until the last day of the month indicated, after the last [sic]1 day of the next month; the card cannot be used to make a purchase if the merchant attempts to obtain an authorization. - Source

Also, while looking this up, I found an interesting article on Microsoft's website using an example like this, exec summary: Access 2000 for a month/year defaults to the first day of the month, here's how to override that to calculate the end of the month like you'd want for a credit card.

Additionally, this page has everything you ever wanted to know about credit cards.


  1. This is assumed to be a typo and that it should read "..., after the first day of the next month; ..."

How do you detect Credit card type based on number?

The regular expression rules that match the respective card vendors:

  • (4\d{12}(?:\d{3})?) for VISA.
  • (5[1-5]\d{14}) for MasterCard.
  • (3[47]\d{13}) for AMEX.
  • ((?:5020|5038|6304|6579|6761)\d{12}(?:\d\d)?) for Maestro.
  • (3(?:0[0-5]|[68][0-9])[0-9]{11}) for Diners Club.
  • (6(?:011|5[0-9]{2})[0-9]{12}) for Discover.
  • (35[2-8][89]\d\d\d{10}) for JCB.

Magento - Retrieve products with a specific attribute value

create attribute name is "price_screen_tab_name". and access using this simple formula.

<?php $_product = $this->getProduct(); ?>
<?php echo $_product->getData('price_screen_tab_name');?>

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

how to toggle (hide/show) a table onClick of <a> tag in java script

Try

<script>
  function toggleTable()
    {

    var status = document.getElementById("loginTable").style.display;

    if (status == 'block') {
      document.getElementById("loginTable").style.display="none";
    } else {
      document.getElementById("loginTable").style.display="block";
    }
  }
</script>

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

Generic deep diff between two objects

I stumbled here trying to look for a way to get the difference between two objects. This is my solution using Lodash:

// Get updated values (including new values)
var updatedValuesIncl = _.omitBy(curr, (value, key) => _.isEqual(last[key], value));

// Get updated values (excluding new values)
var updatedValuesExcl = _.omitBy(curr, (value, key) => (!_.has(last, key) || _.isEqual(last[key], value)));

// Get old values (by using updated values)
var oldValues = Object.keys(updatedValuesIncl).reduce((acc, key) => { acc[key] = last[key]; return acc; }, {});

// Get newly added values
var newCreatedValues = _.omitBy(curr, (value, key) => _.has(last, key));

// Get removed values
var deletedValues = _.omitBy(last, (value, key) => _.has(curr, key));

// Then you can group them however you want with the result

Code snippet below:

_x000D_
_x000D_
var last = {_x000D_
"authed": true,_x000D_
"inForeground": true,_x000D_
"goodConnection": false,_x000D_
"inExecutionMode": false,_x000D_
"online": true,_x000D_
"array": [1, 2, 3],_x000D_
"deep": {_x000D_
 "nested": "value",_x000D_
},_x000D_
"removed": "value",_x000D_
};_x000D_
_x000D_
var curr = {_x000D_
"authed": true,_x000D_
"inForeground": true,_x000D_
"deep": {_x000D_
 "nested": "changed",_x000D_
},_x000D_
"array": [1, 2, 4],_x000D_
"goodConnection": true,_x000D_
"inExecutionMode": false,_x000D_
"online": false,_x000D_
"new": "value"_x000D_
};_x000D_
_x000D_
// Get updated values (including new values)_x000D_
var updatedValuesIncl = _.omitBy(curr, (value, key) => _.isEqual(last[key], value));_x000D_
// Get updated values (excluding new values)_x000D_
var updatedValuesExcl = _.omitBy(curr, (value, key) => (!_.has(last, key) || _.isEqual(last[key], value)));_x000D_
// Get old values (by using updated values)_x000D_
var oldValues = Object.keys(updatedValuesIncl).reduce((acc, key) => { acc[key] = last[key]; return acc; }, {});_x000D_
// Get newly added values_x000D_
var newCreatedValues = _.omitBy(curr, (value, key) => _.has(last, key));_x000D_
// Get removed values_x000D_
var deletedValues = _.omitBy(last, (value, key) => _.has(curr, key));_x000D_
_x000D_
console.log('oldValues', JSON.stringify(oldValues));_x000D_
console.log('updatedValuesIncl', JSON.stringify(updatedValuesIncl));_x000D_
console.log('updatedValuesExcl', JSON.stringify(updatedValuesExcl));_x000D_
console.log('newCreatedValues', JSON.stringify(newCreatedValues));_x000D_
console.log('deletedValues', JSON.stringify(deletedValues));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
_x000D_
_x000D_
_x000D_

Writing to an Excel spreadsheet

Use DataFrame.to_excel from pandas. Pandas allows you to represent your data in functionally rich datastructures and will let you read in excel files as well.

You will first have to convert your data into a DataFrame and then save it into an excel file like so:

In [1]: from pandas import DataFrame
In [2]: l1 = [1,2,3,4]
In [3]: l2 = [1,2,3,4]
In [3]: df = DataFrame({'Stimulus Time': l1, 'Reaction Time': l2})
In [4]: df
Out[4]: 
   Reaction Time  Stimulus Time
0              1              1
1              2              2
2              3              3
3              4              4

In [5]: df.to_excel('test.xlsx', sheet_name='sheet1', index=False)

and the excel file that comes out looks like this:

enter image description here

Note that both lists need to be of equal length else pandas will complain. To solve this, replace all missing values with None.

jquery json to string?

The best way I have found is to use jQuery JSON

Java creating .jar file

Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.

SmartGit Installation and Usage on Ubuntu

Now on the Smartgit webpage (I don't know since when) there is the possibility to download directly the .deb package. Once installed, it will upgrade automagically itself when a new version is released.

Custom li list-style with font-awesome icon

The CSS Lists and Counters Module Level 3 introduces the ::marker pseudo-element. From what I've understood it would allow such a thing. Unfortunately, no browser seems to support it.

What you can do is add some padding to the parent ul and pull the icon into that padding:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
  padding: 0;_x000D_
}_x000D_
li {_x000D_
  padding-left: 1.3em;_x000D_
}_x000D_
li:before {_x000D_
  content: "\f00c"; /* FontAwesome Unicode */_x000D_
  font-family: FontAwesome;_x000D_
  display: inline-block;_x000D_
  margin-left: -1.3em; /* same as padding-left set on li */_x000D_
  width: 1.3em; /* same as padding-left set on li */_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">_x000D_
<ul>_x000D_
  <li>Item one</li>_x000D_
  <li>Item two</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Adjust the padding/font-size/etc to your liking, and that's it. Here's the usual fiddle: http://jsfiddle.net/joplomacedo/a8GxZ/

=====

This works with any type of iconic font. FontAwesome, however, provides their own way to deal with this 'problem'. Check out Darrrrrren's answer below for more details.

How can I draw vertical text with CSS cross-browser?

I am using the following code to write vertical text in a page. Firefox 3.5+, webkit, opera 10.5+ and IE

.rot-neg-90 {
    -moz-transform:rotate(-270deg); 
    -moz-transform-origin: bottom left;
    -webkit-transform: rotate(-270deg);
    -webkit-transform-origin: bottom left;
    -o-transform: rotate(-270deg);
    -o-transform-origin:  bottom left;
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
}

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

An alternative to adding LINQ would be to use this code instead:

List<Pax_Detail> paxList = new List<Pax_Detail>(pax);

How do you disable browser Autocomplete on web form field / input tag?

This worked for me like a charm.

  1. Set the autocomplete attribute of the form to off
  2. Add a dummy input field and set its attribute also to off.
<form autocomplete="off">
 <input type="text" autocomplete="off" style="display:none">
</form>

HttpContext.Current.User.Identity.Name is Empty

These might resolve the issue(It did for me). In IIS Express change the project property values, "Anonymous Authentication" and "Windows Authentication". To do this, when project is selected, press F4 and then change these properties.

enter image description here

In case you are deploying it on IIS locally, make sure local machines "Windows Authentication" feature is enabled and "Anonymous Authentication" is disabled.

Refer to

https://grekai.wordpress.com/2011/03/31/httpcontext-current-user-identity-name-is-empty/

How To Raise Property Changed events on a Dependency Property?

I question the logic of raising a PropertyChanged event on the second property when it's the first property that's changing. If the second properties value changes then the PropertyChanged event could be raised there.

At any rate, the answer to your question is you should implement INotifyPropertyChange. This interface contains the PropertyChanged event. Implementing INotifyPropertyChanged lets other code know that the class has the PropertyChanged event, so that code can hook up a handler. After implementing INotifyPropertyChange, the code that goes in the if statement of your OnPropertyChanged is:

if (PropertyChanged != null)
    PropertyChanged(new PropertyChangedEventArgs("MySecondProperty"));

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

How to add text to an existing div with jquery

Very easy from My side:-

<html>
<head>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("input").click(function() {
            $('<input type="text" name="name" value="value"/>').appendTo('#testdiv');
        });

    });
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <div id="testdiv"></div>
    <input type="button" value="Add" />
</body>
</html>

How can I make text appear on next line instead of overflowing?

Try the <wbr> tag - not as elegant as the word-wrap property that others suggested, but it's a working solution until all major browsers (read IE) implement CSS3.

How do I convert datetime.timedelta to minutes, hours in Python?

# Try this code
from datetime import timedelta

class TimeDelta(timedelta):
    def __str__(self):
        _times = super(TimeDelta, self).__str__().split(':')
        if "," in _times[0]:
            _hour = int(_times[0].split(',')[-1].strip())
            if _hour:
                _times[0] += " hours" if _hour > 1 else " hour"
            else:
                _times[0] = _times[0].split(',')[0]
        else:
            _hour = int(_times[0].strip())
            if _hour:
                _times[0] += " hours" if _hour > 1 else " hour"
            else:
                _times[0] = ""
        _min = int(_times[1])
        if _min:
            _times[1] += " minutes" if _min > 1 else " minute"
        else:
            _times[1] = ""
        _sec = int(_times[2])
        if _sec:
            _times[2] += " seconds" if _sec > 1 else " second"
        else:
            _times[2] = ""
        return ", ".join([i for i in _times if i]).strip(" ,").title()

# Test
>>> str(TimeDelta(seconds=10))
'10 Seconds'
>>> str(TimeDelta(seconds=60))
'01 Minute'
>>> str(TimeDelta(seconds=90))
'01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3000))
'50 Minutes'
>>> str(TimeDelta(seconds=3600))
'1 Hour'
>>> str(TimeDelta(seconds=3690))
'1 Hour, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3660))
'1 Hour, 01 Minute'
>>> str(TimeDelta(seconds=3630))
'1 Hour, 30 Seconds'
>>> str(TimeDelta(seconds=3600*20))
'20 Hours'
>>> str(TimeDelta(seconds=3600*20 + 3000))
'20 Hours, 50 Minutes'
>>> str(TimeDelta(seconds=3600*20 + 3630))
'21 Hours, 30 Seconds'
>>> str(TimeDelta(seconds=3600*20 + 3660))
'21 Hours, 01 Minute'
>>> str(TimeDelta(seconds=3600*20 + 3690))
'21 Hours, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24))
'1 Day'
>>> str(TimeDelta(seconds=3600*24 + 10))
'1 Day, 10 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 60))
'1 Day, 01 Minute'
>>> str(TimeDelta(seconds=3600*24 + 90))
'1 Day, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 3000))
'1 Day, 50 Minutes'
>>> str(TimeDelta(seconds=3600*24 + 3600))
'1 Day, 1 Hour'
>>> str(TimeDelta(seconds=3600*24 + 3630))
'1 Day, 1 Hour, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 3660))
'1 Day, 1 Hour, 01 Minute'
>>> str(TimeDelta(seconds=3600*24 + 3690))
'1 Day, 1 Hour, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24*2))
'2 Days'
>>> str(TimeDelta(seconds=3600*24*2 + 9999))
'2 Days, 2 Hours, 46 Minutes, 39 Seconds'

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

This specifies the default collation for the database. Every text field that you create in tables in the database will use that collation, unless you specify a different one.

A database always has a default collation. If you don't specify any, the default collation of the SQL Server instance is used.

The name of the collation that you use shows that it uses the Latin1 code page 1, is case insensitive (CI) and accent sensitive (AS). This collation is used in the USA, so it will contain sorting rules that are used in the USA.

The collation decides how text values are compared for equality and likeness, and how they are compared when sorting. The code page is used when storing non-unicode data, e.g. varchar fields.

retrieve data from db and display it in table in php .. see this code whats wrong with it?

In your while statement just replace mysql_fetch_row with mysql_fetch_array or mysql_fetch_assoc... whichever works...

Difference between Relative path and absolute path in javascript

Relative Paths

A relative path assumes that the file is on the current server. Using relative paths allows you to construct your site offline and fully test it before uploading it.

For example:

php/webct/itr/index.php

.

Absolute Paths

An absolute path refers to a file on the Internet using its full URL. Absolute paths tell the browser precisely where to go.

For example:

http://www.uvsc.edu/disted/php/webct/itr/index.php

Absolute paths are easier to use and understand. However, it is not good practice on your own website. For one thing, using relative paths allows you to construct your site offline and fully test it before uploading it. If you were to use absolute paths you would have to change your code before uploading it in order to get it to work. This would also be the case if you ever had to move your site or if you changed domain names.

Reference: http://openhighschoolcourses.org/mod/book/tool/print/index.php?id=12503

How to copy JavaScript object to new variable NOT by reference?

Your only option is to somehow clone the object.

See this stackoverflow question on how you can achieve this.

For simple JSON objects, the simplest way would be:

var newObject = JSON.parse(JSON.stringify(oldObject));

if you use jQuery, you can use:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

In ES6 or TypeScript (2.1+):

var shallowCopy = { ...oldObject };

var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };

Note that if extraProp is also a property on oldObject, its value will not be used because the extraProp : "abc" is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

What is meant by immutable?

java.time

It might be a bit late but in order to understand what an immutable object is, consider the following example from the new Java 8 Date and Time API (java.time). As you probably know all date objects from Java 8 are immutable so in the following example

LocalDate date = LocalDate.of(2014, 3, 18); 
date.plusYears(2);
System.out.println(date);

Output:

2014-03-18

This prints the same year as the initial date because the plusYears(2) returns a new object so the old date is still unchanged because it's an immutable object. Once created you cannot further modify it and the date variable still points to it.

So, that code example should capture and use the new object instantiated and returned by that call to plusYears.

LocalDate date = LocalDate.of(2014, 3, 18); 
LocalDate dateAfterTwoYears = date.plusYears(2);

date.toString()… 2014-03-18

dateAfterTwoYears.toString()… 2016-03-18

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.

in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.

name, lastname, email in unpaidMembers.items() so you should refer data or your code might be
lastname, email in unpaidMembers.items() or name, email in unpaidMembers.items()

How to fix/convert space indentation in Sublime Text?

I found, in my mind, a simpler solution than Magne:

On mac:

"cmd+f" => "  "(two spaces) => "alt+enter" => "arrow right" => "  "(two more spaces) => set tab width to 4(this can be done before or after.

On windows or other platforms change cmd+f and alt+enter with whatever your find and select all hotkeys are.

Note: this method is prone to "errors" if you have more than one space within your code. It is thus less safe than Magne's method, but it is faster (for me at least).

How to hide a div with jQuery?

$("#myDiv").hide();

will set the css display to none. if you need to set visibility to hidden as well, could do this via

$("#myDiv").css("visibility", "hidden");

or combine both in a chain

$("#myDiv").hide().css("visibility", "hidden");

or write everything with one css() function

$("#myDiv").css({
  display: "none",
  visibility: "hidden"
});

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

Creating .pem file for APNS?

There is a easiest way to create .Pem file if you have already apns p12 file in your key chain access.

Open terminal and enter the below command:

For Devlopment openssl pkcs12 -in apns-div-cert.p12 -out apns-div-cert.pem -nodes -clcerts

For Production openssl pkcs12 -in apns-dist-cert.p12 -out apns-dist-cert.pem -nodes -clcerts

Rename your P12 file with this name : apns-div-cert.p12 otherwise instead of this you need to enter your filename. Thanks!!

Get element inside element by class and ID - JavaScript

You can do it like this:

var list = document.getElementById("foo").getElementsByClassName("bar");
if (list && list.length > 0) {
    list[0].innerHTML = "Goodbye world!";
}

or, if you want to do it with with less error checking and more brevity, it can be done in one line like this:

document.getElementById("foo").getElementsByClassName("bar")[0].innerHTML = "Goodbye world!";

In explanation:

  1. You get the element with id="foo".
  2. You then find the objects that are contained within that object that have class="bar".
  3. That returns an array-like nodeList, so you reference the first item in that nodeList
  4. You can then set the innerHTML of that item to change its contents.

Caveats: some older browsers don't support getElementsByClassName (e.g. older versions of IE). That function can be shimmed into place if missing.


This is where I recommend using a library that has built-in CSS3 selector support rather than worrying about browser compatibility yourself (let someone else do all the work). If you want just a library to do that, then Sizzle will work great. In Sizzle, this would be be done like this:

Sizzle("#foo .bar")[0].innerHTML = "Goodbye world!";

jQuery has the Sizzle library built-in and in jQuery, this would be:

$("#foo .bar").html("Goodbye world!");

What does the ^ (XOR) operator do?

^ is the Python bitwise XOR operator. It is how you spell XOR in python:

>>> 0 ^ 0
0
>>> 0 ^ 1
1
>>> 1 ^ 0
1
>>> 1 ^ 1
0

XOR stands for exclusive OR. It is used in cryptography because it let's you 'flip' the bits using a mask in a reversable operation:

>>> 10 ^ 5
15
>>> 15 ^ 5
10

where 5 is the mask; (input XOR mask) XOR mask gives you the input again.

SQL order string as number

Alter your field to be INT instead of VARCHAR.

I can not make them INT due to some other depending circumstances.

Then fix the depending circumstances first. Otherwise you are working around the real underlying issue. Using a MySQL CAST is an option, but it's masking your bad schema which should be fixed.

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

For windows :

Package.json

  "scripts": {
    "start": "nodemon app.js",
    "test": "mocha"
  },

then run the command

npm run test

Links in <select> dropdown options

You can use the onChange property. Something like:

<select onChange="window.location.href=this.value">
    <option value="www.google.com">A</option>
    <option value="www.aol.com">B</option>
</select>

How to set dropdown arrow in spinner?

Set the Dropdown arrow image to spinner like this :

<Spinner
    android:id="@+id/Exam_Course"
    android:layout_width="320dp"
    android:background="@drawable/spinner_bg"
    android:layout_height="wrap_content"/>

Here android:background="@drawable/spinner_bg" the spinner_bg is the Dropdown arrow image.

Getting ssh to execute a command in the background on target machine

You can do it like this...

sudo /home/script.sh -opt1 > /tmp/script.out &

IIS Express Windows Authentication

Visual Studio 2010 SP1 and 2012 added support for IIS Express eliminating the need to edit angle brackets.

  1. If you haven't already, right-click a web-flavored project and select "Use IIS Express...".
  2. Once complete, select the web project and press F4 to focus the Properties panel.
  3. Set the "Windows Authentication" property to Enabled, and the "Anonymous Authentication" property to Disabled.

enter image description here

I believe this solution is superior to the vikomall's options.

  • Option #1 is a global change for all IIS Express sites.
  • Option #2 leaves development cruft in the web.config.
    • Further, it will probably lead to an error when deployed to IIS 7.5 unless you follow the "unlock" procedure on your IIS server's applicationHost.config.

The UI-based solution above uses site-specific location elements in IIS Express's applicationHost.config leaving the app untouched.

More information here: http://msdn.microsoft.com/en-us/magazine/hh288080.aspx

Add a column with a default value to an existing table in SQL Server

SQL Server + Alter Table + Add Column + Default Value uniqueidentifier...

ALTER TABLE [TABLENAME] ADD MyNewColumn INT not null default 0 GO

How to write a:hover in inline CSS?

<style>a:hover { }</style>
<a href="/">Go Home</a>

Hover is a pseudo class, and thus cannot be applied with a style attribute. It is part of the selector.

Fatal error: Class 'ZipArchive' not found in

Centos 6

Or any RHEL-based flavors

yum install php-pecl-zip

service httpd restart

How to wait for a process to terminate to execute another process in batch file

This is my adaptation johnrefling's. This work also in WindowsXP; in my case i start the same application at the end, because i want reopen it with different parametrs. My application is a WindowForm .NET

@echo off
taskkill -im:MyApp.exe
:loop1
tasklist | find /i "MyApp.exe" >nul 2>&1
if errorlevel 1 goto cont1
echo "Waiting termination of process..."
:: timeout /t 1 /nobreak >nul 2>&1      ::this don't work in windows XP
:: from: https://stackoverflow.com/questions/1672338/how-to-sleep-for-five-seconds-in-a-batch-file-cmd/33286113#33286113
typeperf "\System\Processor Queue Length" -si 1 -sc 1 >nul s
goto loop1
:cont1
echo "Process terminated, start new application"
START "<SYMBOLIC-TEXT-NAME>" "<full-path-of-MyApp2.exe>" "MyApp2-param1" "MyApp2-param2"
pause

Why does CSS not support negative padding?

Fitting an Iframe inside containers will not match the size of the container. It adds about 20px of padding. Currently there is no easy way to fix this. You need javascript (http://css-tricks.com/snippets/jquery/fit-iframe-to-content/)

Negative margins would be an easy solution.

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

JavaScript - Use variable in string match

Example. To find number of vowels within the string

var word='Web Development Tutorial';
var vowels='[aeiou]'; 
var re = new RegExp(vowels, 'gi');
var arr = word.match(re);
document.write(arr.length);

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

ClientScript.RegisterClientScriptBlock?

Hai sridhar, I found an answer for your prob

ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);

change false to true

or try this

ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);

How can I pass POST parameters in a URL?

You can make a link perform an Ajax post request when it's clicked.

In jQuery:

$('a').click(function(e) {
    var $this = $(this);
    e.preventDefault();
    $.post('url', {'user': 'something', 'foo': 'bar'}, function() {
        window.location = $this.attr('href');
    });
});

You could also make the link submit a POST form with JavaScript:

<form action="url" method="post">
    <input type="hidden" name="user" value="something" />
    <a href="#">CLick</a>
</form>

<script>
    $('a').click(function(e) {
        e.preventDefault();
        $(this).parents('form').submit();
    });
</script>

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

Swapping two variable value without using third variable

public void swapnumber(int a,int b){
    a = a+b-(b=a);
    System.out.println("a = "+a +" b= "+b);
}

How do I programmatically get the GUID of an application in .NET 2.0

Another way is to use Marshal.GetTypeLibGuidForAssembly.

According to MSDN:

When assemblies are exported to type libraries, the type library is assigned a LIBID. You can set the LIBID explicitly by applying the System.Runtime.InteropServices.GuidAttribute at the assembly level, or it can be generated automatically. The Tlbimp.exe (Type Library Importer) tool calculates a LIBID value based on the identity of the assembly. GetTypeLibGuid returns the LIBID that is associated with the GuidAttribute, if the attribute is applied. Otherwise, GetTypeLibGuidForAssembly returns the calculated value. Alternatively, you can use the GetTypeLibGuid method to extract the actual LIBID from an existing type library.

Extract / Identify Tables from PDF python

You should definitely have a look at this answer of mine:

and also have a look at all the links included therein.

Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.

Update records using LINQ

You have two options as far as I know:

  1. Perform your query, iterate over it to modify the entities, then call SaveChanges().
  2. Execute a SQL command like you mentioned at the top of your question. To see how to do this, take a look at this page.

If you use option 2, you're losing some of the abstraction that the Entity Framework gives you, but if you need to perform a very large update, this might be the best choice for performance reasons.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Debug/run standard java in Visual Studio Code IDE and OS X?

There is a much easier way to run Java, no configuration needed:

  1. Install the Code Runner Extension
  2. Open your Java code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.

runJave

jquery: how to get the value of id attribute?

$('.select_continent').click(function () {
    alert($(this).attr('value'));
});

Line break in HTML with '\n'

You should consider replacing your line breaks with <br/>. In HTML a line break will only stand for new line in your code.

Alternatively you can use some other HTML markups like placing your lines in paragraphs:

<p>Sample line</p>
<p>Another line</p>

or other wrappers like for instance <div>sample</div> with CSS attribute: display: block.

You can also use <pre>. The content of pre will have its HTML styling ignored. In other words it will display pure HTML with normal \n line breaks.

How do I send an HTML Form in an Email .. not just MAILTO

I don't know that what you want to do is possible. From my understanding, sending an email from a web form requires a server side language to communicate with a mail server and send messages.

Are you running PHP or ASP.NET?

ASP.NET Example

PHP Example

How to set the LDFLAGS in CMakeLists.txt?

Look at:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

Check if starting characters of a string are alphabetical in T-SQL

select * from my_table where my_field Like '[a-z][a-z]%'

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

Need to enable Directions API as well in the Google API Console. I have the following enabled:

  • Directions API
  • Geocoding API
  • Maps Javascript API

I also have Geolocation API enabled but the console doesn't show it as being used (0 requests). But maybe it's not real-time reporting so doesn't hurt to enable anyway.

How to add calendar events in Android?

Try this in your code:

Calendar cal = Calendar.getInstance();              
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);

plotting different colors in matplotlib

Joe Kington's excellent answer is already 4 years old, Matplotlib has incrementally changed (in particular, the introduction of the cycler module) and the new major release, Matplotlib 2.0.x, has introduced stylistic differences that are important from the point of view of the colors used by default.

The color of individual lines

The color of individual lines (as well as the color of different plot elements, e.g., markers in scatter plots) is controlled by the color keyword argument,

plt.plot(x, y, color=my_color)

my_color is either

The color cycle

By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).

The color cycle is a property of the axes object, and in older releases was simply a sequence of valid color names (by default a string of one character color names, "bgrcmyk") and you could set it as in

my_ax.set_color_cycle(['kbkykrkg'])

(as noted in a comment this API has been deprecated, more on this later).

In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"], the Vega category10 palette.

enter image description here

(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)

The cycler module: composable cycles

The following code shows that the color cycle notion has been deprecated

In [1]: from matplotlib import rc_params

In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
Out[2]: 
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']

Now the relevant property is the 'axes.prop_cycle'

In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

Previously, the color_cycle was a generic sequence of valid color denominations, now by default it is a cycler object containing a label ('color') and a sequence of valid color denominations. The step forward with respect to the previous interface is that it is possible to cycle not only on the color of lines but also on other line attributes, e.g.,

In [5]: from cycler import cycler

In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])

In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}

As you have seen, the cycler objects are composable and when you iterate on a composed cycler what you get, at each iteration, is a dictionary of keyword arguments for plt.plot.

You can use the new defaults on a per axes object ratio,

my_ax.set_prop_cycle(new_prop_cycle)

or you can install temporarily the new default

plt.rc('axes', prop_cycle=new_prop_cycle)

or change altogether the default editing your .matplotlibrc file.

Last possibility, use a context manager

with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
    ...

to have the new cycler used in a group of different plots, reverting to defaults at the end of the context.

The doc string of the cycler() function is useful, but the (not so much) gory details about the cycler module and the cycler() function, as well as examples, can be found in the fine docs.

SELECT INTO a table variable in T-SQL

Try something like this:

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData (name, oldlocation)
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

How to create a custom attribute in C#

While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:

Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.

So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:

    /// <summary>
    /// blah blah code.
    /// </summary>
    [DataMember]
    [StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
    public string Code { get; set; }

From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.

However, the Enterprise Library has a Validation.Validate method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.

So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.

Add a properties file to IntelliJ's classpath

I have the same problem and it annoys me tremendously!!

I have always thought I was surposed to do as answer 2. That used to work in Intellij 9 (now using 10).

However I figured out that by adding these line to my maven pom file helps:

<build>
  ...
  <resources>
    <resource>
      <directory>src/main/resources</directory>
    </resource>
  </resources>
  ...
</build>

.prop() vs .attr()

attributes are in your HTML text document/file (== imagine this is the result of your html markup parsed), whereas
properties are in HTML DOM tree (== basically an actual property of some object in JS sense).

Importantly, many of them are synced (if you update class property, class attribute in html will also be updated; and otherwise). But some attributes may be synced to unexpected properties - eg, attribute checked corresponds to property defaultChecked, so that

  • manually checking a checkbox will change .prop('checked') value, but will not change .attr('checked') and .prop('defaultChecked') values
  • setting $('#input').prop('defaultChecked', true) will also change .attr('checked'), but this will not be visible on an element.

Rule of thumb is: .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method. (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)

And here is a table that shows where .prop() is preferred (even though .attr() can still be used).

table with preferred usage


Why would you sometimes want to use .prop() instead of .attr() where latter is officially adviced?

  1. .prop() can return any type - string, integer, boolean; while .attr() always returns a string.
  2. .prop() is said to be about 2.5 times faster than .attr().

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I had tried most of the answers here but didn't manage to resolve the issue (on Windows 10).

What resolved the problem was simply to upgrade version from git version 2.8.1.windows.1 to the latest version git version 2.10.1.windows.1

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

How to make a variadic macro (variable number of arguments)

__VA_ARGS__ is the standard way to do it. Don't use compiler-specific hacks if you don't have to.

I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.

How to plot ROC curve in Python

There is a library called metriculous that will do that for you:

$ pip install metriculous

Let's first mock some data, this would usually come from the test dataset and the model(s):

import numpy as np

def normalize(array2d: np.ndarray) -> np.ndarray:
    return array2d / array2d.sum(axis=1, keepdims=True)

class_names = ["Cat", "Dog", "Pig"]
num_classes = len(class_names)
num_samples = 500

# Mock ground truth
ground_truth = np.random.choice(range(num_classes), size=num_samples, p=[0.5, 0.4, 0.1])

# Mock model predictions
perfect_model = np.eye(num_classes)[ground_truth]
noisy_model = normalize(
    perfect_model + 2 * np.random.random((num_samples, num_classes))
)
random_model = normalize(np.random.random((num_samples, num_classes)))

Now we can use metriculous to generate a table with various metrics and diagrams, including ROC curves:

import metriculous

metriculous.compare_classifiers(
    ground_truth=ground_truth,
    model_predictions=[perfect_model, noisy_model, random_model],
    model_names=["Perfect Model", "Noisy Model", "Random Model"],
    class_names=class_names,
    one_vs_all_figures=True, # This line is important to include ROC curves in the output
).save_html("model_comparison.html").display()

The ROC curves in the output: metriculous ROC curves

The plots are zoomable and draggable, and you get further details when hovering with your mouse over the plot:

metriculous ROC curve

Android ListView with different layouts for each row

In your custom array adapter, you override the getView() method, as you presumably familiar with. Then all you have to do is use a switch statement or an if statement to return a certain custom View depending on the position argument passed to the getView method. Android is clever in that it will only give you a convertView of the appropriate type for your position/row; you do not need to check it is of the correct type. You can help Android with this by overriding the getItemViewType() and getViewTypeCount() methods appropriately.

How can I delete Docker's images?

The most compact version of a command to remove all untagged images is:

docker rmi $(docker images | grep "^<none>" | awk '{print $"3"}')

How can I change my Cygwin home folder after installation?

I did something quite simple. I did not want to change the windows 7 environment variable. So I directly edited the Cygwin.bat file.

@echo off
SETLOCAL
set HOME=C:\path\to\home
C:
chdir C:\apps\cygwin\bin
bash --login -i
ENDLOCAL

This just starts the local shell with this home directory; that is what I wanted. I am not going to remotely access this, so this worked for me.

How to access elements of a JArray (or iterate over them)

Update - I verified the below works. Maybe the creation of your JArray isn't quite right.

[TestMethod]
    public void TestJson()
    {
        var jsonString = @"{""trends"": [
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              },
              {
                ""name"": ""#HNCJ"",
                ""url"": ""http://twitter.com/search?q=%23HNCJ"",
                ""promoted_content"": null,
                ""query"": ""%23HNCJ"",
                ""events"": null
              },
              {
                ""name"": ""Boston"",
                ""url"": ""http://twitter.com/search?q=Boston"",
                ""promoted_content"": null,
                ""query"": ""Boston"",
                ""events"": null
              },
              {
                ""name"": ""#prayforboston"",
                ""url"": ""http://twitter.com/search?q=%23prayforboston"",
                ""promoted_content"": null,
                ""query"": ""%23prayforboston"",
                ""events"": null
              },
              {
                ""name"": ""#TheMrsCarterShow"",
                ""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
                ""promoted_content"": null,
                ""query"": ""%23TheMrsCarterShow"",
                ""events"": null
              },
              {
                ""name"": ""#Raw"",
                ""url"": ""http://twitter.com/search?q=%23Raw"",
                ""promoted_content"": null,
                ""query"": ""%23Raw"",
                ""events"": null
              },
              {
                ""name"": ""Iran"",
                ""url"": ""http://twitter.com/search?q=Iran"",
                ""promoted_content"": null,
                ""query"": ""Iran"",
                ""events"": null
              },
              {
                ""name"": ""#gaa"",
                ""url"": ""http://twitter.com/search?q=%23gaa"",
                ""promoted_content"": null,
                ""query"": ""gaa"",
                ""events"": null
              },
              {
                ""name"": ""Facebook"",
                ""url"": ""http://twitter.com/search?q=Facebook"",
                ""promoted_content"": null,
                ""query"": ""Facebook"",
                ""events"": null
              }]}";

        var twitterObject = JToken.Parse(jsonString);
        var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;


        foreach (var item in trendsArray.Children())
        {
            var itemProperties = item.Children<JProperty>();
            //you could do a foreach or a linq here depending on what you need to do exactly with the value
            var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
            var myElementValue = myElement.Value; ////This is a JValue type
        }
    }

So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.

foreach(var item in yourJArray.Children())
{
    var itemProperties = item.Children<JProperty>();
    //you could do a foreach or a linq here depending on what you need to do exactly with the value
    var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
    var myElementValue = myElement.Value; ////This is a JValue type
}

How to add new item to hash

Create the hash:

hash = {:item1 => 1}

Add a new item to it:

hash[:item2] = 2

Find and Replace Inside a Text File from a Bash Command

Be careful if you replace URLs with "/" character.

An example of how to do it:

sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"

Extracted from: http://www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html

KeyListener, keyPressed versus keyTyped

private String message;
private ScreenManager s;


//Here is an example of code to add the keyListener() as suggested; modify 
public void init(){
Window w = s.getFullScreenWindow();
w.addKeyListener(this);

public void keyPressed(KeyEvent e){
    int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_F5)
            message = "Pressed: " + KeyEvent.getKeyText(keyCode);
}

Creating a new directory in C

I want to write a program that (...) creates the directory and a (...) file inside of it

because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.

void rek_mkdir(char *path) {
    char *sep = strrchr(path, '/');
    if(sep != NULL) {
        *sep = 0;
        rek_mkdir(path);
        *sep = '/';
    }
    if(mkdir(path, 0777) && errno != EEXIST)
        printf("error while trying to create '%s'\n%m\n", path); 
}

FILE *fopen_mkdir(char *path, char *mode) {
    char *sep = strrchr(path, '/');
    if(sep) { 
        char *path0 = strdup(path);
        path0[ sep - path ] = 0;
        rek_mkdir(path0);
        free(path0);
    }
    return fopen(path,mode);
}

How to set Oracle's Java as the default Java in Ubuntu?

See this; run

sudo  update-java-alternatives --list

to list off all the Java installations on a machine by name and directory, and then run

sudo  update-java-alternatives --set [JDK/JRE name e.g. java-8-oracle]

to choose which JRE/JDK to use.

If you want to use different JDKs/JREs for each Java task, you can run update-alternatives to configure one java executable at a time; you can run

sudo  update-alternatives --config java[Tab]

to see the Java commands that can be configured (java, javac, javah, javaws, etc). And then

sudo  update-alternatives --config [javac|java|javadoc|etc.]

will associate that Java task/command to a particular JDK/JRE.

You may also need to set JAVA_HOME for some applications: from this answer you can use

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

for JREs, or

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")

for JDKs.

How to convert numbers to words without using num2word library?

I know that this is a very old post and I am probably very late to the party, but hopefully this will help someone else. This has worked for me.

phone_words = input('Phone: ')
numbered_words = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    '5': 'five',
    '6': 'six',
    '7': 'seven',
    '8': 'eight',
    '9': 'nine'
}
output = ""
for ch in phone_words:
    output += numbered_words.get(ch, "!") + " "
phone_words = numbered_words

print(output)

How to add double quotes to a string that is inside a variable?

So you are essentially asking how to store doublequotes within a string variable? Two solutions for that:

var string1 = @"""inside quotes""";
var string2 = "\"inside quotes\"";

In order to perhaps make it a bit more clear what happens:

var string1 = @"before ""inside"" after";
var string2 = "before \"inside\" after";

How to load npm modules in AWS Lambda?

Hope this helps, with Serverless framework you can do something like this:

  1. Add these things in your serverless.yml file:

plugins: - serverless-webpack custom: webpackIncludeModules: forceInclude: - <your package name> (for example: node-fetch) 2. Then create your Lambda function, deploy it by serverless deploy, the package that included in serverless.yml will be there for you.

For more information about serverless: https://serverless.com/framework/docs/providers/aws/guide/quick-start/

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

It all depends on the data at hand. If you have considerable amount of data then 80/20 is a good choice as mentioned above. But if you do not Cross-Validation with a 50/50 split might help you a lot more and prevent you from creating a model over-fitting your training data.

Set View Width Programmatically

You can use something like code below, if you need to affect only specific value, and not touch others:

view.getLayoutParams().width = newWidth;

How do I return multiple values from a function in C?

Option 1: Declare a struct with an int and string and return a struct variable.

struct foo {    
 int bar1;
 char bar2[MAX];
};

struct foo fun() {
 struct foo fooObj;
 ...
 return fooObj;
}

Option 2: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:

int fun(char **param) {
 int bar;
 ...
 strcpy(*param,"....");
 return bar;
}

or

 char* fun(int *param) {
 char *str = /* malloc suitably.*/
 ...
 strcpy(str,"....");
 *param = /* some value */
 return str;
}

Option 3: Similar to the option 2. You can pass both via pointer and return nothing from the function:

void fun(char **param1,int *param2) {
 strcpy(*param1,"....");
 *param2 = /* some calculated value */
}

Using Oracle to_date function for date string with milliseconds

You can try this format SS.FF for milliseconds:

to_timestamp(table_1.date_col,'DD-Mon-RR HH24:MI:SS.FF')

For more details:
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions193.htm

Copy file remotely with PowerShell

Just in case that the remote file needs your credential to get accessed, you can generate a System.Net.WebClient object using cmdlet New-Object to "Copy File Remotely", like so

$Source = "\\192.168.x.x\somefile.txt"
$Dest   = "C:\Users\user\somefile.txt"
$Username = "username"
$Password = "password"

$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)

$WebClient.DownloadFile($Source, $Dest)

Or if you need to upload a file, you can use UploadFile:

$Dest = "\\192.168.x.x\somefile.txt"
$Source   = "C:\Users\user\somefile.txt"

$WebClient.UploadFile($Dest, $Source)

How to update an "array of objects" with Firestore?

#Edit (add explanation :) ) say you have an array you want to update your existing firestore document field with. You can use set(yourData, {merge: true} ) passing setOptions(second param in set function) with {merge: true} is must in order to merge the changes instead of overwriting. here is what the official documentation says about it

An options object that configures the behavior of set() calls in DocumentReference, WriteBatch, and Transaction. These calls can be configured to perform granular merges instead of overwriting the target documents in their entirety by providing a SetOptions with merge: true.

you can use this

const yourNewArray = [{who: "[email protected]", when:timestamp}
{who: "[email protected]", when:timestamp}]    


collectionRef.doc(docId).set(
  {
    proprietary: "jhon",
    sharedWith: firebase.firestore.FieldValue.arrayUnion(...yourNewArray),
  },
  { merge: true },
);

hope this helps :)

Install a module using pip for specific python version

Alternatively, since pip itself is written in python, you can just call it with the python version you want to install the package for:

python2.7 -m pip install foo

What are the applications of binary trees?

They can be used as a quick way to sort data. Insert data into a binary search tree at O(log(n)). Then traverse the tree in order to sort them.

'readline/readline.h' file not found

This command helped me on linux mint when i had exact same problem

gcc filename.c -L/usr/include -lreadline -o filename

You could use alias if you compile it many times Forexample:

alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'

Find kth smallest element in a binary search tree in Optimum way

I couldn't find a better algorithm..so decided to write one :) Correct me if this is wrong.

class KthLargestBST{
protected static int findKthSmallest(BSTNode root,int k){//user calls this function
    int [] result=findKthSmallest(root,k,0);//I call another function inside
    return result[1];
}
private static int[] findKthSmallest(BSTNode root,int k,int count){//returns result[]2 array containing count in rval[0] and desired element in rval[1] position.
    if(root==null){
        int[]  i=new int[2];
        i[0]=-1;
        i[1]=-1;
        return i;
    }else{
        int rval[]=new int[2];
        int temp[]=new int[2];
        rval=findKthSmallest(root.leftChild,k,count);
        if(rval[0]!=-1){
            count=rval[0];
        }
        count++;
        if(count==k){
            rval[1]=root.data;
        }
        temp=findKthSmallest(root.rightChild,k,(count));
        if(temp[0]!=-1){
            count=temp[0];
        }
        if(temp[1]!=-1){
            rval[1]=temp[1];
        }
        rval[0]=count;
        return rval;
    }
}
public static void main(String args[]){
    BinarySearchTree bst=new BinarySearchTree();
    bst.insert(6);
    bst.insert(8);
    bst.insert(7);
    bst.insert(4);
    bst.insert(3);
    bst.insert(4);
    bst.insert(1);
    bst.insert(12);
    bst.insert(18);
    bst.insert(15);
    bst.insert(16);
    bst.inOrderTraversal();
    System.out.println();
    System.out.println(findKthSmallest(bst.root,11));
}

}

How do I get a button to open another activity?

Using an OnClickListener

Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

Button yourButton = (Button) findViewById(R.id.your_buttons_id);

yourButton.setOnClickListener(new OnClickListener(){
    public void onClick(View v){                        
        startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
    }
});

This is probably most developers preferred method. However, there is a common alternative.

Using onClick in XML

Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

public void yourMethodName(View v){
    startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}

Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

References;

Android: checkbox listener

Change RadioGroup group with CompoundButton buttonView and then press Ctrl+Shift+O to fix your imports.

What is the behavior difference between return-path, reply-to and from?

I had to add a Return-Path header in emails send by a Redmine instance. I agree with greatwolf only the sender can determine a correct (non default) Return-Path. The case is the following : E-mails are send with the default email address : [email protected] But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ). We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.

What is the difference between `new Object()` and object literal notation?

There are a lot of great answers here, but I want to come with my 50 cents.

What all of these answers are missing is a simple analogy which would work for a person who just starts his journey in the programming languages.

Hopefully, I will fill this gap with this analogy:

Object Literal Creation vs Constructor-based Syntax

Feel the difference with a sentence creation.

If I have a sentence "I like cheese", I can tell you clearly and loudly (literally, or verbatim): I like cheese.

This is my literal (word by word) creation of the sentence.

All other ways are some tricky ways of making you to understand of what sentence I created exactly. For example, I tell you:

  1. In my sentence, the subject is "I", the object is "cheese", and the predicate is "to like". This is another way of YOU to learn without any ambiguities the very same sentence: "I like cheese".

Or,

  1. My sentence has 3 words: the first one is the n-th word in the English dictionary, the the second one is the m-th word in the English dictionary and the last one is the l-th word in the English dictionary.

In this case, you also come to the same result: you know exactly what the sentence is.

You can devise any other methods which would differ from "word-by-word" sentence creation (LITERAL), and which would be INDIRECT (non literal, non verbatim) method of sentence creation.

I think this is the core concept which lays here.

YouTube iframe embed - full screen

Adding allowfullscreen="allowfullscreen" and altering the type of YouTube embed fixed my issue.

Can I bind an array to an IN() condition?

For something quick:

//$db = new PDO(...);
//$ids = array(...);

$qMarks = str_repeat('?,', count($ids) - 1) . '?';
$sth = $db->prepare("SELECT * FROM myTable WHERE id IN ($qMarks)");
$sth->execute($ids);

error: expected unqualified-id before ‘.’ token //(struct)

ReducedForm is a type, so you cannot say

ReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;

You can only use the . operator on an instance:

ReducedForm rf;
rf.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;

PHP Fatal error: Cannot redeclare class

This error might also occur if you define the __construct method more than once.

How to format a float in javascript?

There is no way to avoid inconsistent rounding for prices with x.xx5 as actual value using either multiplication or division. If you need to calculate correct prices client-side you should keep all amounts in cents. This is due to the nature of the internal representation of numeric values in JavaScript. Notice that Excel suffers from the same problems so most people wouldn't notice the small errors caused by this phenomen. However errors may accumulate whenever you add up a lot of calculated values, there is a whole theory around this involving the order of calculations and other methods to minimize the error in the final result. To emphasize on the problems with decimal values, please note that 0.1 + 0.2 is not exactly equal to 0.3 in JavaScript, while 1 + 2 is equal to 3.

Why use Gradle instead of Ant or Maven?

I agree partly with Ed Staub. Gradle definitely is more powerful compared to maven and provides more flexibility long term.

After performing an evaluation to move from maven to gradle, we decided to stick to maven itself for two issues we encountered with gradle ( speed is slower than maven, proxy was not working ) .

Remove title in Toolbar in appcompat-v7

this

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    //toolbar.setNavigationIcon(R.drawable.ic_toolbar);
    toolbar.setTitle("");
    toolbar.setSubtitle("");
    //toolbar.setLogo(R.drawable.ic_toolbar);

Select all elements with a "data-xxx" attribute without using jQuery

document.querySelectorAll("[data-foo]")

will get you all elements with that attribute.

document.querySelectorAll("[data-foo='1']")

will only get you ones with a value of 1.

How to extend available properties of User.Identity

For anyone that finds this question looking for how to access custom properties in ASP.NET Core 2.1 - it's much easier: You'll have a UserManager, e.g. in _LoginPartial.cshtml, and then you can simply do (assuming "ScreenName" is a property that you have added to your own AppUser which inherits from IdentityUser):

@using Microsoft.AspNetCore.Identity

@using <namespaceWhereYouHaveYourAppUser>

@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager

@if (SignInManager.IsSignedIn(User)) {
    <form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })" 
          method="post" id="logoutForm" 
          class="form-inline my-2 my-lg-0">

        <ul class="nav navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">
                    Hello @((await UserManager.GetUserAsync(User)).ScreenName)!
                    <!-- Original code, shows Email-Address: @UserManager.GetUserName(User)! -->
                </a>
            </li>
            <li class="nav-item">
                <button type="submit" class="btn btn-link nav-item navbar-link nav-link">Logout</button>
            </li>
        </ul>

    </form>
} else {
    <ul class="navbar-nav ml-auto">
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Register">Register</a></li>
        <li class="nav-item"><a class="nav-link" asp-area="Identity" asp-page="/Account/Login">Login</a></li>
    </ul>
}

Cannot convert lambda expression to type 'string' because it is not a delegate type

If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.

Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.

In your case it could be :

objContentLine = (from q in db.qryContents
                  where q.LineID == Value
                  orderby q.RowID descending
                  select q).FirstOrDefault();

Errors:

Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type

Error 242 Delegate 'System.Func<..>' does not take 1 arguments

Error 243 The name 'Value' does not exist in the current context

Fix the "Value" variable error and the other errors will also disappear.

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

This is intended behavior.

When you make an HTTP request, the server normally returns code 200 OK. If you set If-Modified-Since, the server may return 304 Not modified (and the response will not have the content). This is supposed to be your cue that the page has not been modified.

The authors of the class have foolishly decided that 304 should be treated as an error and throw an exception. Now you have to clean up after them by catching the exception every time you try to use If-Modified-Since.

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

How to skip the first n rows in sql query

For SQL Server 2012 and later versions, the best method is @MajidBasirati's answer.

I also loved @CarlosToledo's answer, it's not limited to any SQL Server version but it's missing Order By Clauses. Without them, it may return wrong results.

For SQL Server 2008 and later I would use Common Table Expressions for better performance.

-- This example omits first 10 records and select next 5 records
;WITH MyCTE(Id) as
(
    SELECT TOP (10) Id 
    FROM MY_TABLE
    ORDER BY Id
)
SELECT TOP (5) * 
FROM MY_TABLE
    INNER JOIN MyCTE ON (MyCTE.Id <> MY_TABLE.Id) 
ORDER BY Id

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

For those who have the following error:

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

You can simply run this command to see which folder can load files from:

SHOW VARIABLES LIKE "secure_file_priv";

After that, you have to copy the files in that folder and run the query with LOAD DATA LOCAL INFILE instead of LOAD DATA INFILE.

How do you upload a file to a document library in sharepoint?

string filePath = @"C:\styles\MyStyles.css"; 
string siteURL = "http://example.org/"; 
string libraryName = "Style Library"; 

using (SPSite oSite = new SPSite(siteURL)) 
{ 
    using (SPWeb oWeb = oSite.OpenWeb()) 
    { 
        if (!System.IO.File.Exists(filePath)) 
            throw new FileNotFoundException("File not found.", filePath);                     

        SPFolder libFolder = oWeb.Folders[libraryName]; 

        // Prepare to upload 
        string fileName = System.IO.Path.GetFileName(filePath); 
        FileStream fileStream = File.OpenRead(filePath); 

        //Check the existing File out if the Library Requires CheckOut
        if (libFolder.RequiresCheckout)
        {
            try {
                SPFile fileOld = libFolder.Files[fileName];
                fileOld.CheckOut();
            } catch {}
        }

        // Upload document 
        SPFile spfile = libFolder.Files.Add(fileName, fileStream, true); 

        // Commit  
        myLibrary.Update(); 

        //Check the File in and Publish a Major Version
        if (libFolder.RequiresCheckout)
        {
                spFile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
                spFile.Publish("Publish Comment");
        }
    } 
} 

Bash: Strip trailing linebreak from output

If you assign its output to a variable, bash automatically strips whitespace:

linecount=`wc -l < log.txt`

WebView link click open default browser

I had to do the same thing today and I have found a very useful answer on StackOverflow that I want to share here in case someone else needs it.

Source (from sven)

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
            view.getContext().startActivity(
                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
});

How to get a string between two characters?

String result = s.substring(s.indexOf("(") + 1, s.indexOf(")"));

Adding local .aar files to Gradle build using "flatDirs" is not working

Edit: The correct way (currently) to use a local AAR file as a build dependency is to use the module import wizard (File | New Module | Import .JAR or .AAR package) which will automatically add the .aar as a library module in your project.

Old Answer

Try this:

allprojects {
  repositories {
    jcenter()
    flatDir {
      dirs 'libs'
    }
  }
}

...

compile(name:'slidingmenu', ext:'aar')

TypeError: 'str' object is not callable (Python)

This is the problem:

global str

str = str(mar)

You are redefining what str() means. str is the built-in Python name of the string type, and you don't want to change it.

Use a different name for the local variable, and remove the global statement.

Self-reference for cell, column and row in worksheet functions

Just for row, but try referencing a cell just below the selected cell and subtracting one from row.

=ROW(A2)-1

Yields the Row of cell A1 (This formula would go in cell A1.

This avoids all the indirect() and index() use but still works.

How do I parse JSON in Android?

Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.

Get your JSON:

Assume you have a json string

String result = "{\"someKey\":\"someValue\"}";

Create a JSONObject:

JSONObject jObject = new JSONObject(result);

If your json string is an array, e.g.:

String result = "[{\"someKey\":\"someValue\"}]"

then you should use JSONArray as demonstrated below and not JSONObject

To get a specific string

String aJsonString = jObject.getString("STRINGNAME");

To get a specific boolean

boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");

To get a specific integer

int aJsonInteger = jObject.getInt("INTEGERNAME");

To get a specific long

long aJsonLong = jObject.getLong("LONGNAME");

To get a specific double

double aJsonDouble = jObject.getDouble("DOUBLENAME");

To get a specific JSONArray:

JSONArray jArray = jObject.getJSONArray("ARRAYNAME");

To get the items from the array

for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
        String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
    } catch (JSONException e) {
        // Oops
    }
}

How to convert string to boolean in typescript Angular 4

I have been trying different values with JSON.parse(value) and it seems to do the work:

// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));

// false
Boolean(JSON.parse("0")); 
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));

Javascript Regular Expression Remove Spaces

str.replace(/\s/g,'')

Works for me.

jQuery.trim has the following hack for IE, although I'm not sure what versions it affects:

// Check if a string has a non-whitespace character in it
rnotwhite = /\S/

// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
    trimLeft = /^[\s\xA0]+/;
    trimRight = /[\s\xA0]+$/;
}

What does it mean to "call" a function in Python?

when you invoke a function , it is termed 'calling' a function . For eg , suppose you've defined a function that finds the average of two numbers like this-

def avgg(a,b) :
        return (a+b)/2;

now, to call the function , you do like this .

x=avgg(4,6)
print x

value of x will be 5 .

SQL "IF", "BEGIN", "END", "END IF"?

Off hand the code looks right. What if you try using an 'Else' and see what happens?

IF @SchoolCategoryCode = 'Elem' 

--- We now have determined we are processing an elementary school...

BEGIN

---- Only do the following if the variable @Term equals a 3 - if it does not, skip just this first part

    IF @Term = 3
    BEGIN
        INSERT INTO @Classes

        SELECT              
            XXXXXX  
        FROM XXXX blah blah blah

        INSERT INTO @Classes    
        SELECT
        XXXXXXXX    
        FROM XXXXXX (more code) 
    END   <----(Should this be ENDIF?)
    ELSE
    BEGIN


        INSERT INTO @Classes    
        SELECT
        XXXXXXXX    
        FROM XXXXXX (more code) 
    END
END

Android ListView Text Color

if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.

ADD android:theme="@style/AppTheme" in Android Manifest.

Filter data.frame rows by a logical condition

I was working on a dataframe and having no luck with the provided answers, it always returned 0 rows, so I found and used grepl:

df = df[grepl("downlink",df$Transmit.direction),]

Which basically trimmed my dataframe to only the rows that contained "downlink" in the Transmit direction column. P.S. If anyone can guess as to why I'm not seeing the expected behavior, please leave a comment.

Specifically to the original question:

expr[grepl("hesc",expr$cell_type),]

expr[grepl("bj fibroblast|hesc",expr$cell_type),]

Converting string to Date and DateTime

If you wish to accept dates using American ordering (month, date, year) for European style formats (using dash or period as day, month, year) while still accepting other formats, you can extend the DateTime class:

/**
 * Quietly convert European format to American format
 *
 * Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
 * as well as all other built-in formats
 * 
 */
class CustomDateTime extends DateTime 
{
  public function __construct(string $time="now", DateTimeZone $timezone = null) 
  {
    // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
    $time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );

    parent::__construct($time, $timezone);
  }
}

// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');

// => '2019-07-24'

Or, you can make a function to accept m-d-Y and output Y-m-d:

/**
 * Accept dates in various m, d, y formats and return as Y-m-d
 * 
 * Changes PHP's default behaviour for dates with dashes or dots.
 * Accepts:
 *   m-d-y, m-d-Y, Y-m-d,
 *   m.d.y, m.d.Y, Y.m.d,
 *   m/d/y, m/d/Y, Y/m/d,
 *   ... and all other formats natively supported 
 * 
 * Unsupported formats or invalid dates will generate an Exception
 * 
 * @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
 * @param  string $d various representations of date
 * @return string    Y-m-d or '----' for null or blank
 */
function asYmd($d) {
  if(is_null($d) || $d=='') { return '----'; }

  // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
  $d = str_replace(['-','.'], '/', $d);

  return (new DateTime($d))->format('Y-m-d');
}

// usage:

<?= asYmd('7-24-2019') ?>

// or

<?php echo asYmd('7-24-2019'); ?>

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I believe that this is a bug in the current Google Play Services library, revision 15, as the underlying cause appears to be caused by failing to read a resource file:

W/ResourceType(25122): Requesting resource 0x7f0c000d failed because it is complex
E/GooglePlayServicesUtil(25122): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.

It seems that the Google Play Services library attempts to read a resource file and has a generic catch-all that displays this error message when the resource fails to load. This corresponds with what kreker managed to decompile from the library and would explain the log messages.

Google Maps V3 - How to calculate the zoom level for a given bounds

A similar question has been asked on the Google group: http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/e6448fc197c3c892

The zoom levels are discrete, with the scale doubling in each step. So in general you cannot fit the bounds you want exactly (unless you are very lucky with the particular map size).

Another issue is the ratio between side lengths e.g. you cannot fit the bounds exactly to a thin rectangle inside a square map.

There's no easy answer for how to fit exact bounds, because even if you are willing to change the size of the map div, you have to choose which size and corresponding zoom level you change to (roughly speaking, do you make it larger or smaller than it currently is?).

If you really need to calculate the zoom, rather than store it, this should do the trick:

The Mercator projection warps latitude, but any difference in longitude always represents the same fraction of the width of the map (the angle difference in degrees / 360). At zoom zero, the whole world map is 256x256 pixels, and zooming each level doubles both width and height. So after a little algebra we can calculate the zoom as follows, provided we know the map's width in pixels. Note that because longitude wraps around, we have to make sure the angle is positive.

var GLOBE_WIDTH = 256; // a constant in Google's map projection
var west = sw.lng();
var east = ne.lng();
var angle = east - west;
if (angle < 0) {
  angle += 360;
}
var zoom = Math.round(Math.log(pixelWidth * 360 / angle / GLOBE_WIDTH) / Math.LN2);

Summarizing multiple columns with dplyr?

The dplyr package contains summarise_all for this aim:

library(dplyr)
# summarise_all was replaced with the summarise(acrosss(..)) syntax dplyr >=1.00
df %>% group_by(grp) %>% summarise(across(everything(), list(mean)))
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Alternatively, the purrrlyr package provides the same functionality:

library(purrrlyr)
df %>% slice_rows("grp") %>% dmap(mean)
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Also don't forget about data.table (use keyby to sort sort groups):

library(data.table)
setDT(df)[, lapply(.SD, mean), keyby = grp]
#>    grp        a        b        c        d
#> 1:   1 3.079412 2.979412 2.979412 2.914706
#> 2:   2 3.029126 3.038835 2.967638 2.873786
#> 3:   3 2.854701 2.948718 2.951567 3.062678

Let's try to compare performance.

library(dplyr)
library(purrrlyr)
library(data.table)
library(bench)
set.seed(123)
n <- 10000
df <- data.frame(
  a = sample(1:5, n, replace = TRUE), 
  b = sample(1:5, n, replace = TRUE), 
  c = sample(1:5, n, replace = TRUE), 
  d = sample(1:5, n, replace = TRUE), 
  grp = sample(1:3, n, replace = TRUE)
)
dt <- setDT(df)
mark(
  dplyr = df %>% group_by(grp) %>% summarise(across(everything(), list(mean))),
  purrrlyr = df %>% slice_rows("grp") %>% dmap(mean),
  data.table = dt[, lapply(.SD, mean), keyby = grp],
  check = FALSE
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 dplyr        2.81ms   2.85ms      328.        NA     17.3
#> 2 purrrlyr     7.96ms   8.04ms      123.        NA     24.5
#> 3 data.table 596.33µs 707.91µs     1409.        NA     10.3

AngularJS - Animate ng-view transitions

I'm not sure about a way to do it directly with AngularJS but you could set the display to none for both welcome and login and animate the opacity with an directive once they are loaded.

I would do it some way like so. 2 Directives for fading in the content and fading it out when a link is clicked. The directive for fadeouts could simply animate a element with an unique ID or call a service which broadcasts the fadeout

Template:

<div class="tmplWrapper" onLoadFadeIn>
    <a href="somewhere/else" fadeOut>
</div>

Directives:

angular
  .directive('onLoadFadeIn', ['Fading', function('Fading') {
    return function(scope, element, attrs) {
      $(element).animate(...);
      scope.$on('fading', function() {
    $(element).animate(...);
      });
    }
  }])
  .directive('fadeOut', function() {
    return function(scope, element, attrs) {
      element.bind('fadeOut', function(e) {
    Fading.fadeOut(e.target);
  });
    }
  });

Service:

angular.factory('Fading', function() {
  var news;
  news.setActiveUnit = function() {
    $rootScope.$broadcast('fadeOut');
  };
  return news;
})

I just have put together this code quickly so there may be some bugs :)

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

Here's a plain JavaScript version:

function scroll(e) {
  var delta = (e.type === "mousewheel") ? e.wheelDelta : e.detail * -40;
  if (delta < 0 && (this.scrollHeight - this.offsetHeight - this.scrollTop) <= 0) {
    this.scrollTop = this.scrollHeight;
    e.preventDefault();
  } else if (delta > 0 && delta > this.scrollTop) {
    this.scrollTop = 0;
    e.preventDefault();
  }
}
document.querySelectorAll(".scroller").addEventListener("mousewheel", scroll);
document.querySelectorAll(".scroller").addEventListener("DOMMouseScroll", scroll);

Convert floating point number to a certain precision, and then copy to string

It's not print that does the formatting, It's a property of strings, so you can just use

newstring = "%.9f" % numvar

Pyspark: Exception: Java gateway process exited before sending the driver its port number

I figured out the problem in Windows system. The installation directory for Java must not have blanks in the path such as in C:\Program Files. I re-installed Java in C\Java. I set JAVA_HOME to C:\Java and the problem went away.

DB query builder toArray() laravel 4

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);

How to set a Postgresql default value datestamp like 'YYYYMM'?

Why would you want to do this?

IMHO you should store the date as default type and if needed fetch it transforming to desired format.

You could get away with specifying column's format but with a view. I don't know other methods.

Edited:

Seriously, in my opinion, you should create a view on that a table with date type. I'm talking about something like this:

create table sample_table ( id serial primary key, timestamp date); 

and than

create view v_example_table as select id, to_char(date, 'yyyymmmm');

And use v_example_table in your application.

SQL query to group by day

if you're using SQL Server,

dateadd(DAY,0, datediff(day,0, created)) will return the day created

for example, if the sale created on '2009-11-02 06:12:55.000', dateadd(DAY,0, datediff(day,0, created)) return '2009-11-02 00:00:00.000'

select sum(amount) as total, dateadd(DAY,0, datediff(day,0, created)) as created
from sales
group by dateadd(DAY,0, datediff(day,0, created))

How to view transaction logs in SQL Server 2008

You can't read the transaction log file easily because that's not properly documented. There are basically two ways to do this. Using undocumented or semi-documented database functions or using third-party tools.

Note: This only makes sense if your database is in full recovery mode.

SQL Functions:

DBCC LOG and fn_dblog - more details here and here.

Third-party tools:

Toad for SQL Server and ApexSQL Log.

You can also check out several other topics where this was discussed:

How to change angular port from 4200 to any other

Just Run

ng serve --port yourport

Example:

ng serve --port 4401

How do I run git log to see changes only for a specific branch?

If you want only those commits which are done by you in a particular branch, use the below command.

git log branch_name --author='Dyaniyal'

Link to Flask static files with url_for

You have by default the static endpoint for static files. Also Flask application has the following arguments:

static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.

static_folder: the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default:

url_for('static', filename='path/to/file')

will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file.

So if you want to get files from the static/bootstrap folder you use this code:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

Which will be converted to (using default settings):

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

Also look at url_for documentation.

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

When you are releasing signed apk , please make sure you tick both v1 and v2 in signature versions

See below screenshot for more info Signed APK generation

iterating through Enumeration of hastable keys throws NoSuchElementException error

You're calling nextElement twice in the loop. You should call it only once, else it moves ahead twice:

while(e.hasMoreElements()){
    String s = e.nextElement();
    System.out.println(s);
}

CSS list-style-image size

I'm using:

_x000D_
_x000D_
li {_x000D_
 margin: 0;_x000D_
 padding: 36px 0 36px 84px;_x000D_
 list-style: none;_x000D_
 background-image: url("../../images/checked_red.svg");_x000D_
 background-repeat: no-repeat;_x000D_
 background-position: left center;_x000D_
 background-size: 40px;_x000D_
}
_x000D_
_x000D_
_x000D_

where background-size set the background image size.

How to securely save username/password (local)?

This only works on Windows, so if you are planning to use dotnet core cross-platform, you'll have to look elsewhere. See https://github.com/dotnet/corefx/blob/master/Documentation/architecture/cross-platform-cryptography.md

C# Pass Lambda Expression as Method Parameter

Use a Func<T1, T2, TResult> delegate as the parameter type and pass it in to your Query:

public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
  using (SqlConnection connection = new SqlConnection(getConnectionString())) {
    connection.Open();
    return connection.Query<FullTimeJob, Student, FullTimeJob>(sql, 
        lambda,
        splitOn: "user_id",
        param: parameters).ToList<IJob>();   
  }  
}

You would call it:

getJobs((job, student) => {         
        job.Student = student;
        job.StudentId = student.Id;
        return job;
        });

Or assign the lambda to a variable and pass it in.

How to check if that data already exist in the database during update (Mongoose And Express)

Here is another way to accomplish this in less code.

UPDATE 3: Asynchronous model class statics

Similar to option 2, this allows you to create a function directly linked to the schema, but called from the same file using the model.

model.js

 userSchema.statics.updateUser = function(user, cb) {
  UserModel.find({name : user.name}).exec(function(err, docs) {
    if (docs.length){
      cb('Name exists already', null);
    } else {
      user.save(function(err) {
        cb(err,user);
      }
    }
  });
}

Call from file

var User = require('./path/to/model');

User.updateUser(user.name, function(err, user) {
  if(err) {
    var error = new Error('Already exists!');
    error.status = 401;
    return next(error);
  }
});

background: fixed no repeat not working on mobile

I've been having the same problem, but now it works. All I had to do was add background-size: cover !important; and it works on my Android device!

The entire code looks like this:

body.page-id-8 #art-main {
  background: #000000 url("link to image") !important;
  background-repeat: no-repeat !important;
  background-position: 50% 50% !important;
  background-attachment: fixed !important;
  background-color: transparent !important;
  background-size: cover !important;
}

Thanks a lot @taylan derinbay and @Vincent!

Why do we need the "finally" clause in Python?

To add to the other answers above, the finally clause executes no matter what whereas the else clause executes only if an exception was not raised.

For example, writing to a file with no exceptions will output the following:

file = open('test.txt', 'w')

try:
    file.write("Testing.")
    print("Writing to file.")
except IOError:
    print("Could not write to file.")
else:
    print("Write successful.")
finally:
    file.close()
    print("File closed.")

OUTPUT:

Writing to file.
Write successful.
File closed.

If there is an exception, the code will output the following, (note that a deliberate error is caused by keeping the file read-only.

file = open('test.txt', 'r')

try:
    file.write("Testing.")
    print("Writing to file.")
except IOError:
    print("Could not write to file.")
else:
    print("Write successful.")
finally:
    file.close()
    print("File closed.")

OUTPUT:

Could not write to file.
File closed.

We can see that the finally clause executes regardless of an exception. Hope this helps.

Convert a object into JSON in REST service by Spring MVC

Another simple solution is to add jackson-databind dependency in POM.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>

Keep Rest of the code as it is.

Using the last-child selector

As an alternative to using a class you could use a detailed list, setting the child dt elements to have one style and the child dd elements to have another. Your example would become:

#refundReasonMenu #nav li:dd
{
  border-bottom: 1px solid #b5b5b5;
}

html:

<div id="refundReasonMenu">
  <dl id="nav">
        <dt><a id="abc" href="#">abcde</a></dt>
        <dd><a id="def" href="#">xyz</a></dd>
  </dl>
</div>

Neither method is better than the other and it is just down to personal preference.

"Debug certificate expired" error in Eclipse Android plugins

  • WINDOWS

Delete: debug.keystore located in C:\Documents and Settings\\[user]\.android, Clean and build your project.

  • Windows 7 go to C:\Users\[username]\.android and delete debug.keystore file.

Clean and build your project.

  • MAC

Delete your keystore located in ~/.android/debug.keystore Clean and build your project.

In all the options if you can´t get the new debug.keystore just restart eclipse.

Better way to find control in ASP.NET

Late as usual. If anyone is still interested in this there are a number of related SO questions and answers. My version of recursive extension method for resolving this:

public static IEnumerable<T> FindControlsOfType<T>(this Control parent)
                                                        where T : Control
{
    foreach (Control child in parent.Controls)
    {
        if (child is T)
        {
            yield return (T)child;
        }
        else if (child.Controls.Count > 0)
        {
            foreach (T grandChild in child.FindControlsOfType<T>())
            {
                yield return grandChild;
            }
        }
    }
}

How can I wait for 10 second without locking application UI in android

do this on a new thread (seperate it from main thread)

 new Thread(new Runnable() {
     @Override
     public void run() {
        // TODO Auto-generated method stub
     }
}).run();

How to create temp table using Create statement in SQL Server?

Same thing, Just start the table name with # or ##:

CREATE TABLE #TemporaryTable          -- Local temporary table - starts with single #
(
    Col1 int,
    Col2 varchar(10)
    ....
);

CREATE TABLE ##GlobalTemporaryTable   -- Global temporary table - note it starts with ##.
(
    Col1 int,
    Col2 varchar(10)
    ....
);

Temporary table names start with # or ## - The first is a local temporary table and the last is a global temporary table.

Here is one of many articles describing the differences between them.

CSS: Center block, but align contents to the left

First, create a parent div that centers its child content with text-align: center. Next, create a child div that uses display: inline-block to adapt to the width of its children and text-align: left to make the content it holds align to the left as desired.

_x000D_
_x000D_
<div style="text-align: center;">_x000D_
    <div style="display: inline-block; text-align: left;">_x000D_
        Centered<br />_x000D_
        Content<br />_x000D_
        That<br />_x000D_
        Is<br />_x000D_
        Left<br />_x000D_
        Aligned_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Generics in C#, using type of a variable as parameter

You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.

In other words, after compilation,

DoesEntityExist<int>

is a different type to

DoesEntityExist<string>

This is how the compiler is able to enfore compile-time type safety.

For the scenario you describe, you should pass the type as an argument that can be examined at run time.

The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

This should do it for you.

<div id="nav-wrap">
    <ul id="nav">
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </ul>
</div>

#nav-wrap {
    float: left;
    height: 87px;
    width: 900px;
}

#nav {
    display: inline;
    height: 87px;
    width: 100%;
}

.nav-item {
    float: left;
    height: 87px;
    line-height: 87px;
    text-align: center;
    text-decoration: none;
    width: 150px;

}

Failed to authenticate on SMTP server error using gmail

This is how I solved this issue:

  1. Change the .env file as follow

Screenshot Reference

  1. Never forget to restart the server after you change the .env file

Size of character ('a') in C/C++

In C, the type of a character constant like 'a' is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1. This is one of many small differences between the two languages.

How to generate different random numbers in a loop in C++?

I had this same problem for days. Keeping srand() out of the loop is a +. Also, dont assign rand() % 100 to any variable. Simply cout rand() % 100 in the loop. Try this:

    srand (time(NULL));
    (int t=0;t<10;t++)
    {
    cout << rand() % 100 << endl;
    } 

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

MVC 4 - how do I pass model data to a partial view?

You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>(). Try this:

@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
    </div>
</div>

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

How to disable 'X-Frame-Options' response header in Spring Security?

If you're using Spring Boot, the simplest way to disable the Spring Security default headers is to use security.headers.* properties. In particular, if you want to disable the X-Frame-Options default header, just add the following to your application.properties:

security.headers.frame=false

There is also security.headers.cache, security.headers.content-type, security.headers.hsts and security.headers.xss properties that you can use. For more information, take a look at SecurityProperties.

Getting the base url of the website and globally passing it to twig in Symfony 2

Base url is defined inside Symfony\Component\Routing\RequestContext.

It can be fetched from controller like this:

$this->container->get('router')->getContext()->getBaseUrl()

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

Chrome: Uncaught SyntaxError: Unexpected end of input

See my case on another similar question:

In my case, I was trying to parse an empty JSON:

JSON.parse(stringifiedJSON);

In other words, what happened was the following:

JSON.parse("");

How can you get the Manifest Version number from the App's (Layout) XML variables?

Late to the game, but you can do it without @string/xyz by using ?android:attr

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="?android:attr/versionName"
     />
    <!-- or -->
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="?android:attr/versionCode"
     />

How to remove an item from an array in Vue.js

Why not just omit the method all together like:

v-for="(event, index) in events"
...
<button ... @click="$delete(events, index)">

Blocking device rotation on mobile web pages

New API's are developing (and are currently available)!

screen.orientation.lock();   // webkit only

and

screen.lockOrientation("orientation");

Where "orientation" can be any of the following:

portrait-primary - It represents the orientation of the screen when it is in its primary portrait mode. A screen is considered in its primary portrait mode if the device is held in its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held turned by 90° clockwise. The normal position is device dependant.

portrait-secondary - It represents the orientation of the screen when it is in its secondary portrait mode. A screen is considered in its secondary portrait mode if the device is held 180° from its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held is turned by 90° anticlockwise. The normal position is device dependant.

landscape-primary - It represents the orientation of the screen when it is in its primary landscape mode. A screen is considered in its primary landscape mode if the device is held in its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° clockwise. The normal position is device dependant.

landscape-secondary - It represents the orientation of the screen when it is in its secondary landscape mode. A screen is considered in its secondary landscape mode if the device held is 180° from its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° anticlockwise. The normal position is device dependant.

portrait - It represents both portrait-primary and portrait-secondary.

landscape - It represents both landscape-primary and landscape-secondary.

default - It represents either portrait-primary and landscape-primary depends on natural orientation of devices. For example, if the panel resolution is 1280*800, default will make it landscape, if the resolution is 800*1280, default will make it to portrait.

Mozilla recommends adding a lockOrientationUniversal to screen to make it more cross-browser compatible.

screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;

Go here for more info: https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation

WPF: Grid with column/row margin/padding?

Use a Border control outside the cell control and define the padding for that:

    <Grid>
        <Grid.Resources >
            <Style TargetType="Border" >
                <Setter Property="Padding" Value="5,5,5,5" />
            </Style>
        </Grid.Resources>

        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <Border Grid.Row="0" Grid.Column="0">
            <YourGridControls/>
        </Border>
        <Border Grid.Row="1" Grid.Column="0">
            <YourGridControls/>
        </Border>

    </Grid>


Source:

What are C++ functors and their uses?

Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.

Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy functor that multiplies its argument by a specified amount:

class MultiplyBy {
private:
    int factor;

public:
    MultiplyBy(int x) : factor(x) {
    }

    int operator () (int other) const {
        return factor * other;
    }
};

Then you could pass a MultiplyBy object to an algorithm like std::transform:

int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}

Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.

Swift Set to Array

ADDITION :

Swift has no DEFINED ORDER for Set and Dictionary.For that reason you should use sorted() method to prevent from getting unexpected results such as your array can be like ["a","b"] or ["b","a"] and you do not want this.

TO FIX THIS:

FOR SETS

var example:Set = ["a","b","c"]
let makeExampleArray = [example.sorted()]
makeExampleArray 

Result: ["a","b","c"]

Without sorted()

It can be:

["a","b","c"] or ["b","c","a",] or ["c","a","b"] or ["a","c","b"] or ["b","a","c"] or ["c","b","a"] 

simple math : 3! = 6

Confirm Password with jQuery Validate

I'm implementing it in Play Framework and for me it worked like this:

1) Notice that I used data-rule-equalTo in input tag for the id inputPassword1. The code section of userform in my Modal:

<div class="form-group">
    <label for="pass1">@Messages("authentication.password")</label>
    <input class="form-control required" id="inputPassword1" placeholder="@Messages("authentication.password")" type="password" name="password" maxlength=10 minlength=5>
</div>
<div class="form-group">
    <label for="pass2">@Messages("authentication.password2")</label>
    <input class="form-control required" data-rule-equalTo="#inputPassword1" id="inputPassword2" placeholder="@Messages("authentication.password")" type="password" name="password2">
</div>

2)Since I used validator within a Modal

$(document).on("click", ".createUserModal", function () {
       $(this).find('#userform').validate({
           rules: {
               firstName: "required",
               lastName: "required",
               nationalId: {
                   required: true,
                   digits:true
               },
               email: {
                   required: true,
                   email: true
               },
               optradio: "required",
               password :{
                   required: true,
                   minlength: 5
               },
               password2: {
                   required: true
               }
           },
           highlight: function (element) {
               $(element).parent().addClass('error')
           },
           unhighlight: function (element) {
               $(element).parent().removeClass('error')
           },
           onsubmit: true
       });

   });

Hope it helps someone :).

Location for session files in Apache/PHP

Another common default location besides /tmp/ is /var/lib/php5/

Faster way to zero memory than with memset?

memset could be inlined by compiler as a series of efficient opcodes, unrolled for a few cycles. For very large memory blocks, like 4000x2000 64bit framebuffer, you can try optimizing it across several threads (which you prepare for that sole task), each setting its own part. Note that there is also bzero(), but it is more obscure, and less likely to be as optimized as memset, and the compiler will surely notice you pass 0.

What compiler usually assumes, is that you memset large blocks, so for smaller blocks it would likely be more efficient to just do *(uint64_t*)p = 0, if you init large number of small objects.

Generally, all x86 CPUs are different (unless you compile for some standardized platform), and something you optimize for Pentium 2 will behave differently on Core Duo or i486. So if you really into it and want to squeeze the last few bits of toothpaste, it makes sense to ship several versions your exe compiled and optimized for different popular CPU models. From personal experience Clang -march=native boosted my game's FPS from 60 to 65, compared to no -march.

Send auto email programmatically

Referred link has correct answer, but there are written some libraries to make your work easy.

So don't write all code again, just use any of these library and get your work done in little time.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Link to all Visual Studio $ variables

Anybody working on legacy software using Visual Studio 6.0 will find that $(Configuration) and $(ProjectDir) macro's are not defined. For post-build/pre-build events, give a relative path starting with the location of your .dsw file(workspace) as the starting point. In relative path dot represents the current directory and .. represents the parent directory. Give a relative path to the file that need to be processed. Example: ( copy /y .\..\..\Debug\mylib.dll .\..\MyProject\Debug\ )

How to read a list of files from a folder using PHP?

If you have problems with accessing to the path, maybe you need to put this:

$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/"; 

// Open the folder
 $dir_handle = @opendir($root . $path) or die("Unable to open $path");

String in function parameter

Inside the function parameter list, char arr[] is absolutely equivalent to char *arr, so the pair of definitions and the pair of declarations are equivalent.

void function(char arr[]) { ... }
void function(char *arr)  { ... }

void function(char arr[]);
void function(char *arr);

The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.

Treat string literals as if they were static const char literal[] = "string literal"; and do not attempt to modify them.

How to convert an Array to a Set in Java

Quickly : you can do :

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

and to reverse

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

Add Insecure Registry to Docker

Anyone looking to add insecure registry on amazon linux 2: You will have to change the setting under /etc/sysconfig/docker and then restart docker daemon: here's how my /etc/sysconfig/docker looks like

# The max number of open files for the daemon itself, and all
# running containers.  The default value of 1048576 mirrors the value
# used by the systemd service unit.
DAEMON_MAXFILES=1048576

# Additional startup options for the Docker daemon, for example:
# OPTIONS="--ip-forward=true --iptables=true"
# By default we limit the number of open files per container
OPTIONS="--default-ulimit nofile=1024:4096 --insecure-registry yourinsecureregistryhostname:port"

# How many seconds the sysvinit script waits for the pidfile to appear
# when starting the daemon.
DAEMON_PIDFILE_TIMEOUT=10

how to delete all cookies of my website in php

All previous answers have overlooked that the setcookie could have been used with an explicit domain. Furthermore, the cookie might have been set on a higher subdomain, e.g. if you were on a foo.bar.tar.com domain, there might be a cookie set on tar.com. Therefore, you want to unset cookies for all domains that might have dropped the cookie:

$host = explode('.', $_SERVER['HTTP_HOST']);

while ($host) {
    $domain = '.' . implode('.', $host);

    foreach ($_COOKIE as $name => $value) {
        setcookie($name, '', 1, '/', $domain);
    }

    array_shift($host);
}

How do I clone a generic List in Java?

I am not a java professional, but I have the same problem and I tried to solve by this method. (It suppose that T has a copy constructor).

 public static <T extends Object> List<T> clone(List<T> list) {
      try {
           List<T> c = list.getClass().newInstance();
           for(T t: list) {
             T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);
             c.add(copy);
           }
           return c;
      } catch(Exception e) {
           throw new RuntimeException("List cloning unsupported",e);
      }
}

How to fit a smooth curve to my data in R?

In ggplot2 you can do smooths in a number of ways, for example:

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "gam", formula = y ~ poly(x, 2)) 
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
  geom_smooth(method = "loess", span = 0.3, se = FALSE) 

enter image description here enter image description here

How can I convert an image into a Base64 string?

Here is the encoding and decoding code in Kotlin:

 fun encode(imageUri: Uri): String {
    val input = activity.getContentResolver().openInputStream(imageUri)
    val image = BitmapFactory.decodeStream(input , null, null)

    // Encode image to base64 string
    val baos = ByteArrayOutputStream()
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
    var imageBytes = baos.toByteArray()
    val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
    return imageString
}

fun decode(imageString: String) {

    // Decode base64 string to image
    val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
    val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

    imageview.setImageBitmap(decodedImage)
}

htaccess remove index.php from url

Some may get a 403 with the method listed above using mod_rewrite. Another solution to rewite index.php out is as follows:

<IfModule mod_rewrite.c> 

RewriteEngine On

# Put your installation directory here:
RewriteBase /

# Do not enable rewriting for files or directories that exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

</IfModule> 

c# foreach (property in object)... Is there a simple way of doing this?

Use Reflection to do this

SomeClass A = SomeClass(...)
PropertyInfo[] properties = A.GetType().GetProperties();

Kill python interpeter in linux from the terminal

You can try the killall command:

killall python

MetadataException: Unable to load the specified metadata resource

I simply hadn't referenced my class library that contained the EDMX file.

How do I get my solution in Visual Studio back online in TFS?

You can go use registry editor.

  1. Turn off all VS instances.
  2. Open registry editor and go to: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\TeamFoundation\Instances
  3. Find proper server e.g: team32system1
  4. Go to Collection and nex DefaultCollection: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\TeamFoundation\Instances\team32system1\Collections\DefaultCollection
  5. Set Offline key to 0
  6. Open solution in VS. Afterwards pop up should appear which question would you like bring solution to online mode.