Programs & Examples On #Software estimation

Failing to run jar file from command line: “no main manifest attribute”

First run your application from eclipse to create launch configuration. Then just follow the steps:

  1. From the menu bar's File menu, select Export.
  2. Expand the Java node and select Runnable JAR file. Click Next.
  3. In the Runnable JAR File Specification page, select a 'Java Application' launch configuration to use to create a runnable JAR.
  4. In the Export destination field, either type or click Browse to select a location for the JAR file.
  5. Select an appropriate library handling strategy.
  6. Optionally, you can also create an ANT script to quickly regenerate a previously created runnable JAR file.

Source: Creating a New Runnable JAR File at Eclipse.org

How to convert a date String to a Date or Calendar object?

The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date / java.util.Calendar classes.

Joda's DateFormatter can parse a String to a Joda DateTime.

Pass Javascript Variable to PHP POST

Yes you could use an <input type="hidden" /> and set the value of that hidden field in your javascript code so it gets posted with your other form data.

Fatal error: Call to undefined function pg_connect()

I encountered this error and it ended up being related to how PHP's extension_dir was loading.

If upon printing out phpinfo() you find that under the PDO header PDO drivers is set to no value, you may want to check that you are successfully loading your extension directory as detailed in this post:

https://stackoverflow.com/a/14786808/2578505

Install Android App Bundle on device

For MAC:

brew install bundletool
bundletool build-apks --bundle=./app.aab --output=./app.apks
bundletool install-apks --apks=app.apks

Joining two lists together

The Union method might address your needs. You didn't specify whether order or duplicates was important.

Take two IEnumerables and perform a union as seen here:

int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };

IEnumerable<int> union = ints1.Union(ints2);

// yields { 5, 3, 9, 7, 8, 6, 4, 1, 0 } 

Linux bash script to extract IP address

In my opinion the simplest and most elegant way to achieve what you need is this:

ip route get 8.8.8.8 | tr -s ' ' | cut -d' ' -f7

ip route get [host] - gives you the gateway used to reach a remote host e.g.:

8.8.8.8 via 192.168.0.1 dev enp0s3  src 192.168.0.109

tr -s ' ' - removes any extra spaces, now you have uniformity e.g.:

8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109

cut -d' ' -f7 - truncates the string into ' 'space separated fields, then selects the field #7 from it e.g.:

192.168.0.109

How to make a <svg> element expand or contract to its parent container?

What's worked for me recently is to remove all height="" and width="" attributes from the <svg> tag and all child tags. Then you can use scaling using a percentage of the parent container's height or width.

Before:

<svg width="3212" height="3212" viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
   circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>

After:

<svg viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
   circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>

How to Set OnClick attribute with value containing function in ie8?

You could also set onclick to call your function like this:

foo.onclick = function() { callYourJSFunction(arg1, arg2); };

This way, you can pass arguments too. .....

Closing WebSocket correctly (HTML5, Javascript)

According to the protocol spec v76 (which is the version that browser with current support implement):

To close the connection cleanly, a frame consisting of just a 0xFF byte followed by a 0x00 byte is sent from one peer to ask that the other peer close the connection.

If you are writing a server, you should make sure to send a close frame when the server closes a client connection. The normal TCP socket close method can sometimes be slow and cause applications to think the connection is still open even when it's not.

The browser should really do this for you when you close or reload the page. However, you can make sure a close frame is sent by doing capturing the beforeunload event:

window.onbeforeunload = function() {
    websocket.onclose = function () {}; // disable onclose handler first
    websocket.close();
};

I'm not sure how you can be getting an onclose event after the page is refreshed. The websocket object (with the onclose handler) will no longer exist once the page reloads. If you are immediately trying to establish a WebSocket connection on your page as the page loads, then you may be running into an issue where the server is refusing a new connection so soon after the old one has disconnected (or the browser isn't ready to make connections at the point you are trying to connect) and you are getting an onclose event for the new websocket object.

How to resize the jQuery DatePicker control

I tried the approach of using the callback function beforeShow but found I had to also set the line height. My version looked like:

beforeShow: function(){$j('.ui-datepicker').css({'font-size': 11, 'line-height': 1.2})}

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

How to start debug mode from command prompt for apache tomcat server?

  1. From your IDE, create a remote debug configuration, configure it for the default JPDA Tomcat port which is port 8000.

  2. From the command line:

    Linux:

    cd apache-tomcat/bin
    export JPDA_SUSPEND=y
    ./catalina.sh jpda run
    

    Windows:

    cd apache-tomcat\bin
    set JPDA_SUSPEND=y
    catalina.bat jpda run
    
  3. Execute the remote debug configuration from your IDE, and Tomcat will start running and you are now able to set breakpoints in the IDE.

Note:

The JPDA_SUSPEND=y line is optional, it is useful if you want that Apache Tomcat doesn't start its execution until step 3 is completed, useful if you want to troubleshoot application initialization issues.

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

Lower mm means minutes, so

DateTime.Now.ToString("dd/MM/yyyy");  

or

DateTime.Now.ToString("d");  

or

DateTime.Now.ToShortDateString()

works.

Standard Date and Time Format Strings

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

I had almost just as same error with my Ruby on Rails application running postgresql(mac). This worked for me:

brew services restart postgresql

How to use placeholder as default value in select2 framework

$("#e2").select2({
   placeholder: "Select a State",
   allowClear: true
});
$("#e2_2").select2({
   placeholder: "Select a State"
});

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder configuration element as seen in the example code.

When placeholder is used for a non-multi-value select box, it requires that you include an empty tag as your first option.

Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

https://select2.org/placeholders

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

You can convert the value to a date using a formula like this, next to the cell:

=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))

Where A1 is the field you need to convert.

Alternatively, you could use this code in VBA:

Sub ConvertYYYYMMDDToDate()
   Dim c As Range
   For Each c In Selection.Cells
       c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
       'Following line added only to enforce the format.
       c.NumberFormat = "mm/dd/yyyy"
   Next
End Sub

Just highlight any cells you want fixed and run the code.

Note as RJohnson mentioned in the comments, this code will error if one of your selected cells is empty. You can add a condition on c.value to skip the update if it is blank.

How to convert JSON to CSV format and store in a variable

Personally I would use d3-dsv library to do this. Why to reinvent the wheel?


import { csvFormat } from 'd3-dsv';
/**
 * Based on input data convert it to csv formatted string
 * @param (Array) columnsToBeIncluded array of column names (strings)
 *                which needs to be included in the formated csv
 * @param {Array} input array of object which need to be transformed to string
 */
export function convertDataToCSVFormatString(input, columnsToBeIncluded = []) {
  if (columnsToBeIncluded.length === 0) {
    return csvFormat(input);
  }
  return csvFormat(input, columnsToBeIncluded);
}

With tree-shaking you can just import that particular function from d3-dsv library

Difference between number and integer datatype in oracle dictionary views

Integer is only there for the sql standard ie deprecated by Oracle.

You should use Number instead.

Integers get stored as Number anyway by Oracle behind the scenes.

Most commonly when ints are stored for IDs and such they are defined with no params - so in theory you could look at the scale and precision columns of the metadata views to see of no decimal values can be stored - however 99% of the time this will not help.

As was commented above you could look for number(38,0) columns or similar (ie columns with no decimal points allowed) but this will only tell you which columns cannot take decimals, and not what columns were defined so that INTS can be stored.

Suggestion: do a data profile on the number columns. Something like this:

 select max( case when trunc(column_name,0)=column_name then 0 else 1 end ) as has_dec_vals
 from table_name

How to Execute a Python File in Notepad ++?

All the answers for the Run->Run menu option go with the "/K" switch of cmd, so the terminal stays open, or "-i" for python.exe so python forces interactive mode - both to preserve the output for you to observe.

Yet in cmd /k you have to type exit to close it, in the python -i - quit(). If that is too much typing for your liking (for me it sure is :), the Run command to use is

cmd /k C:\Python27\python.exe  "$(FULL_CURRENT_PATH)" & pause & exit

C:\Python27\python.exe - obviously the full path to your python install (or just python if you want to go with the first executable in your user's path).

& is unconditional execution of the next command in Windows - unconditional as it runs regardless of the RC of the previous command (&& is "and" - run only if the previous completed successfully, || - is "or").

pause - prints "Press any key to continue . . ." and waits for any key (that output can be suppressed if need).

exit - well, types the exit for you :)

So at the end, cmd runs python.exe which executes the current file and keeps the window opened, pause waits for you to press any key, and exit finally close the window once you press that any key.

Javascript date regex DD/MM/YYYY

Take a look from here https://www.regextester.com/?fam=114662

Use this following Regular Expression Details, This will support leap year also.

var reg = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([1][26]|[2468][048]|[3579][26])00))))$/g;

Example

Find all CSV files in a directory using Python

Many (linked) answers change working directory with os.chdir(). But you don't have to.

Recursively print all CSV files in /home/project/ directory:

pathname = "/home/project/**/*.csv"

for file in glob.iglob(pathname, recursive=True):
    print(file)

Requires python 3.5+. From docs [1]:

  • pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif)
  • pathname can contain shell-style wildcards.
  • Whether or not the results are sorted depends on the file system.
  • If recursive is true, the pattern ** will match any files and zero or more directories, subdirectories and symbolic links to directories

[1] https://docs.python.org/3/library/glob.html#glob.glob

Split Div Into 2 Columns Using CSS

Divide a division in two columns is very easy, just specify the width of your column better if you put this (like width:50%) and set the float:left for left column and float:right for right column.

How to vertically center content with variable height within a div?

You can use margin auto. With flex, the div seems to be centered vertically too.

body,
html {
  height: 100%;
  margin: 0;
}
.site {
  height: 100%;
  display: flex;
}
.site .box {
  background: #0ff;
  max-width: 20vw;
  margin: auto;
}
<div class="site">
  <div class="box">
    <h1>blabla</h1>
    <p>blabla</p>
    <p>blablabla</p>
    <p>lbibdfvkdlvfdks</p>
  </div>
</div>

Select and display only duplicate records in MySQL

SELECT id, payer_email FROM paypal_ipn_orders
WHERE payer_email IN (
    SELECT payer_email FROM papypal_ipn_orders GROUP BY payer_email HAVING COUNT(*) > 1)

How to limit file upload type file size in PHP?

Hope this helps :-)

if(isset($_POST['submit'])){
    ini_set("post_max_size", "30M");
    ini_set("upload_max_filesize", "30M");
    ini_set("memory_limit", "20000M"); 
    $fileName='product_demo.png';

    if($_FILES['imgproduct']['size'] > 0 && 
            (($_FILES["imgproduct"]["type"] == "image/gif") || 
                ($_FILES["imgproduct"]["type"] == "image/jpeg")|| 
                ($_FILES["imgproduct"]["type"] == "image/pjpeg") || 
                ($_FILES["imgproduct"]["type"] == "image/png") &&
                ($_FILES["imgproduct"]["size"] < 2097152))){

        if ($_FILES["imgproduct"]["error"] > 0){
            echo "Return Code: " . $_FILES["imgproduct"]["error"] . "<br />";
        } else {    
            $rnd=rand(100,999);
            $rnd=$rnd."_";
            $fileName = $rnd.trim($_FILES['imgproduct']['name']);
            $tmpName  = $_FILES['imgproduct']['tmp_name'];
            $fileSize = $_FILES['imgproduct']['size'];
            $fileType = $_FILES['imgproduct']['type'];  
            $target = "upload/";
            echo $target = $target .$rnd. basename( $_FILES['imgproduct']['name']) ; 
            move_uploaded_file($_FILES['imgproduct']['tmp_name'], $target);
        }
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
}

Swap two variables without using a temporary variable

we can do that by doing a simple trick

a = 20;
b = 30;
a = a+b; // add both the number now a has value 50
b = a-b; // here we are extracting one number from the sum by sub
a = a-b; // the number so obtained in above help us to fetch the alternate number from sum
System.out.print("swapped numbers are a = "+ a+"b = "+ b);

jQuery - select all text from a textarea

Selecting text in an element (akin to highlighting with your mouse)

:)

Using the accepted answer on that post, you can call the function like this:

$(function() {
  $('#textareaId').click(function() {
    SelectText('#textareaId');
  });
});

Has anyone ever got a remote JMX JConsole to work?

In order to make a contribution, this is what I did on CentOS 6.4 for Tomcat 6.

  1. Shutdown iptables service

    service iptables stop
    
  2. Add the following line to tomcat6.conf

    CATALINA_OPTS="${CATALINA_OPTS} -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8085 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=[host_ip]"
    

This way I was able to connect from another PC using JConsole.

How to initailize byte array of 100 bytes in java with all 0's

A new byte array will automatically be initialized with all zeroes. You don't have to do anything.

The more general approach to initializing with other values, is to use the Arrays class.

import java.util.Arrays;

byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

How to reset index in a pandas dataframe?

Another solutions are assign RangeIndex or range:

df.index = pd.RangeIndex(len(df.index))

df.index = range(len(df.index))

It is faster:

df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())

In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop

In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop

In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop

SQL Inner-join with 3 tables?

select empid,empname,managename,[Management ],cityname  
from employees inner join Managment  
on employees.manageid = Managment.ManageId     
inner join CITY on employees.Cityid=CITY.CityId


id name  managename  managment  cityname
----------------------------------------
1  islam   hamza       it        cairo

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

Adding css class through aspx code behind

If you want to add attributes, including the class, you need to set runat="server" on the tag.

    <div id="classMe" runat="server"></div>

Then in the code-behind:

classMe.Attributes.Add("class", "some-class")

Prevent screen rotation on Android

You can try This way

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itclanbd.spaceusers">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Login_Activity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

How to ignore conflicts in rpm installs

The --force option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.

If you tell rpm to install all RPMs from some directory, then it does exactly this. rpm will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.

You can remove the old RPM and rpm will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.

If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i (zypper in can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.

I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify command. It will complain for the new package if the old one has overwritten some files.

Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?

How to use *ngIf else?

In Angular 4.x.x You can use ngIf in four way to achieve simple if else procedure:

  1. Just Use If

    <div *ngIf="isValid">
        If isValid is true
    </div>
    
  2. Using If with Else (Please notice to templateName)

    <div *ngIf="isValid; else templateName">
        If isValid is true
    </div>
    
    <ng-template #templateName>
        If isValid is false
    </ng-template>
    
  3. Using If with Then (Please notice to templateName)

    <div *ngIf="isValid; then templateName">
        Here is never showing
    </div>
    
    <ng-template #templateName>
        If isValid is true
    </ng-template>
    
  4. Using If with Then and Else

    <div *ngIf="isValid; then thenTemplateName else elseTemplateName">
        Here is never showing
    </div>
    
    <ng-template #thenTemplateName>
        If isValid is true
    </ng-template>
    
    <ng-template #elseTemplateName>
        If isValid is false
    </ng-template>
    

Tip: ngIf evaluates the expression and then renders the then or else template in its place when expression is truthy or falsy respectively. Typically the:

  • then template is the inline template of ngIf unless bound to a different value.
  • else template is blank unless it is bound.

PHP + MySQL transactions examples

I made a function to get a vector of queries and do a transaction, maybe someone will find out it useful:

function transaction ($con, $Q){
        mysqli_query($con, "START TRANSACTION");

        for ($i = 0; $i < count ($Q); $i++){
            if (!mysqli_query ($con, $Q[$i])){
                echo 'Error! Info: <' . mysqli_error ($con) . '> Query: <' . $Q[$i] . '>';
                break;
            }   
        }

        if ($i == count ($Q)){
            mysqli_query($con, "COMMIT");
            return 1;
        }
        else {
            mysqli_query($con, "ROLLBACK");
            return 0;
        }
    }

Javascript array value is undefined ... how do I test for that

Check for

if (predQuery[preId] === undefined)

Use the strict equal to operator. See comparison operators

Should I use PATCH or PUT in my REST API?

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

JavaScript Array splice vs slice

Another example:

[2,4,8].splice(1, 2) -> returns [4, 8], original array is [2]

[2,4,8].slice(1, 2) -> returns 4, original array is [2,4,8]

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

How to make for loops in Java increase by increments other than 1

In your example, j+=3 increments by 3.

(Not much else to say here, if it's syntax related I'd suggest Googling first, but I'm new here so I could be wrong.)

How to add url parameters to Django template url tag?

Simply add Templates URL:

<a href="{% url 'service_data' d.id %}">
 ...XYZ
</a>

Used in django 2.0

UnicodeDecodeError, invalid continuation byte

It is invalid UTF-8. That character is the e-acute character in ISO-Latin1, which is why it succeeds with that codeset.

If you don't know the codeset you're receiving strings in, you're in a bit of trouble. It would be best if a single codeset (hopefully UTF-8) would be chosen for your protocol/application and then you'd just reject ones that didn't decode.

If you can't do that, you'll need heuristics.

How can I check if some text exist or not in the page using Selenium?

This will help you to check whether required text is there in webpage or not.

driver.getPageSource().contains("Text which you looking for");

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

NuGet: 'X' already has a dependency defined for 'Y'

In my case I had to delete the file NuGet.exe in the Project folder/.nuget and rebuild the project.

I also have in NuGet.targets the DownloadNuGetExe marked as true:

<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">true</DownloadNuGetExe>

Hope it's helps.

How do I temporarily disable triggers in PostgreSQL?

Alternatively, if you are wanting to disable all triggers, not just those on the USER table, you can use:

SET session_replication_role = replica;

This disables triggers for the current session.

To re-enable for the same session:

SET session_replication_role = DEFAULT;

Source: http://koo.fi/blog/2013/01/08/disable-postgresql-triggers-temporarily/

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

php return 500 error but no error log

For Symfony projects, be sure to check files in the project'es app/logs

More details available on this post :
How to debug 500 Error in Symfony 2

Btw, other frameworks or CMS share this kind of behaviour.

How to show matplotlib plots in python

In matplotlib you have two main options:

  1. Create your plots and draw them at the end:

    import matplotlib.pyplot as plt
    
    plt.plot(x, y)
    plt.plot(z, t)
    plt.show()
    
  2. Create your plots and draw them as soon as they are created:

    import matplotlib.pyplot as plt
    from matplotlib import interactive
    interactive(True)
    
    plt.plot(x, y)
    raw_input('press return to continue')
    
    plt.plot(z, t)
    raw_input('press return to end')
    

Composer install error - requires ext_curl when it's actually enabled

if use wamp go to:

wamp\bin\php\php.5.x.x\php.ini find: ;extension=php_curl.dll remove (;)

connecting to mysql server on another PC in LAN

actually you shouldn't specify port in the host name. Mysql has special option for port (if port differs from default)

kind of

mysql --host=192.168.1.2 --port=3306

How to change a table name using an SQL query?

rename table name :

RENAME TABLE old_tableName TO new_tableName;

for example:

RENAME TABLE company_name TO company_master;

Excel formula to get ranking position

If your C-column is sorted, you can check whether the current row is equal to your last row. If not, use the current row number as the ranking-position, otherwise use the value from above (value for b3):

=IF(C3=C2, B2, ROW()-1)

You can use the LARGE function to get the n-th highest value in case your C-column is not sorted:

=LARGE(C2:C7,3)

MVC3 DropDownListFor - a simple example?

I think this will help : In Controller get the list items and selected value

public ActionResult Edit(int id)
{
    ItemsStore item = itemStoreRepository.FindById(id);
    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
                                        "Id", "Name",item.CategoryId);

    // ViewBag to pass values to View and SelectList
    //(get list of items,valuefield,textfield,selectedValue)

    return View(item);
}

and in View

@Html.DropDownList("CategoryId",String.Empty)

How should I log while using multiprocessing in Python?

All current solutions are too coupled to the logging configuration by using a handler. My solution has the following architecture and features:

  • You can use any logging configuration you want
  • Logging is done in a daemon thread
  • Safe shutdown of the daemon by using a context manager
  • Communication to the logging thread is done by multiprocessing.Queue
  • In subprocesses, logging.Logger (and already defined instances) are patched to send all records to the queue
  • New: format traceback and message before sending to queue to prevent pickling errors

Code with usage example and output can be found at the following Gist: https://gist.github.com/schlamar/7003737

Angular no provider for NameService

As of Angular 2 Beta:

Add @Injectable to your service as:

@Injectable()
export class NameService {
    names: Array<string>;

    constructor() {
        this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
    }

    getNames() {
        return this.names;
    }
}

and to your component config add the providers as:

@Component({
    selector: 'my-app',
    providers: [NameService]
})

React-Native: Application has not been registered error

I had the same problem and for me the root cause was that I ran (react-native start) the packager from another react-native folder (AwesomeApp), while I created another project in an other folder.

Running the packager from the new app's directory solved it.

struct in class

I'd like to add another use case for an internal struct/class and its usability. An inner struct is often used to declare a data only member of a class that packs together relevant information and as such we can enclose it all in a struct instead of loose data members lying around.

The inner struct/class is but a data only compartment, ie it has no functions (except maybe constructors).

#include <iostream>

class E
{
    // E functions..
public:
    struct X
    {
        int v;
        // X variables..
    } x;
    // E variables..
};

int main()
{
    E e;
    e.x.v = 9;
    std::cout << e.x.v << '\n';
    
    E e2{5};
    std::cout << e2.x.v << '\n';

    // You can instantiate an X outside E like so:
    //E::X xOut{24};
    //std::cout << xOut.v << '\n';
    // But you shouldn't want to in this scenario.
    // X is only a data member (containing other data members)
    // for use only inside the internal operations of E
    // just like the other E's data members
}

This practice is widely used in graphics, where the inner struct will be sent as a Constant Buffer to HLSL. But I find it neat and useful in many cases.

Select DISTINCT individual columns in django?

The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.

>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}

or

>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']

And, it works without PostgreSQL.

This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set, but it's great for noodling around the shell.

No resource identifier found for attribute '...' in package 'com.app....'

This also happened to me when a PercentageRelativeLayout https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html was used and the build was targeting Android 0 = 26. PercentageRelativeLayout layout is obsolete starting from Android O and obviously sometime was changed in the resource generation. Replacing the layout with a ConstraintLayout or just a RelativeLayout solved it.

How to convert an array to object in PHP?

i have done it with quite simple way,

    $list_years         = array();
    $object             = new stdClass();

    $object->year_id   = 1 ;
    $object->year_name = 2001 ;
    $list_years[]       = $object;

Responding with a JSON object in Node.js (converting object/array to JSON string)

You have to use the JSON.stringify() function included with the V8 engine that node uses.

var objToJson = { ... };
response.write(JSON.stringify(objToJson));

Edit: As far as I know, IANA has officially registered a MIME type for JSON as application/json in RFC4627. It is also is listed in the Internet Media Type list here.

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

What is the command for cut copy paste a file from one directory to other directory

use the xclip which is command line interface to X selections

install

apt-get install xclip

usage

echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out

cat /tmp/test.xclip.out   # "test xclip"

enjoy.

Sql Server string to date conversion

Took me a minute to figure this out so here it is in case it might help someone:

In SQL Server 2012 and better you can use this function:

SELECT DATEFROMPARTS(2013, 8, 19);

Here's how I ended up extracting the parts of the date to put into this function:

select
DATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'
from MyTable

Make HTML5 video poster be same size as video itself

height:500px;
min-width:100%;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size:100% 100%;
object-fit:cover;

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size:cover;

How do I auto-hide placeholder text upon focus using css or jquery?

Using SCSS along with http://bourbon.io/, this solution is simple, elegant, and works on all web browsers:

input:focus {
  @include placeholder() {
    color: transparent;
  }
}

Use Bourbon ! It's good for you !

If statement with String comparison fails

If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

How to redirect in a servlet filter?

I'm trying to find a method to redirect my request from filter to login page

Don't

You just invoke

chain.doFilter(request, response);

from filter and the normal flow will go ahead.

I don't know how to redirect from servlet

You can use

response.sendRedirect(url);

to redirect from servlet

How to download a file via FTP with Python ftplib

FILENAME = 'StarWars.avi'    

with ftplib.FTP(FTP_IP, FTP_LOGIN, FTP_PASSWD) as ftp:
    ftp.cwd('movies')
    with open(FILENAME, 'wb') as f:
        ftp.retrbinary('RETR ' + FILENAME, f.write)

Of course it would we be wise to handle possible errors.

Can I do Model->where('id', ARRAY) multiple where conditions?

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();

python variable NameError

In addition to the missing quotes around 100Mb in the last else, you also want to quote the constants in your if-statements if tSizeAns == "1":, because raw_input returns a string, which in comparison with an integer will always return false.

However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. Please check your posted code. I cannot reproduce the error message.

Also if ... elif ... else in the way you use it is basically equivalent to a case or switch in other languages and is neither less readable nor much longer. It is fine to use here. One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup:

tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns] 

This however does only work as long as tSizeAns is guaranteed to be in the range of tSize. Otherwise you would have to either catch the KeyError exception or use a defaultdict:

lookup = {"1": "100Mb", "2": "200Mb"} try:     tSize = lookup[tSizeAns] except KeyError:     tSize = "100Mb" 

or

from collections import defaultdict  [...]  lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"}) tSize = lookup[tSizeAns] 

In your case I think these methods are not justified for two values. However you could use the dictionary to construct the initial output at the same time.

Why doesn't Dijkstra's algorithm work for negative weight edges?

Correctness of Dijkstra's algorithm:

We have 2 sets of vertices at any step of the algorithm. Set A consists of the vertices to which we have computed the shortest paths. Set B consists of the remaining vertices.

Inductive Hypothesis: At each step we will assume that all previous iterations are correct.

Inductive Step: When we add a vertex V to the set A and set the distance to be dist[V], we must prove that this distance is optimal. If this is not optimal then there must be some other path to the vertex V that is of shorter length.

Suppose this some other path goes through some vertex X.

Now, since dist[V] <= dist[X] , therefore any other path to V will be atleast dist[V] length, unless the graph has negative edge lengths.

Thus for dijkstra's algorithm to work, the edge weights must be non negative.

How to edit .csproj file

For JetBrains Rider:

First Option

  1. Unload Project
  2. Double click the unloaded project

Second option:

  1. Click on the project
  2. Press F4

That's it!

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

JavaScript module pattern with example

I would really recommend anyone entering this subject to read Addy Osmani's free book:

"Learning JavaScript Design Patterns".

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.

How to abort makefile if variable not set?

Use the shell function test:

foo:
    test $(something)

Usage:

$ make foo
test 
Makefile:2: recipe for target 'foo' failed
make: *** [foo] Error 1
$ make foo something=x
test x

Installing mysql-python on Centos

I have Python 2.7.5, MySQL 5.6 and CentOS 7.1.1503.

For me it worked with the following command:

# pip install mysql-python

Note pre-requisites here:

Install Python pip:

# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm

# yum -y update
Reboot the machine (if kernel is also updated)

# yum -y install python-pip

Install Python devel packages:

# yum install python-devel

Install MySQL devel packages:

# yum install mysql-devel

How to unstage large number of files without deleting the content

If you want to unstage all the changes use below command,

git reset --soft HEAD

In the case you want to unstage changes and revert them from the working directory,

git reset --hard HEAD

HEAD and ORIG_HEAD in Git

HEAD is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.

And @ alone is a shortcut for HEAD, since Git 1.8.5

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation).

For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary

How can I check if a key exists in a dictionary?

Another method is has_key() (if still using Python 2.X):

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True

Double % formatting question for printf in Java

%d is for integers use %f instead, it works for both float and double types:

double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000

How to change the Spyder editor background to dark?

I've seen some people recommending installing aditional software but in my opinion the best way is by using the built-in skins, you can find them at:

Tools > Preferences > Syntax Coloring

Pretty printing XML with javascript

This my version, maybe usefull for others, using String builder Saw that someone had the same piece of code.

    public String FormatXml(String xml, String tab)
    {
        var sb = new StringBuilder();
        int indent = 0;
        // find all elements
        foreach (string node in Regex.Split(xml,@">\s*<"))
        {
            // if at end, lower indent
            if (Regex.IsMatch(node, @"^\/\w")) indent--;
            sb.AppendLine(String.Format("{0}<{1}>", string.Concat(Enumerable.Repeat(tab, indent).ToArray()), node));
            // if at start, increase indent
            if (Regex.IsMatch(node, @"^<?\w[^>]*[^\/]$")) indent++;
        }
        // correct first < and last > from the output
        String result = sb.ToString().Substring(1);
        return result.Remove(result.Length - Environment.NewLine.Length-1);
    }

Running a simple shell script as a cronjob

The easiest way would be to use a GUI:

For Gnome use gnome-schedule (universe)

sudo apt-get install gnome-schedule 

For KDE use kde-config-cron

It should be pre installed on Kubuntu

But if you use a headless linux or don´t want GUI´s you may use:

crontab -e

If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:

*     *     *     *     *  YOURCOMMAND
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- Day in Week (0 to 7) (Sunday is 0 and 7)
|     |     |     +------- Month (1 to 12)
|     |     +--------- Day in Month (1 to 31)
|     +----------- Hour (0 to 23)
+------------- Minute (0 to 59)

There are some shorts, too (if you don´t want the *):

@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year

If you want to use the shorts as cron (because they don´t work or so):

@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

If copy-dependencies, unpack, pack, etc., are important for your project you shouldn't ignore it. You have to enclose your <plugins> in <pluginManagement> tested with Eclipse Indigo SR1, maven 2.2.1

How should we manage jdk8 stream for null values

Stuart's answer provides a great explanation, but I'd like to provide another example.

I ran into this issue when attempting to perform a reduce on a Stream containing null values (actually it was LongStream.average(), which is a type of reduction). Since average() returns OptionalDouble, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.

So, as the OP suggests, I added a filter like so:

list.stream()
    .filter(o -> o != null)
    .reduce(..);

Or as tangens pointed out below, use the predicate provided by the Java API:

list.stream()
    .filter(Objects::nonNull)
    .reduce(..);

From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams

Fatal error: "No Target Architecture" in Visual Studio

I had a similar problem. In my case, I had accidentally included winuser.h before windows.h (actually, a buggy IDE extension had added it). Removing the winuser.h solved the problem.

Replace multiple whitespaces with single whitespace in JavaScript string

I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:

  • I want to replace multiple occurences of whitespace inside the string with a single space
  • ...and... I do not want whitespaces in the beginnin or end of the string (trim)

For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):

s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');

The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.

Print array without brackets and commas

Replace the brackets and commas with empty space.

String formattedString = myArrayList.toString()
    .replace(",", "")  //remove the commas
    .replace("[", "")  //remove the right bracket
    .replace("]", "")  //remove the left bracket
    .trim();           //remove trailing spaces from partially initialized arrays

Is it possible to read the value of a annotation in java?

For the few people asking for a generic method, this should help you (5 years later :p).

For my below example, I'm pulling the RequestMapping URL value from methods that have the RequestMapping annotation. To adapt this for fields, just change the

for (Method method: clazz.getMethods())

to

for (Field field: clazz.getFields())

And swap usage of RequestMapping for whatever annotation you are looking to read. But make sure that the annotation has @Retention(RetentionPolicy.RUNTIME).

public static String getRequestMappingUrl(final Class<?> clazz, final String methodName)
{
    // Only continue if the method name is not empty.
    if ((methodName != null) && (methodName.trim().length() > 0))
    {
        RequestMapping tmpRequestMapping;
        String[] tmpValues;

        // Loop over all methods in the class.
        for (Method method: clazz.getMethods())
        {
            // If the current method name matches the expected method name, then keep going.
            if (methodName.equalsIgnoreCase(method.getName()))
            {
                // Try to extract the RequestMapping annotation from the current method.
                tmpRequestMapping = method.getAnnotation(RequestMapping.class);

                // Only continue if the current method has the RequestMapping annotation.
                if (tmpRequestMapping != null)
                {
                    // Extract the values from the RequestMapping annotation.
                    tmpValues = tmpRequestMapping.value();

                    // Only continue if there are values.
                    if ((tmpValues != null) && (tmpValues.length > 0))
                    {
                        // Return the 1st value.
                        return tmpValues[0];
                    }
                }
            }
        }
    }

    // Since no value was returned, log it and return an empty string.
    logger.error("Failed to find RequestMapping annotation value for method: " + methodName);

    return "";
}

Starting a shell in the Docker Alpine container

Usually, an Alpine Linux image doesn't contain bash, Instead you can use /bin/ash, /bin/sh, ash or only sh.

/bin/ash

docker run -it --rm alpine /bin/ash

/bin/sh

docker run -it --rm alpine /bin/sh

ash

docker run -it --rm alpine ash

sh

docker run -it --rm alpine sh

I hope this information helps you.

Does Spring @Transactional attribute work on a private method?

If you need to wrap a private method inside a transaction and don't want to use aspectj, you can use TransactionTemplate.

@Service
public class MyService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    private void process(){
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                processInTransaction();
            }
        });

    }

    private void processInTransaction(){
        //...
    }

}

How to set the width of a RaisedButton in Flutter?

match_parent (Full width):

SizedBox(
  width: double.infinity, // <-- match_parent
  child: RaisedButton(...)
)

Specific width:

SizedBox(
  width: 100, // <-- Your width
  child: RaisedButton(...)
)

Refresh (reload) a page once using jQuery?

Add this to the top of your file and the site will refresh every 30 seconds.

<script type="text/javascript">
    window.onload = Refresh;

    function Refresh() {
        setTimeout("refreshPage();", 30000);
    }
    function refreshPage() {
        window.location = location.href;
    }
</script>

Another one is: Add in the head tag

<meta http-equiv="refresh" content="30">

CSS Styling for a Button: Using <input type="button> instead of <button>

Do you want something like the given fiddle!


HTML

<div class="button">
    <input type="button" value="TELL ME MORE" onClick="document.location.reload(true)">
</div>

CSS

.button input[type="button"] {
    color:#08233e;
    font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
    font-size:70%;
    padding:14px;
    background:url(overlay.png) repeat-x center #ffcc00;
    background-color:rgba(255,204,0,1);
    border:1px solid #ffcc00;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px;
    border-bottom:1px solid #9f9f9f;
    -moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    -webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
    cursor:pointer;
    display:block;
    width:100%;
}
.button input[type="button"]:hover {
    background-color:rgba(255,204,0,0.8);
}

Position: absolute and parent height?

This is a late answer, but by looking at the source code, I noticed that when the video is fullscreen, the "mejs-container-fullscreen" class is added to the "mejs-container" element. It is thus possible to change the styling based on this class.

.mejs-container.mejs-container-fullscreen {
    // This rule applies only to the container when in fullscreen
    padding-top: 57%;
}

Also, if you wish to make your MediaElement video fluid using CSS, below is a great trick by Chris Coyier: http://css-tricks.com/rundown-of-handling-flexible-media/

Just add this to your CSS:

.mejs-container {
    width: 100% !important;
    height: auto !important;
    padding-top: 57%;
}
.mejs-overlay, .mejs-poster {
    width: 100% !important;
    height: 100% !important;
}
.mejs-mediaelement video {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    width: 100% !important;
    height: 100% !important;
}

I hope it helps.

How can I initialize an array without knowing it size?

Use LinkedList instead. Than, you can create an array if necessary.

How do I install cURL on cygwin?

In order to use the command-line version of curl, you need the curl executable. So, run the Cygwins Setup.exe, and select curl (under Net->curl). That one uses libcurl3, which is located in Libs->libcurl3. But libcurl3 will be pulled in as a dependency if it's not already installed. So, just select Net->curl and you're good to go.

Python JSON encoding

JSON uses square brackets for lists ( [ "one", "two", "three" ] ) and curly brackets for key/value dictionaries (also called objects in JavaScript, {"one":1, "two":"b"}).

The dump is quite correct, you get a list of three elements, each one is a list of two strings.

if you wanted a dictionary, maybe something like this:

x = simplejson.dumps(dict(data))
>>> {"pear": "fish", "apple": "cat", "banana": "dog"}

your expected string ('{{"apple":{"cat"},{"banana":"dog"}}') isn't valid JSON. A

What does Include() do in LINQ?

Let's say for instance you want to get a list of all your customers:

var customers = context.Customers.ToList();

And let's assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product.

As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include() allows you to indicate which related entities should be read from the database as part of the same query.

Using the same example, this might bring in all of the related order headers, but none of the other records:

var customersWithOrderDetail = context.Customers.Include("Orders").ToList();

As a final point since you asked for SQL, the first statement without Include() could generate a simple statement:

SELECT * FROM Customers;

The final statement which calls Include("Orders") may look like this:

SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;

How to change the Title of the window in Qt?

For new Qt users this is a little more confusing than it seems if you are using QT Designer and .ui files.

Initially I tried to use ui->setWindowTitle, but that doesn't exist. ui is not a QDialog or a QMainWindow.

The owner of the ui is the QDialog or QMainWindow, the .ui just describes how to lay it out. In that case, you would use:

this->setWindowTitle("New Title");

I hope this helps someone else.

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

In your giant elif chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:

...
elif x == 90:
    return 6
else:
    raise ValueError(x)

How to replace NaNs by preceding values in pandas DataFrame?

ffill now has it's own method pd.DataFrame.ffill

df.ffill()

     0    1    2
0  1.0  2.0  3.0
1  4.0  2.0  3.0
2  4.0  2.0  9.0

Java getHours(), getMinutes() and getSeconds()

For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:

long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));

This will print:

Duration: 1:23:45.678

Xcode - ld: library not found for -lPods

Had this problem as well. Something was wrong with my CocoaPods installation. No pods other than KIF were installing properly. I followed the comments on this thread to be of help.

Basically, I needed to ensure that Build Active Architectures Only settings for both my project and the Pods project were equal.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Explicitly filling in the ContentDisposition fields did the trick.

if (attachmentFilename != null)
{
    Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
    ContentDisposition disposition = attachment.ContentDisposition;
    disposition.CreationDate = File.GetCreationTime(attachmentFilename);
    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
    disposition.FileName = Path.GetFileName(attachmentFilename);
    disposition.Size = new FileInfo(attachmentFilename).Length;
    disposition.DispositionType = DispositionTypeNames.Attachment;
    message.Attachments.Add(attachment);                
}

BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!

smtpClient.EnableSsl = true;
smtpClient.Port = 587;

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

Makefile: How to correctly include header file and its directory?

These lines in your makefile,

INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h

and this line in your .cpp file,

#include "StdCUtil/split.h"

are in conflict.

With your makefile in your source directory and with that -I option you should be using #include "split.h" in your source file, and your dependency should be ../StdCUtil/split.h.

Another option:

INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/..  # Ugly!
DEPS = $(INC_DIR)/split.h

With this your #include directive would remain as #include "StdCUtil/split.h".

Yet another option is to place your makefile in the parent directory:

root
  |____Makefile
  |
  |___Core
  |     |____DBC.cpp
  |     |____Lock.cpp
  |     |____Trace.cpp
  |
  |___StdCUtil
        |___split.h

With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core and StdCUtil directories. Object, for example. With this, your makefile becomes:

INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS  = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.

DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.


all: $(OBJS)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
  $(CC) $(CFLAGS) -c $< -o $@

$(OBJ_DIR)/Trace.o: $(DEPS)

Algorithm to generate all possible permutations of a list?

In the following Java solution we take advantage over the fact that Strings are immutable in order to avoid cloning the result-set upon every iteration.

The input will be a String, say "abc", and the output will be all the possible permutations:

abc
acb
bac
bca
cba
cab

Code:

public static void permute(String s) {
    permute(s, 0);
}

private static void permute(String str, int left){
    if(left == str.length()-1) {
        System.out.println(str);
    } else {
        for(int i = left; i < str.length(); i++) {
            String s = swap(str, left, i);
            permute(s, left+1);
        }
    }
}

private static String swap(String s, int left, int right) {
    if (left == right)
        return s;

    String result = s.substring(0, left);
    result += s.substring(right, right+1);
    result += s.substring(left+1, right);
    result += s.substring(left, left+1);
    result += s.substring(right+1);
    return result;
}

Same approach can be applied to arrays (instead of a string):

public static void main(String[] args) {
    int[] abc = {1,2,3};
    permute(abc, 0);
}
public static void permute(int[] arr, int index) {
    if (index == arr.length) {
        System.out.println(Arrays.toString(arr));
    } else {
        for (int i = index; i < arr.length; i++) {
            int[] permutation = arr.clone();
            permutation[index] = arr[i];
            permutation[i] = arr[index];
            permute(permutation, index + 1);
        }
    }
}

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

RegEx match open tags except XHTML self-contained tags

RegEx match open tags except XHTML self-contained tags
All other tags (and content) are skipped.


This regex does that. If you need to match only specific Open tags, make a list
in an alternation (?:p|br|<whatever tags you want>) and replace the [\w:]+ construct
in the appropriate place below.

<(?:(?:(?:(script|style|object|embed|applet|noframes|noscript|noembed)(?:\s+(?>"[\S\s]*?"|'[\S\s]*?'|(?:(?!/>)[^>])?)+)?\s*>)[\S\s]*?</\1\s*(?=>)(*SKIP)(*FAIL))|(?:[\w:]+\b(?=((?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)*)>)\2(?<!/))|(?:(?:/?[\w:]+\s*/?)|(?:[\w:]+\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+\s*/?)|\?[\S\s]*?\?|(?:!(?:(?:DOCTYPE[\S\s]*?)|(?:\[CDATA\[[\S\s]*?\]\])|(?:--[\S\s]*?--)|(?:ATTLIST[\S\s]*?)|(?:ENTITY[\S\s]*?)|(?:ELEMENT[\S\s]*?))))(*SKIP)(*FAIL))>

https://regex101.com/r/uMvJn0/1

 # Mix html/xml     
 # https://regex101.com/r/uMvJn0/1     
 
 <
 (?:
    
    # Invisible content gets failed
    
    (?:
       (?:
                               # Invisible content; end tag req'd
          (                    # (1 start)
             script
           | style
           | object
           | embed
           | applet
           | noframes
           | noscript
           | noembed 
          )                    # (1 end)
          (?:
             \s+ 
             (?>
                " [\S\s]*? "
              | ' [\S\s]*? '
              | (?:
                   (?! /> )
                   [^>] 
                )?
             )+
          )?
          \s* >
       )
       
       [\S\s]*? </ \1 \s* 
       (?= > )
       (*SKIP)(*FAIL)
    )
    
  | 
    
    # This is any open html tag we will match
    
    (?:
       [\w:]+ \b 
       (?=
          (                    # (2 start)
             (?:
                " [\S\s]*? " 
              | ' [\S\s]*? ' 
              | [^>]? 
             )*
          )                    # (2 end)
          >
       )
       \2 
       (?<! / )
    )
    
  | 
    # All other tags get failed
    
    (?:
       (?: /? [\w:]+ \s* /? )
     | (?:
          [\w:]+ 
          \s+ 
          (?:
             " [\S\s]*? " 
           | ' [\S\s]*? ' 
           | [^>]? 
          )+
          \s* /?
       )
     | \? [\S\s]*? \?
     | (?:
          !
          (?:
             (?: DOCTYPE [\S\s]*? )
           | (?: \[CDATA\[ [\S\s]*? \]\] )
           | (?: -- [\S\s]*? -- )
           | (?: ATTLIST [\S\s]*? )
           | (?: ENTITY [\S\s]*? )
           | (?: ELEMENT [\S\s]*? )
          )
       )
    )
    (*SKIP)(*FAIL)
 )
 >

How do I erase an element from std::vector<> by index?

Erase an element with index :

vec.erase(vec.begin() + index);

Erase an element with value:

vec.erase(find(vec.begin(),vec.end(),value));

How to save a Seaborn plot into a file

You would get an error for using sns.figure.savefig("output.png") in seaborn 0.8.1.

Instead use:

import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

ImportError: No module named tensorflow

You may need this since first one may not work.

python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl

finished with non zero exit value

just solved this issues with moving the project to a shorter path. It can happen if you exceed the Windows max path length

How to bind 'touchstart' and 'click' events but not respond to both?

You could try like this:

var clickEvent = (('ontouchstart' in document.documentElement)?'touchstart':'click');
$("#mylink").on(clickEvent, myClickHandler);

UTF-8 problems while reading CSV file with fgetcsv

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

npm start error with create-react-app

This occurs when the node_modules gets out of sync with package.json.

Run the following at the root and any sub service /sub-folder that might have node_modules folder within it.

rd node_modules /S /Q
npm install

How to set back button text in Swift

You can do it from interface builder as follows:

click on the navigation item of previous view controller

enter image description here

from the attributes inspector set the back button text to whatever you want. Thats it!!

enter image description here

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

What is the difference between method overloading and overriding?

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Simple regular expression for a decimal with a precision of 2

For numbers that don't have a thousands separator, I like this simple, compact regex:

\d+(\.\d{2})?|\.\d{2}

or, to not be limited to a precision of 2:

\d+(\.\d*)?|\.\d+

The latter matches
1
100
100.
100.74
100.7
0.7
.7
.72

And it doesn't match empty string (like \d*.?\d* would)

Best way to check for "empty or null value"

If there may be empty trailing spaces, probably there isn't better solution. COALESCE is just for problems like yours.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Matt's answer is fine, but just to avoid this to propagate to other elements inside the navbar (like when you also have a dropdown), use

.navbar-nav > li > a {
   line-height: 50px;
}

Change the spacing of tick marks on the axis of a plot?

With base graphics, the easiest way is to stop the plotting functions from drawing axes and then draw them yourself.

plot(1:10, 1:10, axes = FALSE)
axis(side = 1, at = c(1,5,10))
axis(side = 2, at = c(1,3,7,10))
box()

OpenMP set_num_threads() is not working

Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4

#pragma omp parallel
{
   omp_set_num_threads(4);
   int id = omp_get_num_threads();
   #pragma omp for
   for (i = 0:n){foo(A);}
}

printf("Number of threads: %d", id);

Get user's current location

Edited

Change freegeoip.net into ipinfo.io

<?php    

function get_client_ip()
{
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    } else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    } else if (isset($_SERVER['HTTP_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    } else if (isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    } else {
        $ipaddress = 'UNKNOWN';
    }

    return $ipaddress;
}
$PublicIP = get_client_ip();
$json     = file_get_contents("http://ipinfo.io/$PublicIP/geo");
$json     = json_decode($json, true);
$country  = $json['country'];
$region   = $json['region'];
$city     = $json['city'];
?>

Retrieving parameters from a URL

import cgitb
cgitb.enable()

import cgi
print "Content-Type: text/plain;charset=utf-8"
print
form = cgi.FieldStorage()
i = int(form.getvalue('a'))+int(form.getvalue('b'))
print i

Working with Enums in android

public enum Gender {
    MALE,
    FEMALE
}

Renaming Columns in an SQL SELECT Statement

you have to rename each column

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

XSLT counting elements with a given value

<xsl:variable name="count" select="count(/Property/long = $parPropId)"/>

Un-tested but I think that should work. I'm assuming the Property nodes are direct children of the root node and therefor taking out your descendant selector for peformance

Change image source in code behind - Wpf

You are all wrong! Why? Because all you need is this code to work:

(image View) / C# Img is : your Image box

Keep this as is, without change ("ms-appx:///) this is code not your app name Images is your folder in your project you can change it. dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png' So the uri is :"ms-appx:///Images/dog.png" and my code :


private void Button_Click(object sender, RoutedEventArgs e)
    {
         img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
    }

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

How to use a Bootstrap 3 glyphicon in an html select

To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.

<select class="form-control glyphicon">
    <option value="">&#x2212; &#x2212; &#x2212; Hello</option>
    <option value="glyphicon-list-alt">&#xe032; Text</option>
</select>

Here's a list of the icons with their unicode:

http://glyphicons.bootstrapcheatsheets.com/

Readably print out a python dict() sorted by key

Another short oneliner:

mydict = {'c': 1, 'b': 2, 'a': 3}
print(*sorted(mydict.items()), sep='\n')

"The Controls collection cannot be modified because the control contains code blocks"

In my case I got this error because I was wrongly setting InnerText to a div with html inside it.

Example:

SuccessMessagesContainer.InnerText = "";

   <div class="SuccessMessages ui-state-success" style="height: 25px; display: none;" id="SuccessMessagesContainer" runat="server">
      <table>
         <tr>
            <td style="width: 80px; vertical-align: middle; height: 18px; text-align: center;">
               <img src="<%=Image_success_icn %>" style="margin: 0 auto; height: 18px;
                  width: 18px;" />
            </td>
            <td id="SuccessMessage" style="vertical-align: middle;" class="SuccessMessage" runat="server" >
            </td>
         </tr>
      </table>
   </div>

Enforcing the type of the indexed members of a Typescript object?

var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4;  // error

// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above

NHibernate.MappingException: No persister for: XYZ

Should it be name="Id"? Typos are a likely cause.

Next would be to try it out with a non-generic test to make sure you're passing in the proper type parameter.

Can you post the entire error message?

What's wrong with nullable columns in composite primary keys?

NULL == NULL -> false (at least in DBMSs)

So you wouldn't be able to retrieve any relationships using a NULL value even with additional columns with real values.

Django - after login, redirect user to his custom page --> mysite.com/username

If you're using Django's built-in LoginView, it takes next as context, which is "The URL to redirect to after successful login. This may contain a query string, too." (see docs)

Also from the docs:

"If login is successful, the view redirects to the URL specified in next. If next isn’t provided, it redirects to settings.LOGIN_REDIRECT_URL (which defaults to /accounts/profile/)."

Example code:

urls.py

from django.urls import path
from django.contrib.auth import views as auth_views

from account.forms import LoginForm # optional form to pass to view


urlpatterns = [
    ...

    # --------------- login url/view -------------------
    path('account/login/', auth_views.LoginView.as_view(
        template_name='login.html',  
        authentication_form=LoginForm, 
        extra_context={ 

            # option 1: provide full path
            'next': '/account/my_custom_url/', 

            # option 2: just provide the name of the url
            # 'next': 'custom_url_name',  
        },
    ), name='login'),

    ...
]

login.html

...

<form method="post" action="{% url 'login' %}">

  ...

  {# option 1 #}
  <input type="hidden" name="next" value="{{ next }}">

  {# option 2 #}
  {# <input type="hidden" name="next" value="{% url next %}"> #}

</form>

Calling constructors in c++ without new

Both lines are in fact correct but do subtly different things.

The first line creates a new object on the stack by calling a constructor of the format Thing(const char*).

The second one is a bit more complex. It essentially does the following

  1. Create an object of type Thing using the constructor Thing(const char*)
  2. Create an object of type Thing using the constructor Thing(const Thing&)
  3. Call ~Thing() on the object created in step #1

Reducing video size with same format and reducing frame size

I found myself wanting to do this too recently, so I created a tool called Shrinkwrap that uses FFmpeg to transcode videos, while preserving as much of the original metadata as possible (including file modification timestamps).

You can run it as a docker container:

docker run -v /path/to/your/videos:/vids bennetimo/shrinkwrap \
--input-extension mp4 --ffmpeg-opts crf=22,preset=fast /vids

Where:

  • /path/to/your/videos/ is where the videos are that you want to convert
  • --input-extension is the type of videos you want to process, here .mp4
  • --ffmpeg-opts is any arbitrary FFmpeg options you want to use to customise the transcode

Then it will recursively find all of the video files that match the extension and transcode them all into files of the same name with a -tc suffix.

For more configuration options, presets for GoPro etc, see the readme.

Hope this helps someone!

Why is null an object and what's the difference between null and undefined?

null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object". But that is actually a bug (that might even be fixed in ECMAScript 6).

The difference between null and undefined is as follows:

  • undefined: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.

    > var noValueYet;
    > console.log(noValueYet);
    undefined
    
    > function foo(x) { console.log(x) }
    > foo()
    undefined
    
    > var obj = {};
    > console.log(obj.unknownProperty)
    undefined
    

    Accessing unknown variables, however, produces an exception:

    > unknownVariable
    ReferenceError: unknownVariable is not defined
    
  • null: used by programmers to indicate “no value”, e.g. as a parameter to a function.

Examining a variable:

console.log(typeof unknownVariable === "undefined"); // true

var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true

var bar = null;
console.log(bar === null); // true

As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check x == null is an edge case, because it works for both null and undefined:

> null == null
true
> undefined == null
true

A common way of checking whether a variable has a value is to convert it to boolean and see whether it is true. That conversion is performed by the if statement and the boolean operator ! (“not”).

function foo(param) {
    if (param) {
        // ...
    }
}
function foo(param) {
    if (! param) param = "abc";
}
function foo(param) {
    // || returns first operand that can't be converted to false
    param = param || "abc";
}

Drawback of this approach: All of the following values evaluate to false, so you have to be careful (e.g., the above checks can’t distinguish between undefined and 0).

  • undefined, null
  • Booleans: false
  • Numbers: +0, -0, NaN
  • Strings: ""

You can test the conversion to boolean by using Boolean as a function (normally it is a constructor, to be used with new):

> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true

How do I lowercase a string in Python?

Also, you can overwrite some variables:

s = input('UPPER CASE')
lower = s.lower()

If you use like this:

s = "Kilometer"
print(s.lower())     - kilometer
print(s)             - Kilometer

It will work just when called.

Git merge is not possible because I have unmerged files

The error message:

merge: remote/master - not something we can merge

is saying that Git doesn't recognize remote/master. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".

Think of "remotes" as an alias for the url to your Git server. master is your locally checked-out version of the branch. origin/master is the latest version of master from your Git server that you have fetched (downloaded). A fetch is always safe because it will only update the "origin/x" version of your branches.

So, to get your master branch back in sync, first download the latest content from the git server:

git fetch

Then, perform the merge:

git merge origin/master

...But, perhaps the better approach would be:

git pull origin master

The pull command will do the fetch and merge for you in one step.

Update Git submodule to latest commit on origin

Here's an awesome one-liner to update everything to the latest on master:

git submodule foreach 'git fetch origin --tags; git checkout master; git pull' && git pull && git submodule update --init --recursive

Thanks to Mark Jaquith

Convert base class to derived class

No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.

Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.

Parse error: Syntax error, unexpected end of file in my PHP code

I had the same error, but I had it fixed by modifying the php.ini file.

Find your php.ini file see Dude, where's my php.ini?

then open it with your favorite editor.

Look for a short_open_tag property, and apply the following change:

; short_open_tag = Off ; previous value
short_open_tag = On ; new value

How to convert base64 string to image?

This should do the trick:

image = open("image.png", "wb")
image.write(base64string.decode('base64'))
image.close()

Validating an XML against referenced XSD in C#

personally I favor validating without a callback:

public bool ValidateSchema(string xmlPath, string xsdPath)
{
    XmlDocument xml = new XmlDocument();
    xml.Load(xmlPath);

    xml.Schemas.Add(null, xsdPath);

    try
    {
        xml.Validate(null);
    }
    catch (XmlSchemaValidationException)
    {
        return false;
    }
    return true;
}

(see Timiz0r's post in Synchronous XML Schema Validation? .NET 3.5)

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

Save and load weights in keras

For loading weights, you need to have a model first. It must be:

existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')     

If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):

model.save_model('filename')
model = load_model('filename')

Hash Table/Associative Array in VBA

I've used Francesco Balena's HashTable class several times in the past when a Collection or Dictionary wasn't a perfect fit and i just needed a HashTable.

Change EditText hint color when using TextInputLayout

Looks like the parent view had a style for a 3rd party library that was causing the EditText to be white.

android:theme="@style/com_mixpanel_android_SurveyActivityTheme"

Once I removed this everything worked fine.

How to get the MD5 hash of a file in C++?

For anyone redirected from "https://stackoverflow.com/questions/4393017/md5-implementation-in-c" because it's been incorrectly labelled a duplicate.

The example located here works:

http://www.zedwood.com/article/cpp-md5-function

If you are compiling in VC++2010 then you will need to change his main.cpp to this:

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    std::string Temp =  md5("The quick brown fox jumps over the lazy dog");
    cout << Temp.c_str() << endl;

    return 0;
}

You will have to change the MD5 class slightly if you are to read in a char * array instead of a string to answer the question on this page here.

EDIT:

Apparently modifying the MD5 library isn't clear, well a Full VC++2010 solution is here for your convenience to include char *'s:

https://github.com/alm4096/MD5-Hash-Example-VS

A bit of an explanation is here:

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include <fstream>
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    //Start opening your file
    ifstream inBigArrayfile;
    inBigArrayfile.open ("Data.dat", std::ios::binary | std::ios::in);

    //Find length of file
    inBigArrayfile.seekg (0, std::ios::end);
    long Length = inBigArrayfile.tellg();
    inBigArrayfile.seekg (0, std::ios::beg);    

    //read in the data from your file
    char * InFileData = new char[Length];
    inBigArrayfile.read(InFileData,Length);

    //Calculate MD5 hash
    std::string Temp =  md5(InFileData,Length);
    cout << Temp.c_str() << endl;

    //Clean up
    delete [] InFileData;

    return 0;
}

I have simply added the following into the MD5 library:

MD5.cpp:

MD5::MD5(char * Input, long length)
{
  init();
  update(Input, length);
  finalize();
}

MD5.h:

std::string md5(char * Input, long length);

Convert a number range to another range, maintaining ratio

Here's some short Python functions for your copy and paste ease, including a function to scale an entire list.

def scale_number(unscaled, to_min, to_max, from_min, from_max):
    return (to_max-to_min)*(unscaled-from_min)/(from_max-from_min)+to_min

def scale_list(l, to_min, to_max):
    return [scale_number(i, to_min, to_max, min(l), max(l)) for i in l]

Which can be used like so:

scale_list([1,3,4,5], 0, 100)

[0.0, 50.0, 75.0, 100.0]

In my case I wanted to scale a logarithmic curve, like so:

scale_list([math.log(i+1) for i in range(5)], 0, 50)

[0.0, 21.533827903669653, 34.130309724299266, 43.06765580733931, 50.0]

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

AngularJs: How to set radio button checked based on model

Just do something like this,<input type="radio" ng-disabled="loading" name="dateRange" ng-model="filter.DateRange" value="1" ng-checked="(filter.DateRange == 1)"/>

What are the differences between WCF and ASMX web services?

ASMX Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.

Second, ASMX web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

As the error information said first please try to increase the timeout value in the both the client side and service side as following:

<basicHttpBinding>
    <binding name="basicHttpBinding_ACRMS" maxBufferSize="2147483647"
      maxReceivedMessageSize="2147483647"
      openTimeout="00:20:00" 
      receiveTimeout="00:20:00" closeTimeout="00:20:00"
      sendTimeout="00:20:00">
      <readerQuotas maxDepth="32" maxStringContentLength="2097152"
        maxArrayLength="2097152" maxBytesPerRead="4006" maxNameTableCharCount="16384" />
    </binding>

Then please do not forget to apply this binding configuration to the endpoint by doing the following:

<endpoint address="" binding="basicHttpBinding" 
      bindingConfiguration="basicHttpBinding_ACRMS"
      contract="MonitorRAM.IService1" />

If the above can not help, it will be better if you can try to upload your main project here, then I want to have a test in my side.

Access props inside quotes in React JSX

If you're using JSX with Harmony, you could do this:

<img className="image" src={`images/${this.props.image}`} />

Here you are writing the value of src as an expression.

Best way to create a temp table with same columns and type as a permanent table

I realize this question is extremely old, but for anyone looking for a solution specific to PostgreSQL, it's:

CREATE TEMP TABLE tmp_table AS SELECT * FROM original_table LIMIT 0;

Note, the temp table will be put into a schema like pg_temp_3.

This will create a temporary table that will have all of the columns (without indexes) and without the data, however depending on your needs, you may want to then delete the primary key:

ALTER TABLE pg_temp_3.tmp_table DROP COLUMN primary_key;

If the original table doesn't have any data in it to begin with, you can leave off the "LIMIT 0".

Why doesn't Java support unsigned ints?

This is from an interview with Gosling and others, about simplicity:

Gosling: For me as a language designer, which I don't really count myself as these days, what "simple" really ended up meaning was could I expect J. Random Developer to hold the spec in his head. That definition says that, for instance, Java isn't -- and in fact a lot of these languages end up with a lot of corner cases, things that nobody really understands. Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex. The language part of Java is, I think, pretty simple. The libraries you have to look up.

MySQL: Check if the user exists and drop it

If you mean you want to delete a drop from a table if it exists, you can use the DELETE command, for example:

 DELETE FROM users WHERE user_login = 'foobar'

If no rows match, it's not an error.

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes:

'20100301'

SQL Server allows for many accepted date formats and it should be the case that most development libraries provide a series of classes or functions to insert datetime values properly. However, if you are doing it manually, it is important to distinguish the date format using DateFormat and to use generalized format:

Set DateFormat MDY --indicates the general format is Month Day Year

Insert Table( DateTImeCol )
Values( '2011-03-12' )

By setting the dateformat, SQL Server now assumes that my format is YYYY-MM-DD instead of YYYY-DD-MM.

SET DATEFORMAT

SQL Server also recognizes a generic format that is always interpreted the same way: YYYYMMDD e.g. 20110312.

If you are asking how to insert the current date and time using T-SQL, then I would recommend using the keyword CURRENT_TIMESTAMP. For example:

Insert Table( DateTimeCol )
Values( CURRENT_TIMESTAMP )

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Android and setting alpha for (image) view alpha

setAlpha(int) is deprecated as of API 16: Android 4.1

Please use setImageAlpha(int) instead

Get MD5 hash of big files in Python

You need to read the file in chunks of suitable size:

def md5_for_file(f, block_size=2**20):
    md5 = hashlib.md5()
    while True:
        data = f.read(block_size)
        if not data:
            break
        md5.update(data)
    return md5.digest()

NOTE: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.

So to do the whole lot in one method - use something like:

def generate_file_md5(rootdir, filename, blocksize=2**20):
    m = hashlib.md5()
    with open( os.path.join(rootdir, filename) , "rb" ) as f:
        while True:
            buf = f.read(blocksize)
            if not buf:
                break
            m.update( buf )
    return m.hexdigest()

The update above was based on the comments provided by Frerich Raabe - and I tested this and found it to be correct on my Python 2.7.2 windows installation

I cross-checked the results using the 'jacksum' tool.

jacksum -a md5 <filename>

http://www.jonelo.de/java/jacksum/

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

How to use boolean datatype in C?

C99 has a bool type. To use it,

#include <stdbool.h>

base 64 encode and decode a string in angular (2+)

For encoding to base64 in Angular2, you can use btoa() function.

Example:-

console.log(btoa("stringAngular2")); 
// Output:- c3RyaW5nQW5ndWxhcjI=

For decoding from base64 in Angular2, you can use atob() function.

Example:-

console.log(atob("c3RyaW5nQW5ndWxhcjI=")); 
// Output:- stringAngular2

Error: No module named psycopg2.extensions

For macOS Mojave just run pip install psycopg2-binary. Works fine for me, python version -> Python 3.7.2

How can I create a link to a local file on a locally-run web page?

You need to use the file:/// protocol (yes, that's three slashes) if you want to link to local files.

<a href="file:///C:\Programs\sort.mw">Link 1</a>
<a href="file:///C:\Videos\lecture.mp4">Link 2</a>

These will never open the file in your local applications automatically. That's for security reasons which I'll cover in the last section. If it opens, it will only ever open in the browser. If your browser can display the file, it will, otherwise it will probably ask you if you want to download the file.

You cannot cross from http(s) to the file protocol

Modern versions of many browsers (e.g. Firefox and Chrome) will refuse to cross from the http(s) protocol to the file protocol to prevent malicious behaviour.

This means a webpage hosted on a website somewhere will never be able to link to files on your hard drive. You'll need to open your webpage locally using the file protocol if you want to do this stuff at all.

Why does it get stuck without file:///?

The first part of a URL is the protocol. A protocol is a few letters, then a colon and two slashes. HTTP:// and FTP:// are valid protocols; C:/ isn't and I'm pretty sure it doesn't even properly resemble one.

C:/ also isn't a valid web address. The browser could assume it's meant to be http://c/ with a blank port specified, but that's going to fail.

Your browser may not assume it's referring to a local file. It has little reason to make that assumption because webpages generally don't try to link to peoples' local files.

So if you want to access local files: tell it to use the file protocol.

Why three slashes?

Because it's part of the File URI scheme. You have the option of specifying a host after the first two slashes. If you skip specifying a host it will just assume you're referring to a file on your own PC. This means file:///C:/etc is a shortcut for file://localhost/C:/etc.

These files will still open in your browser and that is good

Your browser will respond to these files the same way they'd respond to the same file anywhere on the internet. These files will not open in your default file handler (e.g. MS Word or VLC Media Player), and you will not be able to do anything like ask File Explorer to open the file's location.

This is an extremely good thing for your security.

Sites in your browser cannot interact with your operating system very well. If a good site could tell your machine to open lecture.mp4 in VLC.exe, a malicious site could tell it to open virus.bat in CMD.exe. Or it could just tell your machine to run a few Uninstall.exe files or open File Explorer a million times.

This may not be convenient for you, but HTML and browser security weren't really designed for what you're doing. If you want to be able to open lecture.mp4 in VLC.exe consider writing a desktop application instead.

DateTime group by date and hour

In my case... with MySQL:

SELECT ... GROUP BY TIMESTAMPADD(HOUR, HOUR(columName), DATE(columName))

Parsing JSON with Unix tools

For more complex JSON parsing I suggest using python jsonpath module (by Stefan Goessner) -

  1. Install it -

sudo easy_install -U jsonpath

  1. Use it -

Example file.json (from http://goessner.net/articles/JsonPath) -

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

Parse it (extract all book titles with price < 10) -

$ cat file.json | python -c "import sys, json, jsonpath; print '\n'.join(jsonpath.jsonpath(json.load(sys.stdin), 'store.book[?(@.price < 10)].title'))"

Will output -

Sayings of the Century
Moby Dick

NOTE: The above command line does not include error checking. for full solution with error checking you should create small python script, and wrap the code with try-except.

Android new Bottom Navigation bar or BottomNavigationView

My original answer dealt with the BottomNavigationView, but now there is a BottomAppBar. I added a section at the top for that with an implementation link.

Bottom App Bar

The BottomAppBar supports a Floating Action Button.

enter image description here

Image from here. See the documentation and this tutorial for help setting up the BottomAppBar.

Bottom Navigation View

The following full example shows how to make a Bottom Navigation View similar to the image in the question. See also Bottom Navigation in the documentation.

enter image description here

Add the design support library

Add this line to your app's build.grade file next to the other support library things.

implementation 'com.android.support:design:28.0.0'

Replace the version number with whatever is current.

Create the Activity layout

The only special thing we have added to the layout is the BottomNavigationView. To change the color of the icon and text when it is clicked, you can use a selector instead of specifying the color directly. This is omitted for simplicity here.

activity_main.xml

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

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_nav_menu"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white" />

</RelativeLayout>

Notice that we used layout_alignParentBottom to actually put it at the bottom.

Define the menu items

The xml above for Bottom Navigation View referred to bottom_nav_menu. This is what defines each item in our view. We will make it now. All you have to do is add a menu resource just like you would for an Action Bar or Toolbar.

bottom_nav_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_recents"
        android:enabled="true"
        android:icon="@drawable/ic_action_recents"
        android:title="Recents"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_favorites"
        android:enabled="true"
        android:icon="@drawable/ic_action_favorites"
        android:title="Favorites"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_nearby"
        android:enabled="true"
        android:icon="@drawable/ic_action_nearby"
        android:title="Nearby"
        app:showAsAction="ifRoom" />
</menu>

You will need to add the appropriate icons to your project. This is not very difficult if you go to File > New > Image Asset and choose Action Bar and Tab Icons as the Icon Type.

Add an item selected listener

There is nothing special happening here. We just add a listener to the Bottom Navigation Bar in our Activity's onCreate method.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_recents:
                        Toast.makeText(MainActivity.this, "Recents", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_favorites:
                        Toast.makeText(MainActivity.this, "Favorites", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.action_nearby:
                        Toast.makeText(MainActivity.this, "Nearby", Toast.LENGTH_SHORT).show();
                        break;

                }
                return true;
            }
        });
    }
}

Need more help?

I learned how to do this watching the following YouTube video. The computer voice is a little strange, but the demonstration is very clear.

Format cell color based on value in another sheet and cell

Here's how I did it in Excel 2003 using conditional formatting.

To apply conditional formatting to Sheet1 using values from Sheet2, you need to mirror the values into Sheet1.

Creating a mirror of Sheet2, column B in Sheet 1

  1. Go to Sheet1.
  2. Insert a new column by right-clicking column A's header and selecting "Insert".
  3. Enter the following formula into A1:

    =IF(ISBLANK(Sheet2!B1),"",Sheet2!B1)

  4. Copy A1 by right-clicking it and selecting "Copy".
  5. Paste the formula into column A by right-clicking its header and selecting "Paste".

Sheet1, column A should now exactly mirror the values in Sheet2, column B.

(Note: if you don't like it in column A, it works just as well to have it in column Z or anywhere else.)

Applying the conditional formatting

  1. Stay on Sheet1.
  2. Select column B by left-clicking its header.
  3. Select the menu item Format > Conditional Formatting...
  4. Change Condition 1 to "Formula is" and enter this formula:

    =MATCH(B1,$A:$A,0)

  5. Click the Format... button and select a green background.

You should now see the green background applied to the matching cells in Sheet1.

Hiding the mirror column

  1. Stay on Sheet1.
  2. Right-click the header on column A and select "Hide".

This should automatically update Sheet1 whenever anything in Sheet2 is changed.

Prevent cell numbers from incrementing in a formula in Excel

TL:DR
row lock = A$5
column lock = $A5
Both = $A$5

Below are examples of how to use the Excel lock reference $ when creating your formulas

To prevent increments when moving from one row to another put the $ after the column letter and before the row number. e.g. A$5

To prevent increments when moving from one column to another put the $ before the row number. e.g. $A5

To prevent increments when moving from one column to another or from one row to another put the $ before the row number and before the column letter. e.g. $A$5

Using the lock reference will also prevent increments when dragging cells over to duplicate calculations.

jQuery datepicker set selected date, on the fly

What version of jQuery-UI are you using? I've tested the following with 1.6r6, 1.7 and 1.7.1 and it works:

//Set DatePicker to October 3, 2008
$('#dateselector').datepicker("setDate", new Date(2008,9,03) );

How to use MySQLdb with Python and Django in OSX 10.6?

This worked for Red Hat Enterprise Linux Server release 6.4

sudo yum install mysql-devel
sudo yum install python-devel
pip install mysql-python

How to add a href link in PHP?

you have problems with " :

 <a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>

Double vs. BigDecimal?

If you write down a fractional value like 1 / 7 as decimal value you get

1/7 = 0.142857142857142857142857142857142857142857...

with an infinite sequence of 142857. Since you can only write a finite number of digits you will inevitably introduce a rounding (or truncation) error.

Numbers like 1/10 or 1/100 expressed as binary numbers with a fractional part also have an infinite number of digits after the decimal point:

1/10 = binary 0.0001100110011001100110011001100110...

Doubles store values as binary and therefore might introduce an error solely by converting a decimal number to a binary number, without even doing any arithmetic.

Decimal numbers (like BigDecimal), on the other hand, store each decimal digit as is (binary coded, but each decimal on its own). This means that a decimal type is not more precise than a binary floating point or fixed point type in a general sense (i.e. it cannot store 1/7 without loss of precision), but it is more accurate for numbers that have a finite number of decimal digits as is often the case for money calculations.

Java's BigDecimal has the additional advantage that it can have an arbitrary (but finite) number of digits on both sides of the decimal point, limited only by the available memory.

No grammar constraints (DTD or XML schema) detected for the document

i know this is old but I'm passing trought the same problem and found the solution in the spring documentation, the following xml configuration has been solved the problem for me.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx 

<!-- THIS IS THE LINE THAT SOLVE MY PROBLEM -->
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 

http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

before I put the line above as sugested in this forum topic , I have the same warning message, and placing this...

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>

and it give me the following warning message...

The content of element type "template" must match "
(description,variation?,variation-field?,allow- multiple-variation?,class-
pattern?,getter-setter?,allowed-file-extensions?,number-required- 
classes?,template-body)".

so just try to use the sugested lines of my xml configuration.

How to sort a HashSet?

Use java.util.TreeSet as the actual object. When you iterate over this collection, the values come back in a well-defined order.

If you use java.util.HashSet then the order depends on an internal hash function which is almost certainly not lexicographic (based on content).

How do I use cx_freeze?

find the cxfreeze script and run it. It will be in the same path as your other python helper scripts, such as pip.

cxfreeze Main.py --target-dir dist

read more at: http://cx-freeze.readthedocs.org/en/latest/script.html#script

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

go to c->users->[Your user account]-> remove android 1.2 and restart the android studio when it ask to import select first radio button which is import setting from previous config

there you go fixed

CSS styling in Django forms

You can do:

<form action="" method="post">
    <table>
        {% for field in form %}
        <tr><td>{{field}}</td></tr>
        {% endfor %}
    </table>
    <input type="submit" value="Submit">
</form>

Then you can add classes/id's to for example the <td> tag. You can of course use any others tags you want. Check Working with Django forms as an example what is available for each field in the form ({{field}} for example is just outputting the input tag, not the label and so on).

jQuery callback for multiple ajax calls

I got some good hints from the answers on this page. I adapted it a bit for my use and thought I could share.

// lets say we have 2 ajax functions that needs to be "synchronized". 
// In other words, we want to know when both are completed.
function foo1(callback) {
    $.ajax({
        url: '/echo/html/',
        success: function(data) {
            alert('foo1');
            callback();               
        }
    });
}

function foo2(callback) {
    $.ajax({
        url: '/echo/html/',
        success: function(data) {
            alert('foo2');
            callback();
        }
    });
}

// here is my simplified solution
ajaxSynchronizer = function() {
    var funcs = [];
    var funcsCompleted = 0;
    var callback;

    this.add = function(f) {
        funcs.push(f);
    }

    this.synchronizer = function() {
        funcsCompleted++;
        if (funcsCompleted == funcs.length) {
            callback.call(this);
        }
    }

    this.callWhenFinished = function(cb) {
        callback = cb;
        for (var i = 0; i < funcs.length; i++) {
            funcs[i].call(this, this.synchronizer);
        }
    }
}

// this is the function that is called when both ajax calls are completed.
afterFunction = function() {
    alert('All done!');
}

// this is how you set it up
var synchronizer = new ajaxSynchronizer();
synchronizer.add(foo1);
synchronizer.add(foo2);
synchronizer.callWhenFinished(afterFunction);

There are some limitations here, but for my case it was ok. I also found that for more advanced stuff it there is also a AOP plugin (for jQuery) that might be useful: http://code.google.com/p/jquery-aop/