Programs & Examples On #Bitblt

BitBlt WinAPI function performs a bit-block transfer of the color data corresponding to a rectangle of pixels from the specified source device context into a destination device context.

Eclipse error: indirectly referenced from required .class files?

I had this error because of a corrupted local maven repository.

So, in order to fix the problem, all I had to do was going in my repository and delete the folder where the concerned .jar was, then force an update maven in Eclipse.

How can I find out if an .EXE has Command-Line Options?

Just use IDA PRO (https://www.hex-rays.com/products/ida/index.shtml) to disassemble the file, and search for some known command line option (using Search...Text) - in that section you will then typically see all the command line options - for the program (LIB2NIST.exe) in the screenshot below, for example, it shows a documented command line option (/COM2TAG) but also some undocumented ones, like /L. Hope this helps?

enter image description here

What is a LAMP stack?

LAMP means: L = Linux (OS) A = Apache (web server) M = MySQL (database) P = PHP (language)

From LAMP (Wikipedia):

Short for Linux, Apache, MySQL and PHP, an open-source Web development platform, also called a Web stack, that uses Linux as the operating system, Apache as the Web server, MySQL as the RDBMS and PHP as the object-oriented scripting language. Perl or Python is often substituted for PHP.

Assign output of a program to a variable using a MS batch file

In addition to the answer, you can't directly use output redirection operators in the set part of for loop (e.g. if you wanna hide stderror output from a user and provide a nicer error message). Instead, you have to escape them with a caret character (^):

for /f %%O in ('some-erroring-command 2^> nul') do (echo %%O)

Reference: Redirect output of command in for loop of batch script

Combining "LIKE" and "IN" for SQL Server

No, MSSQL doesn't allow such queries. You should use col LIKE '...' OR col LIKE '...' etc.

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

What's the best way to generate a UML diagram from Python source code?

Epydoc is a tool to generate API documentation from Python source code. It also generates UML class diagrams, using Graphviz in fancy ways. Here is an example of diagram generated from the source code of Epydoc itself.

Because Epydoc performs both object introspection and source parsing it can gather more informations respect to static code analysers such as Doxygen: it can inspect a fair amount of dynamically generated classes and functions, but can also use comments or unassigned strings as a documentation source, e.g. for variables and class public attributes.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

See my post here

How are you? I had the same problem while i was trying connect to MSSQL Server remotely using jdbc (dbeaver on debian).

After a while, i found out that my firewall configuration was not correctly. So maybe it could help you!

Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.

Four exceptions must be configured in Windows Firewall to allow access to SQL Server:

A port exception for TCP Port 1433. In the New Inbound Rule Wizard dialog, use the following information to create a port exception: Select Port Select TCP and specify port 1433 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – TCP 1433" A port exception for UDP Port 1434. Click New Rule again and use the following information to create another port exception: Select Port Select UDP and specify port 1434 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – UDP 1434 A program exception for sqlservr.exe. Click New Rule again and use the following information to create a program exception: Select Program Click Browse to select ‘sqlservr.exe’ at this location: [C:\Program Files\Microsoft SQL Server\MSSQL11.\MSSQL\Binn\sqlservr.exe] where is the name of your SQL instance. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL – sqlservr.exe A program exception for sqlbrowser.exe Click New Rule again and use the following information to create another program exception: Select Program Click Browse to select sqlbrowser.exe at this location: [C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe]. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL - sqlbrowser.exe

Source: http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/

Getting the difference between two sets

Adding a solution which I've recently used myself and haven't seen mentioned here. If you have Apache Commons Collections available then you can use the SetUtils#difference method:

// Returns all the elements of test2 which are not in test1
SetUtils.difference(test2, test1) 

Note that according to the documentation the returned set is an unmodifiable view:

Returns a unmodifiable view containing the difference of the given Sets, denoted by a \ b (or a - b). The returned view contains all elements of a that are not a member of b.

Full documentation: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/SetUtils.html#difference-java.util.Set-java.util.Set-

How to directly move camera to current location in Google Maps Android API v2?

make sure you have these permissions:

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

Then make some activity and register a LocationListener

package com.example.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class LocationActivity extends SherlockFragmentActivity implements LocationListener     {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER        
}

@Override
public void onLocationChanged(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
    map.animateCamera(cameraUpdate);
    locationManager.removeUpdates(this);
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }

@Override
public void onProviderEnabled(String provider) { }

@Override
public void onProviderDisabled(String provider) { }
}

map.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>

Sorting Python list based on the length of the string

I Would like to add how the pythonic key function works while sorting :

Decorate-Sort-Undecorate Design Pattern :

Python’s support for a key function when sorting is implemented using what is known as the decorate-sort-undecorate design pattern.

It proceeds in 3 steps:

  1. Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element.

  2. The list is sorted based upon the natural order of the keys.

  3. The decorated elements are replaced by the original elements.

Key parameter to specify a function to be called on each list element prior to making comparisons. docs

Installing Python packages from local file system folder to virtualenv with pip

Having requirements in requirements.txt and egg_dir as a directory

you can build your local cache:

$ pip download -r requirements.txt -d eggs_dir

then, using that "cache" is simple like:

$ pip install -r requirements.txt --find-links=eggs_dir

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

https://support.google.com/a/answer/3001912?hl=en

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

How to get current page URL in MVC 3

You could use the Request.RawUrl, Request.Url.OriginalString, Request.Url.ToString() or Request.Url.AbsoluteUri.

How to return rows from left table not found in right table?

Try This

SELECT f.*
FROM first_table f LEFT JOIN second_table s ON f.key=s.key
WHERE s.key is NULL

For more please read this article : Joins in Sql Server

enter image description here

Linq with group by having count

Like this:

from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key

Or, using the method syntax:

Company
    .GroupBy(c => c.Name)
    .Where(grp => grp.Count() > 1)
    .Select(grp => grp.Key);

Excel 2010: how to use autocomplete in validation list

Here's another option. It works by putting an ActiveX ComboBox on top of the cell with validation enabled, and then providing autocomplete in the ComboBox instead.

Option Explicit

' Autocomplete - replacing validation lists with ActiveX ComboBox
'
' Usage:
'   1. Copy this code into a module named m_autocomplete
'   2. Go to Tools / References and make sure "Microsoft Forms 2.0 Object Library" is checked
'   3. Copy and paste the following code to the worksheet where you want autocomplete
'      ------------------------------------------------------------------------------------------------------
'      - autocomplete
'      Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'          m_autocomplete.SelectionChangeHandler Target
'      End Sub
'      Private Sub AutoComplete_Combo_KeyDown(ByVal KeyCode As msforms.ReturnInteger, ByVal Shift As Integer)
'          m_autocomplete.KeyDownHandler KeyCode, Shift
'      End Sub
'      Private Sub AutoComplete_Combo_Click()
'          m_autocomplete.AutoComplete_Combo_Click
'      End Sub
'      ------------------------------------------------------------------------------------------------------

' When the combobox is clicked, it should dropdown (expand)
Public Sub AutoComplete_Combo_Click()
    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim cbo As OLEObject: Set cbo = GetComboBoxObject(ws)
    Dim cb As ComboBox: Set cb = cbo.Object
    If cbo.Visible Then cb.DropDown
End Sub

' Make it easier to navigate between cells
Public Sub KeyDownHandler(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Const UP As Integer = -1
    Const DOWN As Integer = 1

    Const K_TAB_______ As Integer = 9
    Const K_ENTER_____ As Integer = 13
    Const K_ARROW_UP__ As Integer = 38
    Const K_ARROW_DOWN As Integer = 40

    Dim direction As Integer: direction = 0

    If Shift = 0 And KeyCode = K_TAB_______ Then direction = DOWN
    If Shift = 0 And KeyCode = K_ENTER_____ Then direction = DOWN
    If Shift = 1 And KeyCode = K_TAB_______ Then direction = UP
    If Shift = 1 And KeyCode = K_ENTER_____ Then direction = UP
    If Shift = 1 And KeyCode = K_ARROW_UP__ Then direction = UP
    If Shift = 1 And KeyCode = K_ARROW_DOWN Then direction = DOWN

    If direction <> 0 Then ActiveCell.Offset(direction, 0).Activate

    AutoComplete_Combo_Click
End Sub

Public Sub SelectionChangeHandler(ByVal Target As Range)
    On Error GoTo errHandler

    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim cbo As OLEObject: Set cbo = GetComboBoxObject(ws)
    Dim cb As ComboBox: Set cb = cbo.Object

    ' Try to hide the ComboBox. This might be buggy...
    If cbo.Visible Then
        cbo.Left = 10
        cbo.Top = 10
        cbo.ListFillRange = ""
        cbo.LinkedCell = ""
        cbo.Visible = False
        Application.ScreenUpdating = True
        ActiveSheet.Calculate
        ActiveWindow.SmallScroll
        Application.WindowState = Application.WindowState
        DoEvents
    End If

    If Not HasValidationList(Target) Then GoTo ex

    Application.EnableEvents = False

    ' TODO: the code below is a little fragile
    Dim lfr As String
    lfr = Mid(Target.Validation.Formula1, 2)
    lfr = Replace(lfr, "INDIREKTE", "") ' norwegian
    lfr = Replace(lfr, "INDIRECT", "") ' english
    lfr = Replace(lfr, """", "")
    lfr = Application.Range(lfr).Address(External:=True)

    cbo.ListFillRange = lfr
    cbo.Visible = True
    cbo.Left = Target.Left
    cbo.Top = Target.Top
    cbo.Height = Target.Height + 5
    cbo.Width = Target.Width + 15
    cbo.LinkedCell = Target.Address(External:=True)
    cbo.Activate
    cb.SelStart = 0
    cb.SelLength = cb.TextLength
    cb.DropDown

    GoTo ex

errHandler:
    Debug.Print "Error"
    Debug.Print Err.Number
    Debug.Print Err.Description
ex:
    Application.EnableEvents = True
End Sub

' Does the cell have a validation list?
Function HasValidationList(Cell As Range) As Boolean
    HasValidationList = False
    On Error GoTo ex
    If Cell.Validation.Type = xlValidateList Then HasValidationList = True
ex:
End Function

' Retrieve or create the ComboBox
Function GetComboBoxObject(ws As Worksheet) As OLEObject
    Dim cbo As OLEObject
    On Error Resume Next
    Set cbo = ws.OLEObjects("AutoComplete_Combo")
    On Error GoTo 0
    If cbo Is Nothing Then
        'Dim EnableSelection As Integer: EnableSelection = ws.EnableSelection
        Dim ProtectContents As Boolean: ProtectContents = ws.ProtectContents

        Debug.Print "Lager AutoComplete_Combo"
        If ProtectContents Then ws.Unprotect
        Set cbo = ws.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
                            Left:=50, Top:=18.75, Width:=129, Height:=18.75)
        cbo.name = "AutoComplete_Combo"
        cbo.Object.MatchRequired = True
        cbo.Object.ListRows = 12
        If ProtectContents Then ws.Protect
    End If
    Set GetComboBoxObject = cbo
End Function

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

That for changing directory of the XAMPP. So you have to change the Directory as well as ServerRoot "E:/xampp/apache"

DocumentRoot "E:/xampp/htdocs"


<Directory "E:/xampp/htdocs">


ScriptAlias /cgi-bin/ "E:/xampp/cgi-bin/"


<Directory "E:/xampp/cgi-bin">
    AllowOverride All
    Options None
    Require all granted
</Directory>

I also facing same problem for changing My laptop. thanks

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

Validate Dynamically Added Input fields

You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.

And here is my solution that I've tested and it works:

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
            numberIncr++;
        }

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // prevent default submit action         
            event.preventDefault();

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
        })

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator
        $('form.commentForm').validate();

   });


</script>

And the html form part:

<form class="commentForm" method="get" action="">
    <div>

        <p id="inputs">    
            <input class="comment" name="name0" />
        </p>

    <input class="submit" type="submit" value="Submit" />
    <input type="button" value="add" id="addInput" />

    </div>
</form>

Good luck! Please approve answer if it suits you!

ArrayAdapter in android to create simple listview

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)

Here, resource means the 'id' of the Layout you are using while instantiating the view.

Now, this layout has many child views with their own ids. So, textViewResourceId tells which child view we need to populate with the data.

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

BEST solution if you ask me is this. This will save the file with the file name of your choice and automatically in HTML or in TXT at your choice with buttons.

Example:

_x000D_
_x000D_
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}

function addTextHTML()
{
    document.addtext.name.value = document.addtext.name.value + ".html"
}

function addTextTXT()
{
    document.addtext.name.value = document.addtext.name.value + ".txt"
}
_x000D_
<html>
  <head></head>
  <body>

    <form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">

    <textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea>
    <br>
    <input type="text" name="name" value="" placeholder="File Name">
    <input type="submit" onClick="addTextHTML();" value="Save As HTML">
    <input type="submit" onClick="addTexttxt();" value="Save As TXT">

    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

Amazon AWS Filezilla transfer permission denied

In my case the /var/www/html in not a directory but a symbolic link to the /var/app/current, so you should change the real directoy ie /var/app/current:

sudo chown -R ec2-user /var/app/current
sudo chmod -R 755 /var/app/current

I hope this save some of your times :)

Add a pipe separator after items in an unordered list unless that item is the last on a line

This is possible with flex-box

The keys to this technique:

  • A container element set to overflow: hidden.
  • Set justify-content: space-between on the ul (which is a flex-box) to force its flex-items to stretch to the left and right edges.
  • Set margin-left: -1px on the ul to cause its left edge to overflow the container.
  • Set border-left: 1px on the li flex-items.

The container acts as a mask hiding the borders of any flex-items touching its left edge.

_x000D_
_x000D_
.flex-list {
    position: relative;
    margin: 1em;
    overflow: hidden;
}
.flex-list ul {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-left: -1px;
}
.flex-list li {
    flex-grow: 1;
    flex-basis: auto;
    margin: .25em 0;
    padding: 0 1em;
    text-align: center;
    border-left: 1px solid #ccc;
    background-color: #fff;
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>
<div class="flex-list">
    <ul>
        <li>Dogs</li>
        <li>Cats</li>
        <li>Lions</li>
        <li>Tigers</li>
        <li>Zebras</li>
        <li>Giraffes</li>
        <li>Bears</li>
        <li>Hippopotamuses</li>
        <li>Antelopes</li>
        <li>Unicorns</li>
        <li>Seagulls</li>
    </ul>
</div>
_x000D_
_x000D_
_x000D_

CSS Transition doesn't work with top, bottom, left, right

Something that is not relevant for the OP, but maybe for someone else in the future:

For pixels (px), if the value is "0", the unit can be omitted: right: 0 and right: 0px both work.

However I noticed that in Firefox and Chrome this is not the case for the seconds unit (s). While transition: right 1s ease 0s works, transition: right 1s ease 0 (missing unit s for last value transition-delay) does not (it does work in Edge however).

In the following example, you'll see that right works for both 0px and 0, but transition only works for 0s and it doesn't work with 0.

_x000D_
_x000D_
#box {_x000D_
    border: 1px solid black;_x000D_
    height: 240px;_x000D_
    width: 260px;_x000D_
    margin: 50px;_x000D_
    position: relative;_x000D_
}_x000D_
.jump {_x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    color: white;_x000D_
    padding: 5px;_x000D_
}_x000D_
#jump1 {_x000D_
    background-color: maroon;_x000D_
    top: 0px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0s;_x000D_
}_x000D_
#jump2 {_x000D_
    background-color: green;_x000D_
    top: 60px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0s;_x000D_
}_x000D_
#jump3 {_x000D_
    background-color: blue;_x000D_
    top: 120px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0;_x000D_
}_x000D_
#jump4 {_x000D_
    background-color: gray;_x000D_
    top: 180px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0;_x000D_
}_x000D_
#box:hover .jump {_x000D_
    right: 50px;_x000D_
}
_x000D_
<div id="box">_x000D_
  <div class="jump" id="jump1">right: 0px<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump2">right: 0<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump3">right: 0px<br>transition: right 1s ease 0</div>_x000D_
  <div class="jump" id="jump4">right: 0<br>transition: right 1s ease 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Entity Framework select distinct name

Entity-Framework Select Distinct Name:

Suppose if you are using Views in which you are using multiple tables and you want to apply distinct in that case first you have to store value in variable & then you can apply Distinct on that variable like this one....

public List<Item_Img_Sal_VIEW> GetItemDescription(int ItemNo) 
        {
            var Result= db.Item_Img_Sal_VIEW.Where(p => p.ItemID == ItemNo).ToList();
            return Result.Distinct().ToList();
        }

Or you can try this Simple Example

Public Function GetUniqueLocation() As List(Of Integer)
          Return db.LoginUsers.Select(Function(p) p.LocID).Distinct().ToList()
End Function

Greyscale Background Css Images

I know it's a really old question, but it's the first result on duckduckgo, so I wanted to share what I think it's a better and more modern solution.

You can use background-blend-mode property to achieve a greyscale image:

#something {
  background-color: #fff;
  background-image: url("yourimage");
  background-blend-mode: luminosity;
}

If you want to remove the effect, just change the blend-mode to initial.

You may need to play a little bit with the background-color if this element is over something with a background. What I've found is that the greyscale does not depend on the actual color but on the alpha value. So, if you have a blue background on the parent, set the same background on #something.

You can also use two images, one with color and the other without and set both as background and play with other blend modes.

https://www.w3schools.com/cssref/pr_background-blend-mode.asp

It won't work on Edge though.

EDIT: I've miss the "fade" part of the question.

If you wan't to make it fade from/to grayscale, you can use a css transition on the background color changeing it's alpha value:

#something {
  background-color: rgba(255,255,255,1);
  background-image: url("yourimage");
  background-blend-mode: luminosity;
  transition: background-color 1s ease-out;
}
#something:hover {
  background-color: rgba(255,255,255,0);
}

I'm also adding a codepen example for completeness https://codepen.io/anon/pen/OBKKVZ

Adding css class through aspx code behind

Assuming your div has some CSS classes already...

<div id="classMe" CssClass="first"></div>

The following won't replace existing definitions:

ClassMe.CssClass += " second";

And if you are not sure until the very last moment...

string classes = ClassMe.CssClass;
ClassMe.CssClass += (classes == "") ? "second" : " second";

Object cannot be cast from DBNull to other types

Reason for the error: In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source:MSDN

Actual Code which I faced error:

Before changed the code:

    if( ds.Tables[0].Rows[0][0] == null ) //   Which is not working

     {
            seqno  = 1; 
      }
    else
    {
          seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
     }

After changed the code:

   if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly
        {
                    seqno  = 1; 
         }
            else
            {
                  seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
             }

Conclusion: when the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.

Selenium using Python - Geckodriver executable needs to be in PATH

Some additional input/clarification for future readers of this thread:

The following suffices as a resolution for Windows 7, Python 3.6, and Selenium 3.11:

dsalaj's note for another answer for Unix is applicable to Windows as well; tinkering with the PATH environment variable at the Windows level and restart of the Windows system can be avoided.

(1) Download geckodriver (as described in this thread earlier) and place the (unzipped) geckdriver.exe at X:\Folder\of\your\choice

(2) Python code sample:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Firefox();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

Notes: (1) It may take about 10 seconds for the above code to open up the Firefox browser for the specified URL. (2) The Python console would show the following error if there's no server already running at the specified URL or serving a page with the title containing the string 'Django': selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF-8&f=regular&d=Firefox%20can%E2%80%9

Java List.add() UnsupportedOperationException

instead of using add() we can use addall()

{ seeAlso.addall(groupDn); }

add adds a single item, while addAll adds each item from the collection one by one. In the end, both methods return true if the collection has been modified. In case of ArrayList this is trivial, because the collection is always modified, but other collections, such as Set, may return false if items being added are already there.

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!

Example:

                     data
2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
                     data
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

Getting current date and time in JavaScript

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

Advantages of std::for_each over for loop

You can have the iterator be a call to a function that is performed on each iteration through the loop.

See here: http://www.cplusplus.com/reference/algorithm/for_each/

How to listen for 'props' changes

Not sure if you have resolved it (and if I understand correctly), but here's my idea:

If parent receives myProp, and you want it to pass to child and watch it in child, then parent has to have copy of myProp (not reference).

Try this:

new Vue({
  el: '#app',
  data: {
    text: 'Hello'
  },
  components: {
    'parent': {
      props: ['myProp'],
      computed: {
        myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
      }
    },
    'child': {
      props: ['myProp'],
      watch: {
        myProp(val, oldval) { now val will differ from oldval }
      }
    }
  }
}

and in html:

<child :my-prop="myInnerProp"></child>

actually you have to be very careful when working on complex collections in such situations (passing down few times)

Java/ JUnit - AssertTrue vs AssertFalse

assertTrue will fail if the checked value is false, and assertFalse will do the opposite: fail if the checked value is true.

Another thing, your last assertEquals will very likely fail, as it will compare the "Book was already checked out" string with the output of m1.checkOut(b1,p2). It needs a third parameter (the second value to check for equality).

How do I get the find command to print out the file size with the file name?

Using gnu find, I think this is what you want. It finds all real files and not directories (-type f), and for each one prints the filename (%p), a tab (\t), the size in kilobytes (%k), the suffix " KB", and then a newline (\n).

find . -type f -printf '%p\t%k KB\n'

If the printf command doesn't format things the way you want, you can use exec, followed by the command you want to execute on each file. Use {} for the filename, and terminate the command with a semicolon (;). On most shells, all three of those characters should be escaped with a backslash.

Here's a simple solution that finds and prints them out using "ls -lh", which will show you the size in human-readable form (k for kilobytes, M for megabytes):

find . -type f -exec ls -lh \{\} \;

As yet another alternative, "wc -c" will print the number of characters (bytes) in the file:

find . -type f -exec wc -c \{\} \;

An implementation of the fast Fourier transform (FFT) in C#

I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010.

I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching.

/**
 * Performs an in-place complex FFT.
 *
 * Released under the MIT License
 *
 * Copyright (c) 2010 Gerald T. Beauregard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
public class FFT2
{
    // Element for linked list in which we store the
    // input/output data. We use a linked list because
    // for sequential access it's faster than array index.
    class FFTElement
    {
        public double re = 0.0;     // Real component
        public double im = 0.0;     // Imaginary component
        public FFTElement next;     // Next element in linked list
        public uint revTgt;         // Target position post bit-reversal
    }

    private uint m_logN = 0;        // log2 of FFT size
    private uint m_N = 0;           // FFT size
    private FFTElement[] m_X;       // Vector of linked list elements

    /**
     *
     */
    public FFT2()
    {
    }

    /**
     * Initialize class to perform FFT of specified size.
     *
     * @param   logN    Log2 of FFT length. e.g. for 512 pt FFT, logN = 9.
     */
    public void init(
        uint logN )
    {
        m_logN = logN;
        m_N = (uint)(1 << (int)m_logN);

        // Allocate elements for linked list of complex numbers.
        m_X = new FFTElement[m_N];
        for (uint k = 0; k < m_N; k++)
            m_X[k] = new FFTElement();

        // Set up "next" pointers.
        for (uint k = 0; k < m_N-1; k++)
            m_X[k].next = m_X[k+1];

        // Specify target for bit reversal re-ordering.
        for (uint k = 0; k < m_N; k++ )
            m_X[k].revTgt = BitReverse(k,logN);
    }

    /**
     * Performs in-place complex FFT.
     *
     * @param   xRe     Real part of input/output
     * @param   xIm     Imaginary part of input/output
     * @param   inverse If true, do an inverse FFT
     */
    public void run(
        double[] xRe,
        double[] xIm,
        bool inverse = false )
    {
        uint numFlies = m_N >> 1;   // Number of butterflies per sub-FFT
        uint span = m_N >> 1;       // Width of the butterfly
        uint spacing = m_N;         // Distance between start of sub-FFTs
        uint wIndexStep = 1;        // Increment for twiddle table index

        // Copy data into linked complex number objects
        // If it's an IFFT, we divide by N while we're at it
        FFTElement x = m_X[0];
        uint k = 0;
        double scale = inverse ? 1.0/m_N : 1.0;
        while (x != null)
        {
            x.re = scale*xRe[k];
            x.im = scale*xIm[k];
            x = x.next;
            k++;
        }

        // For each stage of the FFT
        for (uint stage = 0; stage < m_logN; stage++)
        {
            // Compute a multiplier factor for the "twiddle factors".
            // The twiddle factors are complex unit vectors spaced at
            // regular angular intervals. The angle by which the twiddle
            // factor advances depends on the FFT stage. In many FFT
            // implementations the twiddle factors are cached, but because
            // array lookup is relatively slow in C#, it's just
            // as fast to compute them on the fly.
            double wAngleInc = wIndexStep * 2.0*Math.PI/m_N;
            if (inverse == false)
                wAngleInc *= -1;
            double wMulRe = Math.Cos(wAngleInc);
            double wMulIm = Math.Sin(wAngleInc);

            for (uint start = 0; start < m_N; start += spacing)
            {
                FFTElement xTop = m_X[start];
                FFTElement xBot = m_X[start+span];

                double wRe = 1.0;
                double wIm = 0.0;

                // For each butterfly in this stage
                for (uint flyCount = 0; flyCount < numFlies; ++flyCount)
                {
                    // Get the top & bottom values
                    double xTopRe = xTop.re;
                    double xTopIm = xTop.im;
                    double xBotRe = xBot.re;
                    double xBotIm = xBot.im;

                    // Top branch of butterfly has addition
                    xTop.re = xTopRe + xBotRe;
                    xTop.im = xTopIm + xBotIm;

                    // Bottom branch of butterly has subtraction,
                    // followed by multiplication by twiddle factor
                    xBotRe = xTopRe - xBotRe;
                    xBotIm = xTopIm - xBotIm;
                    xBot.re = xBotRe*wRe - xBotIm*wIm;
                    xBot.im = xBotRe*wIm + xBotIm*wRe;

                    // Advance butterfly to next top & bottom positions
                    xTop = xTop.next;
                    xBot = xBot.next;

                    // Update the twiddle factor, via complex multiply
                    // by unit vector with the appropriate angle
                    // (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm)
                    double tRe = wRe;
                    wRe = wRe*wMulRe - wIm*wMulIm;
                    wIm = tRe*wMulIm + wIm*wMulRe;
                }
            }

            numFlies >>= 1;     // Divide by 2 by right shift
            span >>= 1;
            spacing >>= 1;
            wIndexStep <<= 1;   // Multiply by 2 by left shift
        }

        // The algorithm leaves the result in a scrambled order.
        // Unscramble while copying values from the complex
        // linked list elements back to the input/output vectors.
        x = m_X[0];
        while (x != null)
        {
            uint target = x.revTgt;
            xRe[target] = x.re;
            xIm[target] = x.im;
            x = x.next;
        }
    }

    /**
     * Do bit reversal of specified number of places of an int
     * For example, 1101 bit-reversed is 1011
     *
     * @param   x       Number to be bit-reverse.
     * @param   numBits Number of bits in the number.
     */
    private uint BitReverse(
        uint x,
        uint numBits)
    {
        uint y = 0;
        for (uint i = 0; i < numBits; i++)
        {
            y <<= 1;
            y |= x & 0x0001;
            x >>= 1;
        }
        return y;
    }

}

Connection Java-MySql : Public Key Retrieval is not allowed

If you are getting the following error while connecting the mysql (either local or mysql container running the mysql):

java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed

Solution: Add the following line in your database service:

command: --default-authentication-plugin=mysql_native_password

Trigger event when user scroll to specific element - with jQuery

Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.

Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.

function elementInView(el) {
  // The vertical distance between the top of the page and the top of the element.
  var elementOffset = $(el).offset().top;
  // The height of the element, including padding and borders.
  var elementOuterHeight = $(el).outerHeight();
  // Height of the window without margins, padding, borders.
  var windowHeight = $(window).height();
  // The vertical distance between the top of the page and the top of the viewport.
  var scrollOffset = $(this).scrollTop();

  if (elementOuterHeight < windowHeight) {
    // Element is smaller than viewport.
    if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
      // Element is completely inside viewport, reveal the element!
      return true;
    }
  } else {
    // Element is larger than the viewport, handle visibility differently.
    // Consider it visible as soon as it's top half has filled the viewport.
    if (scrollOffset > elementOffset) {
      // The top of the viewport has touched the top of the element, reveal the element!
      return true;
    }
  }
  return false;
}

Datatype for storing ip address in SQL Server

I like the functions of SandRock. But I found an error in the code of dbo.fn_ConvertIpAddressToBinary. The incoming parameter of @ipAddress VARCHAR(39) is too small when you concat the @delim to it.

SET @ipAddress = @ipAddress + @delim

You can increase it to 40. Or better yet use a new variable that is bigger and use that internally. That way you don't lose the last pair on large numbers.

SELECT dbo.fn_ConvertIpAddressToBinary('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff')

What's the Kotlin equivalent of Java's String[]?

use arrayOf, arrayOfNulls, emptyArray

var colors_1: Array<String> = arrayOf("green", "red", "blue")
var colors_2: Array<String?> = arrayOfNulls(3)
var colors_3: Array<String> = emptyArray()

Initializing IEnumerable<string> In C#

IEnumerable is an interface, instead of looking for how to create an interface instance, create an implementation that matches the interface: create a list or an array.

IEnumerable<string> myStrings = new [] { "first item", "second item" };
IEnumerable<string> myStrings = new List<string> { "first item", "second item" };

Skip the headers when editing a csv file using Python

Your reader variable is an iterable, by looping over it you retrieve the rows.

To make it skip one item before your loop, simply call next(reader, None) and ignore the return value.

You can also simplify your code a little; use the opened files as context managers to have them closed automatically:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row
       writer.writerow(row)

# no need to close, the files are closed automatically when you get to this point.

If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next() to writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

Eclipse : Failed to connect to remote VM. Connection refused.

I faced the same issue. But i resolved it by changing my port numbers to different one.

Unable to create Android Virtual Device

I want to update this question with a screenshot of a recent Android Studio. It took a bit of poking around to find where to install new system images.

You get to the SDK Manager through one of two paths. Option 1. Tools > Android > SDK Manager Option 2. Android Studio > Preferences > Appearance & Behavior > System Settings > Android SDK (This is for Mac; adapt for others.)

In the pane "SDK Platforms," check the "Show Packages" box to see the system images.

Select the ones you want, click "Apply" and voilà!

enter image description here

Height of status bar in Android

The default height used to be 25dp. With Android Marshmallow (API 23) the height was reduced to 24dp.

Update: Please be aware that since the age of notches and punch-whole-cameras began, using a static height for the status bar no longer works. Please use window insets instead!

sorting integers in order lowest to highest java

There are two options, really:

  1. Use standard collections, as explained by Shakedown
  2. Use Arrays.sort

E.g.,

int[] ints = {11367, 11358, 11421, 11530, 11491, 11218, 11789};
Arrays.sort(ints);
System.out.println(Arrays.asList(ints));

That of course assumes that you already have your integers as an array. If you need to parse those first, look for String.split and Integer.parseInt.

Get escaped URL parameter

What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:

$.url().param('foo');

If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:

$.url().param();

This library also works with other urls, not just the current one:

$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes

Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

It has other features as well, check out its homepage for more docs and examples.

Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.

Use an actual URI parser, don't invent your own.

For those averse to jQuery, there's a version of the plugin that's pure JS.

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

Try This:)

before:-

<servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>TestServlet</servlet-class>  
</servlet>

After:-

 <servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>operation.TestServlet</servlet-class>
 </servlet>

How to make UIButton's text alignment center? Using IB

Solution1

You can set the key path in the storyboard

Set the text to your multiline title e.g. hello ? + ? multiline

You need to press ? + ? to move text to next line.

enter image description here

Then add the key path

titleLabel.textAlignment as Number and value 1, 1 means NSTextAlignmentCenter
titleLabel.numberOfLines as Number and value 0, 0 means any number of lines

enter image description here

This will not be reflected on IB/Xcode, but will be in centre at run time (device/simulator)

If you want to see the changes on Xcode you need to do the following: (remember you can skip these steps)

  1. Subclass the UIButton to make the button designable:

    import UIKit
    @IBDesignable class UIDesignableButton: UIButton {}
    

  2. Assign this designable subclass to the buttons you're modifying:

Showing how to change the class of the button using Interface Builder

  1. Iff done right, you will see the visual update in IB when the Designables state is "Up to date" (which can take several seconds):

Comparing the designable and default button in Interface Builder



Solution2

If you want to write the code, then do the long process

1.Create IBOutlet for button
2.Write code in viewDidLoad

btn.titleLabel.textAlignment = .Center
btn.titleLabel.numberOfLines = 0


Solution3

In newer version of xcode (mine is xcode 6.1) we have property attributed title
Select Attributed then select the text and press centre option below

P.S. The text was not coming multiline for that I have to set the

btn.titleLabel.numberOfLines = 0

enter image description here

How to support different screen size in android

you can create bitmaps for the highes resolution / size your application will run and resize them in the code (at run time)

check this article http://nuvornapps-en.blogspot.com.es/

WPF: Grid with column/row margin/padding?

in uwp (Windows10FallCreatorsUpdate version and above)

<Grid RowSpacing="3" ColumnSpacing="3">

PHP to write Tab Characters inside a file?

Use \t and enclose the string with double-quotes:

$chunk = "abc\tdef\tghi";

Rownum in postgresql

If you just want a number to come back try this.

create temp sequence temp_seq;
SELECT inline_v1.ROWNUM,inline_v1.c1
FROM
(
select nextval('temp_seq') as ROWNUM, c1 
from sometable
)inline_v1;

You can add a order by to the inline_v1 SQL so your ROWNUM has some sequential meaning to your data.

select nextval('temp_seq') as ROWNUM, c1 
from sometable
ORDER BY c1 desc;

Might not be the fastest, but it's an option if you really do need them.

Install a Nuget package in Visual Studio Code

nuget package manager gui extension is a GUI tool that lets you easily update/remove/install packages from Nuget server for .NET Core/.Net 5 projects

> To install new package:

  1. Open your project workspace in VSCode
  2. Open the Command Palette (Ctrl+Shift+P)
  3. Select > Nuget Package Manager GUI
  4. Click Install New Package

Nuget Package Manager GUI

For update/remove the packages click Update/Remove Packages

Nuget Package Manager GUI

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

How to fix 'Notice: Undefined index:' in PHP form action

Assuming you only copy/pasted the relevant code and your form includes <form method="POST">


if(isset($_POST['filename'])){
    $filename = $_POST['filename'];
}
if(isset($filename)){ 
    echo $filename;
}

If _POST is not set the filename variable won't be either in the above example.

An alternative way:

$filename = false;
if(isset($_POST['filename'])){
    $filename = $_POST['filename'];
 } 
    echo $filename; //guarenteed to be set so isset not needed

In this example filename is set regardless of the situation with _POST. This should demonstrate the use of isset nicely.

More information here: http://php.net/manual/en/function.isset.php

Should you always favor xrange() over range()?

xrange() is more efficient because instead of generating a list of objects, it just generates one object at a time. Instead of 100 integers, and all of their overhead, and the list to put them in, you just have one integer at a time. Faster generation, better memory use, more efficient code.

Unless I specifically need a list for something, I always favor xrange()

Explain ggplot2 warning: "Removed k rows containing missing values"

The behavior you're seeing is due to how ggplot2 deals with data that are outside the axis ranges of the plot. You can change this behavior depending on whether you use scale_y_continuous (or, equivalently, ylim) or coord_cartesian to set axis ranges, as explained below.

library(ggplot2)

# All points are visible in the plot
ggplot(mtcars, aes(mpg, hp)) + 
  geom_point()

In the code below, one point with hp = 335 is outside the y-range of the plot. Also, because we used scale_y_continuous to set the y-axis range, this point is not included in any other statistics or summary measures calculated by ggplot, such as the linear regression line.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  scale_y_continuous(limits=c(0,300)) +  # Change this to limits=c(0,335) and the warning disappars
  geom_smooth(method="lm")

Warning messages:
1: Removed 1 rows containing missing values (stat_smooth). 
2: Removed 1 rows containing missing values (geom_point).

In the code below, the point with hp = 335 is still outside the y-range of the plot, but this point is nevertheless included in any statistics or summary measures that ggplot calculates, such as the linear regression line. This is because we used coord_cartesian to set the y-axis range, and this function does not exclude points that are outside the plot ranges when it does other calculations on the data.

If you compare this and the previous plot, you can see that the linear regression line in the second plot has a slightly steeper slope, because the point with hp=335 is included when calculating the regression line, even though it's not visible in the plot.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  coord_cartesian(ylim=c(0,300)) +
  geom_smooth(method="lm")

How to insert newline in string literal?

Well, simple options are:

  • string.Format:

    string x = string.Format("first line{0}second line", Environment.NewLine);
    
  • String concatenation:

    string x = "first line" + Environment.NewLine + "second line";
    
  • String interpolation (in C#6 and above):

    string x = $"first line{Environment.NewLine}second line";
    

You could also use \n everywhere, and replace:

string x = "first line\nsecond line\nthird line".Replace("\n",
                                                         Environment.NewLine);

Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.

SDK Location not found Android Studio + Gradle

If you have cloned a project from GitHub for example, and you've tried the methods mentioned here without success including:

  • Editing sdk.dir in the local.properties
  • Trying to set ANDROID_HOME environment variable
  • Or adding an alias as kasiara mentioned

You should try to see if you are trying to build a directory project that is a part within a bigger project, and so it may cause problems. So load the entire project, and then run the project directory you'd like.

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I had to register the .dll.

To do so, open cmd.exe (the console) with admin rights and type:

regsvr32 "foo.dll"

ORA-01031: insufficient privileges when selecting view

Let me make a recap.

When you build a view containing object of different owners, those other owners have to grant "with grant option" to the owner of the view. So, the view owner can grant to other users or schemas....

Example: User_a is the owner of a table called mine_a User_b is the owner of a table called yours_b

Let's say user_b wants to create a view with a join of mine_a and yours_b

For the view to work fine, user_a has to give "grant select on mine_a to user_b with grant option"

Then user_b can grant select on that view to everybody.

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

setInterval in a React app

Thanks @dotnetom, @greg-herbowicz

If it returns "this.state is undefined" - bind timer function:

constructor(props){
    super(props);
    this.state = {currentCount: 10}
    this.timer = this.timer.bind(this)
}

How to create a custom attribute in C#

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

The decorated property [of class Foo]:

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

Fetching it:

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

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

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

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

Major thanks to you, Darin!!

What does MVW stand for?

I feel that MWV (Model View Whatever) or MV* is a more flexible term to describe some of the uniqueness of Angularjs in my opinion. It helped me to understand that it is more than a MVC (Model View Controller) JavaScript framework, but it still uses MVC as it has a Model View, and Controller.

It also can be considered as a MVP (Model View Presenter) pattern. I think of a Presenter as the user-interface business logic in Angularjs for the View. For example by using filters that can format data for display. It's not business logic, but display logic and it reminds me of the MVP pattern I used in GWT.

In addition, it also can be a MVVM (Model View View Model) the View Model part being the two-way binding between the two. Last of all it is MVW as it has other patterns that you can use as well as mentioned by @Steve Chambers.

I agree with the other answers that getting pedantic on these terms can be detrimental, as the point is to understand the concepts from the terms, but by the same token, fully understanding the terms helps one when they are designing their application code, knowing what goes where and why.

Add a new line to the end of a JtextArea

Are you using JTextArea's append(String) method to add additional text?

JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");

How can I selectively merge or pick changes from another branch in Git?

This is my workflow for merging selective files.

# Make a new branch (this will be temporary)
git checkout -b newbranch

# Grab the changes
git merge --no-commit  featurebranch

# Unstage those changes
git reset HEAD
(You can now see the files from the merge are unstaged)

# Now you can chose which files are to be merged.
git add -p

# Remember to "git add" any new files you wish to keep
git commit

Getting unique values in Excel by using formulas only

Even to get a sorted unique value, it can be done using formula. This is an option you can use:

=INDEX($A$2:$A$18,MATCH(SUM(COUNTIF($A$2:$A$18,C$1:C1)),COUNTIF($A$2:$A$18,"<" &$A$2:$A$18),0))

range data: A2:A18

formula in cell C2

This is an ARRAY FORMULA

Emulate/Simulate iOS in Linux

As far as I know, there is no such a thing as iOS emulator on windows or linux, there are only some gameengines that enable you to compile same code for both iOS and windows or linux and there is a toolchain to compile iOS application using linux. none of them are realy emulator/simulator things. and to use that toolchain you need a jailbreaked iOS device to test binary file created using toolchain. I mean linux itself can't run the binary created itself. and by the way even in mac simulator is just an intermediate program which runs mac-compiled binary, since if you change compiling for iOS from simulator or the other way, all the files are rebuild. and also there are some real differences, like iOS is a case-sensitive operation while simulator is not.

so the best solution is to buy an iOS device yourself.

iterating through Enumeration of hastable keys throws NoSuchElementException error

You are calling nextElement twice. Refactor like this:

while(e.hasMoreElements()){


String param = (String) e.nextElement();
System.out.println(param);
}

What is the meaning of CTOR?

Usually this region should contains the constructors of the class

Android Studio Rendering Problems : The following classes could not be found

To use the class ActionBarOverlayLayout you need to include this in the dependencies section of build.gradle file:

compile 'com.android.support:design:24.1.1'

Sync the project once again and then you will find no problem

Getting title and meta tags from external website

If you're working with PHP, check out the Pear packages at pear.php.net and see if you find anything useful to you. I've used the RSS packages effectively and it saves a lot of time, provided you can follow how they implement their code via their examples.

Specifically take a look at Sax 3 and see if it will work for your needs. Sax 3 is no longer updated but it might be sufficient.

Escape sequence \f - form feed - what exactly is it?

From wiki page

12 (form feed, \f, ^L), to cause a printer to eject paper to the top of the next page, or a video terminal to clear the screen.

or more details here.

It seems that this symbol is rather obsolete now and the way it is processed may be(?) implementation dependent. At least for me your code gives the following output (xcode gcc 4.2, gdb console):

hello
    goodbye

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

Creating static library worked for me, compiling using g++ -static. It bundles the dependent libraries along with the build.

How to create json by JavaScript for loop?

If you want a single JavaScript object such as the following:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(where option 2, "Absent", is the current selection) then the following code should produce it:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

If you want an array of all such objects (not just the selected one), use michael's code but swap out status.options[i].text for status.id.

If you want a string that contains a JSON representation of the selected object, use this instead:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }

Why are only final variables accessible in anonymous class?

The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Solution»

Pass a keyword argument name with value as your view name e.g home or home-view etc. to url() function.

Throws Error»

url(r'^home$', 'common.views.view1', 'home'),

Correct»

url(r'^home$', 'common.views.view1', name='home'),

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

Just use strftime :)

Something like that:

my_date = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366, tzinfo=<UTC>)
print(my_date.strftime("%Y, %d %B"))

After edited your question to format timedelta, you could use:

def timedelta_tuple(timedelta_object):
   return timedelta_object.days, timedelta_object.seconds//3600, (timedelta_object.seconds//60)%60

How to get Selected Text from select2 when using <input>

Again I suggest Simple and Easy

Its Working Perfect with ajax when user search and select it saves the selected information via ajax

 $("#vendor-brands").select2({
   ajax: {
   url:site_url('general/get_brand_ajax_json'),
  dataType: 'json',
  delay: 250,
  data: function (params) {
  return {
    q: params.term, // search term
    page: params.page
  };
},
processResults: function (data, params) {
  // parse the results into the format expected by Select2
  // since we are using custom formatting functions we do not need to
  // alter the remote JSON data, except to indicate that infinite
  // scrolling can be used
  params.page = params.page || 1;

  return {
    results: data,
    pagination: {
      more: (params.page * 30) < data.total_count
    }
  };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom    formatter work
minimumInputLength: 1,
}).on("change", function(e) {


  var lastValue = $("#vendor-brands option:last-child").val();
  var lastText = $("#vendor-brands option:last-child").text();

  alert(lastValue+' '+lastText);
 });

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

MVC 4 Razor adding input type date

If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.

@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

<script>

    $(document).ready(function(){

      $('.datepicker').datepicker();

     });

</script>

}

Gradle to execute Java class (without modifying build.gradle)

You can parameterise it and pass gradle clean build -Pprokey=goodbye

task choiceMyMainClass(type: JavaExec) {
     group = "Execution"
    description = "Run Option main class with JavaExecTask"
    classpath = sourceSets.main.runtimeClasspath

    if (project.hasProperty('prokey')){
        if (prokey == 'hello'){
            main = 'com.sam.home.HelloWorld'
        } 
        else if (prokey == 'goodbye'){
            main = 'com.sam.home.GoodBye'
        }
    } else {
            println 'Invalid value is enterrd';

       // println 'Invalid value is enterrd'+ project.prokey;
    }

Why do we use arrays instead of other data structures?

For O(1) random access, which can not be beaten.

How to ignore whitespace in a regular expression subject string?

You could put \s* inbetween every character in your search string so if you were looking for cat you would use c\s*a\s*t\s*s\s*s

It's long but you could build the string dynamically of course.

You can see it working here: http://www.rubular.com/r/zzWwvppSpE

Is there any way to delete local commits in Mercurial?

You can get around this even more easily with the Rebase extension, just use hg pull --rebase and your commits are automatically re-comitted to the pulled revision, avoiding the branching issue.

Correct way to load a Nib for a UIView subclass

MyViewClass *myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0]

I'm using this to initialise the reusable custom views I have.


Note that you can use "firstObject" at the end there, it's a little cleaner. "firstObject" is a handy method for NSArray and NSMutableArray.

Here's a typical example, of loading a xib to use as a table header. In your file YourClass.m

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[NSBundle mainBundle] loadNibNamed:@"TopArea" owner:self options:nil].firstObject;
}

Normally, in the TopArea.xib, you would click on File Owner and set the file owner to YourClass. Then actually in YourClass.h you would have IBOutlet properties. In TopArea.xib, you can drag controls to those outlets.

Don't forget that in TopArea.xib, you may have to click on the View itself and drag that to some outlet, so you have control of it, if necessary. (A very worthwhile tip is that when you are doing this for table cell rows, you absolutely have to do that - you have to connect the view itself to the relevant property in your code.)

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

@Garret Wilson Thank you so much! As a noob to android coding, I've been stuck with the preferences incompatibility issue for so many hours, and I find it so disappointing they deprecated the use of some methods/approaches for new ones that aren't supported by the older APIs thus having to resort to all sorts of workarounds to make your app work in a wide range of devices. It's really frustrating!

Your class is great, for it allows you to keep working in new APIs wih preferences the way it used to be, but it's not backward compatible. Since I'm trying to reach a wide range of devices I tinkered with it a bit to make it work in pre API 11 devices as well as in newer APIs:

import android.annotation.TargetApi;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;

public class MyPrefsActivity extends PreferenceActivity
{
    private static int prefs=R.xml.myprefs;

    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        try {
            getClass().getMethod("getFragmentManager");
            AddResourceApi11AndGreater();
        } catch (NoSuchMethodException e) { //Api < 11
            AddResourceApiLessThan11();
        }
    }

    @SuppressWarnings("deprecation")
    protected void AddResourceApiLessThan11()
    {
        addPreferencesFromResource(prefs);
    }

    @TargetApi(11)
    protected void AddResourceApi11AndGreater()
    {
        getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PF()).commit();
    }

    @TargetApi(11)
    public static class PF extends PreferenceFragment
    {       
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(MyPrefsActivity.prefs); //outer class
            // private members seem to be visible for inner class, and
            // making it static made things so much easier
        }
    }
}

Tested in two emulators (2.2 and 4.2) with success.

Why my code looks so crappy:

I'm a noob to android coding, and I'm not the greatest java fan.

In order to avoid the deprecated warning and to force Eclipse to allow me to compile I had to resort to annotations, but these seem to affect only classes or methods, so I had to move the code onto two new methods to take advantage of this.

I wouldn't like having to write my xml resource id twice anytime I copy&paste the class for a new PreferenceActivity, so I created a new variable to store this value.

I hope this will be useful to somebody else.

P.S.: Sorry for my opinionated views, but when you come new and find such handicaps, you can't help it but to get frustrated!

How to remove from a map while iterating it?

I personally prefer this pattern which is slightly clearer and simpler, at the expense of an extra variable:

for (auto it = m.cbegin(), next_it = it; it != m.cend(); it = next_it)
{
  ++next_it;
  if (must_delete)
  {
    m.erase(it);
  }
}

Advantages of this approach:

  • the for loop incrementor makes sense as an incrementor;
  • the erase operation is a simple erase, rather than being mixed in with increment logic;
  • after the first line of the loop body, the meaning of it and next_it remain fixed throughout the iteration, allowing you to easily add additional statements referring to them without headscratching over whether they will work as intended (except of course that you cannot use it after erasing it).

How to loop through a collection that supports IEnumerable?

foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
{

}

PHP session handling errors

I had the same error everything was correct like the setting the folder permissions.

It looks like an bug in php in my case because when i delete my PHPSESSID cookie it was working again so aperently something was messed up and the session got removed but the cookie was still active so php had to define the cause differently and checking first if the session file is still they and give another error and not the permission error

Android, How can I Convert String to Date?

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)

Java error: Only a type can be imported. XYZ resolves to a package

I had the same error message and my way to deal with it is as follows:

  1. First go check the file directory where your Tomcat is publishing your web application, e.g. D:\Java\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\myDatatable\WEB-INF\classes, in which we normally put our classes. If this is not the place where you put your classes, then you have to find out where by default it is by right click your web application root name-->Build Path-->Configure Build Bath...-->Then check the "Source" Tab and find out the field value of "Default output folder". This shall be the place where Tomcat put your classes.
  2. You would see that XYZ class is not yet built. In order to build it, you could go to Menu "Project"-->"Clean..."-->Select your web application to clean.
  3. After it's completed, try restart your tomcat server and go check the file directory again. Your class should be there. At least it works for me. Hope it helps.

Xcode Error: "The app ID cannot be registered to your development team."

None of the above answers worked for me, and as said in the original question I had also to keep the same bundle identifier since the app was already published in the store by the client.

The solution for me was to ask the client to change my access from App Manager to Admin, so that I had "Access to Certificates, Identifiers & Profiles.", you can check if it is the case in the App Store Connect => Users and Access => and then click on your profile (be sure to choose the right team if you belong to multiple).

Once you are admin go back to Xcode and in the signing tab select 'Automatically manage signing', then in Team dropdown you should be able to select the right team and the signature will work.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.

Make absolute positioned div expand parent div height

With pure JavaScript, you just need to retrieve the height of your static position child element .child1 using the getComputedStyle() method then set that retrieve value as the padding-top for that same child using the HTMLElement.style property.


Check and run the following Code Snippet for a practical example of what I described above:

_x000D_
_x000D_
/* JavaScript */_x000D_
_x000D_
var child1 = document.querySelector(".child1");_x000D_
var parent = document.getElementById("parent");_x000D_
_x000D_
var childHeight = parseInt(window.getComputedStyle(child1).height) + "px";_x000D_
child1.style.paddingTop = childHeight;
_x000D_
/* CSS */_x000D_
_x000D_
#parent { position: relative; width: 100%; }_x000D_
.child1 { width: auto; }_x000D_
.child2 { width: 145px; position: absolute; top: 0px; bottom: 0px; }_x000D_
html, body { width: 100%;height: 100%; margin: 0; padding: 0; }
_x000D_
<!-- HTML -->_x000D_
_x000D_
<div id="parent">_x000D_
    <div class="child1">STATIC</div>_x000D_
    <div class="child2">ABSOLUTE</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I enable/disable log levels in Android?

Log4j or slf4j can also be used as logging frameworks in Android together with logcat. See the project android-logging-log4j or log4j support in android

A method to reverse effect of java String.split()?

Below code gives a basic idea. This is not best solution though.

public static String splitJoin(String sourceStr, String delim,boolean trim,boolean ignoreEmpty){
    return join(Arrays.asList(sourceStr.split(delim)), delim, ignoreEmpty);
}


public static String join(List<?> list, String delim, boolean ignoreEmpty) {
    int len = list.size();
    if (len == 0)
        return "";
    StringBuilder sb = new StringBuilder(list.get(0).toString());
    for (int i = 1; i < len; i++) {
        if (ignoreEmpty && !StringUtils.isBlank(list.get(i).toString())) {
            sb.append(delim);
            sb.append(list.get(i).toString().trim());
        }
    }
    return sb.toString();
}

Why is `input` in Python 3 throwing NameError: name... is not defined

I'd say the code you need is:

test = input("enter the test")
print(test)

Otherwise it shouldn't run at all, due to a syntax error. The print function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?

How to add click event to a iframe with JQuery

This may be interesting for ppl using Primefaces (which uses CLEditor):

document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}

I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)

Flask raises TemplateNotFound error even though template file exists

Another alternative is to set the root_path which fixes the problem both for templates and static folders.

root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)

If you render templates directly via Jinja2, then you write:

ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)

Using if-else in JSP

Instead of if-else condition use if in both conditions. it will work that way but not sure why.

Powershell equivalent of bash ampersand (&) for forking/running background processes

ps2> start-job {start-sleep 20}

i have not yet figured out how to get stdout in realtime, start-job requires you to poll stdout with get-job

update: i couldn't start-job to easily do what i want which is basically the bash & operator. here's my best hack so far

PS> notepad $profile #edit init script -- added these lines
function beep { write-host `a }
function ajp { start powershell {ant java-platform|out-null;beep} } #new window, stderr only, beep when done
function acjp { start powershell {ant clean java-platform|out-null;beep} }
PS> . $profile #re-load profile script
PS> ajp

Inline elements shifting when made bold on hover

try this:

.nav {
  font-family: monospace;
}

Push origin master error on new repository

The error message leads to the conclusion that you do not have a master branch in your local repository. Either push your main development branch (git push origin my-local-master:master which will rename it to master on github) or make a commit first. You can not push a completely empty repository.

Why is MySQL InnoDB insert so slow?

InnoDB has transaction support, you're not using explicit transactions so innoDB has to do a commit after each statement ("performs a log flush to disk for every insert").

Execute this command before your loop:

START TRANSACTION

and this after you loop

COMMIT

Android: How to Programmatically set the size of a Layout

LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                       /*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
               /*height*/ 100,
               /*weight*/ 1.0f
                );
                YOUR_LinearLayout.setLayoutParams(param);

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

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

Javascript ::

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

Check this example that add li element to ul.

How to set a header for a HTTP GET request, and trigger file download?

Try

html

<!-- placeholder , 
    `click` download , `.remove()` options ,
     at js callback , following js 
-->
<a>download</a>

js

        $(document).ready(function () {
            $.ajax({
                // `url` 
                url: '/echo/json/',
                type: "POST",
                dataType: 'json',
                // `file`, data-uri, base64
                data: {
                    json: JSON.stringify({
                        "file": "data:text/plain;base64,YWJj"
                    })
                },
                // `custom header`
                headers: {
                    "x-custom-header": 123
                },
                beforeSend: function (jqxhr) {
                    console.log(this.headers);
                    alert("custom headers" + JSON.stringify(this.headers));
                },
                success: function (data) {
                    // `file download`
                    $("a")
                        .attr({
                        "href": data.file,
                            "download": "file.txt"
                    })
                        .html($("a").attr("download"))
                        .get(0).click();
                    console.log(JSON.parse(JSON.stringify(data)));
                },
                error: function (jqxhr, textStatus, errorThrown) {
                  console.log(textStatus, errorThrown)
                }
            });
        });

jsfiddle http://jsfiddle.net/guest271314/SJYy3/

Javascript-Setting background image of a DIV via a function and function parameter

If you are looking for a direct approach and using a local File in that case. Try

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>

This is the case of JS with inline styling where Image is a local file that you must have imported with a path.

Show / hide div on click with CSS

A little hack-ish but it works. Note that the label tag can be placed any where. The key parts are:

  • The css input:checked+div selects the div immediately next to/after the input
  • The label for said checkbox (or hey leave out the label and just have the checkbox)
  • display:none hides stuff

Code:

<head>
    <style>
        #sidebar {height:100%; background:blue; width:200px; clear:none; float:left;}
        #content {height:100%; background:green; width:400px; clear:none; float:left;}
        label {background:yellow;float:left;}
        input{display:none;}
        input:checked+#sidebar{display:none;}
    </style>
</head>
<body>
<div>
<label for="hider">Hide</label>
<input type="checkbox" id="hider">
<div id="sidebar">foo</div>

<div id="content">hello</div>

</div>
</body>

EDIT: Sorry could have read the question better.

One could also use css3 elements to create the slide/fade effect. I am not familiar enough with them to be much help with that aspect but they do exist. Browser support is iffy though.

You could combine the above effect with javascript to use fancy transitions and still have a fall back. jquery has a css method to override the above and slide and fade for transitions.

  • Tilda(~) mean some sibling after; not next sibling like plus(+).
  • [key="value"] is an attribute selector.
  • Radio buttons must have same name

To string tabs together one could use:

<html>
<head>
<style>
input[value="1"]:checked ~ div[id="1"]{
display:none;
}
input[value="2"]:checked ~ div[id="2"]{
display:none;
}
</style>
</head>
<body>
<input type="radio" name="hider" value="1">
<input type="radio" name="hider" value="2">
<div id="1">div 1</div>
<div id="2">div 2</div>
</body>
</html>

How to update UI from another thread running in another class

Thank God, Microsoft got that figured out in WPF :)

Every Control, like a progress bar, button, form, etc. has a Dispatcher on it. You can give the Dispatcher an Action that needs to be performed, and it will automatically call it on the correct thread (an Action is like a function delegate).

You can find an example here.

Of course, you'll have to have the control accessible from other classes, e.g. by making it public and handing a reference to the Window to your other class, or maybe by passing a reference only to the progress bar.

How to make div same height as parent (displayed as table-cell)

The child can only take a height if the parent has one already set. See this exaple : Vertical Scrolling 100% height

 html, body {
        height: 100%;
        margin: 0;
    }
    .header{
        height: 10%;
        background-color: #a8d6fe;
    }
    .middle {
        background-color: #eba5a3;
        min-height: 80%;
    }
    .footer {
        height: 10%;
        background-color: #faf2cc;
    }

_x000D_
_x000D_
    $(function() {_x000D_
      $('a[href*="#nav-"]').click(function() {_x000D_
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {_x000D_
          var target = $(this.hash);_x000D_
          target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');_x000D_
          if (target.length) {_x000D_
            $('html, body').animate({_x000D_
              scrollTop: target.offset().top_x000D_
            }, 500);_x000D_
            return false;_x000D_
          }_x000D_
        }_x000D_
      });_x000D_
    });
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.header {_x000D_
  height: 100%;_x000D_
  background-color: #a8d6fe;_x000D_
}_x000D_
.middle {_x000D_
  background-color: #eba5a3;_x000D_
  min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
  height: 100%;_x000D_
  background-color: #faf2cc;_x000D_
}_x000D_
nav {_x000D_
  position: fixed;_x000D_
  top: 10px;_x000D_
  left: 0px;_x000D_
}_x000D_
nav li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <nav>_x000D_
    <ul>_x000D_
      <li>_x000D_
        <a href="#nav-a">got to a</a>_x000D_
      </li>_x000D_
      <li>_x000D_
        <a href="#nav-b">got to b</a>_x000D_
      </li>_x000D_
      <li>_x000D_
        <a href="#nav-c">got to c</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </nav>_x000D_
  <div class="header" id="nav-a">_x000D_
_x000D_
  </div>_x000D_
  <div class="middle" id="nav-b">_x000D_
_x000D_
  </div>_x000D_
  <div class="footer" id="nav-c">_x000D_
_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Select from multiple tables without a join?

In this case we are assuming that we have two tables: SMPPMsgLogand SMSService with common column serviceid:

SELECT sp.SMS,ss.CMD 
FROM vas.SMPPMsgLog AS sp,vas.SMSService AS ss 
WHERE sp.serviceid=5431 
AND ss.ServiceID = 5431 
AND Receiver ="232700000" 
AND date(TimeStamp) <='2013-08-07' 
AND date(TimeStamp) >='2013-08-06' \G;

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

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.

NumPy first and last element from array

How about:

In [10]: arr = numpy.array([1,23,4,6,7,8])

In [11]: [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)]
Out[11]: [(1, 8), (23, 7), (4, 6)]

Depending on the size of arr, writing the entire thing in NumPy may be more performant:

In [41]: arr = numpy.array([1,23,4,6,7,8]*100)

In [42]: %timeit [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)]
10000 loops, best of 3: 167 us per loop

In [43]: %timeit numpy.vstack((arr, arr[::-1]))[:,:len(arr)//2]
100000 loops, best of 3: 16.4 us per loop

I want to load another HTML page after a specific amount of time

use this JavaScript code:

<script>
    setTimeout(function(){
       window.location.href = 'form2.html';
    }, 5000);
</script>

Git Stash vs Shelve in IntelliJ IDEA

git shelve doesn't exist in Git.

Only git stash:

  • when you want to record the current state of the working directory and the index, but want to go back to a clean working directory.
  • which saves your local modifications away and reverts the working directory to match the HEAD commit.

You had a 2008 old project git shelve to isolate modifications in a branch, but that wouldn't be very useful nowadays.

As documented in Intellij IDEA shelve dialog, the feature "shelving and unshelving" is not linked to a VCS (Version Control System tool) but to the IDE itself, to temporarily storing pending changes you have not committed yet in changelist.

Note that since Git 2.13 (Q2 2017), you now can stash individual files too.

Get absolute path to workspace directory in Jenkins Pipeline plugin

Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

node('label'){
    // now you are on slave labeled with 'label'
    def workspace = WORKSPACE
    // ${workspace} will now contain an absolute path to job workspace on slave

    workspace = env.WORKSPACE
    // ${workspace} will still contain an absolute path to job workspace on slave

    // When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
    echo "Current workspace is ${env.WORKSPACE}"

    // the current Jenkins instances will support the short syntax, too:
    echo "Current workspace is $WORKSPACE"

}

Convert string into integer in bash script - "Leading Zero" number error

The leading 0 is leading to bash trying to interpret your number as an octal number, but octal numbers are 0-7, and 8 is thus an invalid token.

If I were you, I would add some logic to remove a leading 0, add one, and re-add the leading 0 if the result is < 10.

How to connect SQLite with Java?

Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :

http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html

How do I get git to default to ssh and not https for new repositories

SSH File

~/.ssh/config file
Host *
    StrictHostKeyChecking no
    UserKnownHostsFile=/dev/null
    LogLevel QUIET
    ConnectTimeout=10
Host github.com
        User git
        AddKeystoAgent yes
        UseKeychain yes
        Identityfile ~/github_rsa

Edit reponame/.git/config

[remote "origin"]
        url = [email protected]:username/repo.git

Check if a string is a valid Windows directory (folder) path

Path.GetFullPath gives below exceptions only

ArgumentException path is a zero-length string, contains only white space, or contains one or more of the invalid characters defined in GetInvalidPathChars. -or- The system could not retrieve the absolute path.

SecurityException The caller does not have the required permissions.

ArgumentNullException path is null.

NotSupportedException path contains a colon (":") that is not part of a volume identifier (for example, "c:\").

PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

Alternate way is to use the following :

/// <summary>
/// Validate the Path. If path is relative append the path to the project directory by default.
/// </summary>
/// <param name="path">Path to validate</param>
/// <param name="RelativePath">Relative path</param>
/// <param name="Extension">If want to check for File Path</param>
/// <returns></returns>
private static bool ValidateDllPath(ref string path, string RelativePath = "", string Extension = "")
{
    // Check if it contains any Invalid Characters.
    if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1)
    {
        try
        {
            // If path is relative take %IGXLROOT% as the base directory
            if (!Path.IsPathRooted(path))
            {
                if (string.IsNullOrEmpty(RelativePath))
                {
                    // Exceptions handled by Path.GetFullPath
                    // ArgumentException path is a zero-length string, contains only white space, or contains one or more of the invalid characters defined in GetInvalidPathChars. -or- The system could not retrieve the absolute path.
                    // 
                    // SecurityException The caller does not have the required permissions.
                    // 
                    // ArgumentNullException path is null.
                    // 
                    // NotSupportedException path contains a colon (":") that is not part of a volume identifier (for example, "c:\"). 
                    // PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

                    // RelativePath is not passed so we would take the project path 
                    path = Path.GetFullPath(RelativePath);

                }
                else
                {
                    // Make sure the path is relative to the RelativePath and not our project directory
                    path = Path.Combine(RelativePath, path);
                }
            }

            // Exceptions from FileInfo Constructor:
            //   System.ArgumentNullException:
            //     fileName is null.
            //
            //   System.Security.SecurityException:
            //     The caller does not have the required permission.
            //
            //   System.ArgumentException:
            //     The file name is empty, contains only white spaces, or contains invalid characters.
            //
            //   System.IO.PathTooLongException:
            //     The specified path, file name, or both exceed the system-defined maximum
            //     length. For example, on Windows-based platforms, paths must be less than
            //     248 characters, and file names must be less than 260 characters.
            //
            //   System.NotSupportedException:
            //     fileName contains a colon (:) in the middle of the string.
            FileInfo fileInfo = new FileInfo(path);

            // Exceptions using FileInfo.Length:
            //   System.IO.IOException:
            //     System.IO.FileSystemInfo.Refresh() cannot update the state of the file or
            //     directory.
            //
            //   System.IO.FileNotFoundException:
            //     The file does not exist.-or- The Length property is called for a directory.
            bool throwEx = fileInfo.Length == -1;

            // Exceptions using FileInfo.IsReadOnly:
            //   System.UnauthorizedAccessException:
            //     Access to fileName is denied.
            //     The file described by the current System.IO.FileInfo object is read-only.-or-
            //     This operation is not supported on the current platform.-or- The caller does
            //     not have the required permission.
            throwEx = fileInfo.IsReadOnly;

            if (!string.IsNullOrEmpty(Extension))
            {
                // Validate the Extension of the file.
                if (Path.GetExtension(path).Equals(Extension, StringComparison.InvariantCultureIgnoreCase))
                {
                    // Trim the Library Path
                    path = path.Trim();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;

            }
        }
        catch (ArgumentNullException)
        {
            //   System.ArgumentNullException:
            //     fileName is null.
        }
        catch (System.Security.SecurityException)
        {
            //   System.Security.SecurityException:
            //     The caller does not have the required permission.
        }
        catch (ArgumentException)
        {
            //   System.ArgumentException:
            //     The file name is empty, contains only white spaces, or contains invalid characters.
        }
        catch (UnauthorizedAccessException)
        {
            //   System.UnauthorizedAccessException:
            //     Access to fileName is denied.
        }
        catch (PathTooLongException)
        {
            //   System.IO.PathTooLongException:
            //     The specified path, file name, or both exceed the system-defined maximum
            //     length. For example, on Windows-based platforms, paths must be less than
            //     248 characters, and file names must be less than 260 characters.
        }
        catch (NotSupportedException)
        {
            //   System.NotSupportedException:
            //     fileName contains a colon (:) in the middle of the string.
        }
        catch (FileNotFoundException)
        {
            // System.FileNotFoundException
            //  The exception that is thrown when an attempt to access a file that does not
            //  exist on disk fails.
        }
        catch (IOException)
        {
            //   System.IO.IOException:
            //     An I/O error occurred while opening the file.
        }
        catch (Exception)
        {
            // Unknown Exception. Might be due to wrong case or nulll checks.
        }
    }
    else
    {
        // Path contains invalid characters
    }
    return false;
}

Curly braces in string in PHP

Example:

$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";

Without curly braces PHP would try to find a variable named $numberth, that doesn't exist!

Convert UTC/GMT time to local time

This code block uses universal time to convert current DateTime object then converts it back to local DateTime. Works perfect for me I hope it helps!

CreatedDate.ToUniversalTime().ToLocalTime();

How to get all of the immediate subdirectories in Python

def get_folders_in_directories_recursively(directory, index=0):
    folder_list = list()
    parent_directory = directory

    for path, subdirs, _ in os.walk(directory):
        if not index:
            for sdirs in subdirs:
                folder_path = "{}/{}".format(path, sdirs)
                folder_list.append(folder_path)
        elif path[len(parent_directory):].count('/') + 1 == index:
            for sdirs in subdirs:
                folder_path = "{}/{}".format(path, sdirs)
                folder_list.append(folder_path)

    return folder_list

The following function can be called as:

get_folders_in_directories_recursively(directory, index=1) -> gives the list of folders in first level

get_folders_in_directories_recursively(directory) -> gives all the sub folders

Is there a way to get colored text in GitHubflavored Markdown?

You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:

```diff
+ this text is highlighted in green
- this text is highlighted in red
```

Where is android_sdk_root? and how do I set it.?

I received the same error after installing android studio and trying to run hello world. I think you need to use the SDK Manager inside Android Studio to install some things first.

android_sdk_root error

Open up Android Studio, and click on the SDK Manager in the toolbar.

SDK Manager

Now install the SDK tools you need.

  • Tools -> Android SDK Tools
  • Tools -> Android SDK Platform-tools
  • Tools -> Android SDK Build-tools (highest version)

For each Android release you are targeting, hit the appropriate Android X.X folder and select (at a minimum):

  • SDK Platform
  • A system image for the emulator, such as ARM EABI v7a System Image

The SDK Manager will run (this can take a while) and download and install the various SDKs.

Inside Android Studio, File->Project Structure will show you where your Android sdks are installed. As you can see mine is c:\users\Joe\AppData\Local\Android\sdk1.

enter image description here

If I navigate to C:\Users\Joe\AppData\Local\Android\sdk1\sources you can see the various Android SDKs installed there...

SDK Directories

Changing .gitconfig location on Windows

  1. Change to folder %PROGRAMFILES%\Git\etc
  2. Edit file profile
  3. Add to first line HOME="c:\location_were_you_want_gitconfig"
  4. Done

Note: The file permissions are usually restricted, so change them accordingly or you won't be able to save your changes.

How can I round a number in JavaScript? .toFixed() returns a string?

Because its primary use is displaying numbers? If you want to round numbers, use Math.round() with apropriate factors.

SQL distinct for 2 fields in a database

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

Bootstrap 4 card-deck with number of columns based on viewport

This answer is for those who are using Bootstrap 4.1+ and for those who care about IE 11 as well

Card-deck does not adapt the number visible of cards according to the viewport size.

Above methods work but do not support IE. With the below method, you can achieve similar functionality and responsive cards.

You can manage the number of cards to show/hide in different breakpoints.

In Bootstrap 4.1+ columns are same height by default, just make sure your card/content uses all available space. Run the snippet, you'll understand

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
    <div class="row">_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-sm-6 col-lg-4 mb-3">_x000D_
            <div class="card mb-3 h-100">_x000D_
                <div class="card-body">_x000D_
                    <h5 class="card-title">Card title</h5>_x000D_
                    <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
                    <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

Show/hide image with JavaScript

Here is a working example: http://jsfiddle.net/rVBzt/ (using jQuery)

<img id="tiger" src="https://twimg0-a.akamaihd.net/profile_images/2642324404/46d743534606515238a9a12cfb4b264a.jpeg">

<a id="toggle">click to toggle</a>

img {display: none;}

a {cursor: pointer; color: blue;}

$('#toggle').click(function() {
    $('#tiger').toggle();
});

Neither BindingResult nor plain target object for bean name available as request attr

Make sure you declare the bean associated with the form in GET method of the associated controller and also add it in the model model.addAttribute("uploadItem", uploadItem); which contains @RequestMapping(method = RequestMethod.GET) annotation.

For example UploadItem.java is associated with myform.jsp and controller is SecureAreaController.java

myform.jsp contains

<form:form action="/securedArea" commandName="uploadItem" enctype="multipart/form-data"></form:form>

MyFormController.java

@RequestMapping("/securedArea")
@Controller
public class SecureAreaController {

@RequestMapping(method = RequestMethod.GET)
public String showForm(Model model) {
            UploadItem uploadItem = new UploadItem(); // declareing

            model.addAttribute("uploadItem", uploadItem); // adding in model
    return "securedArea/upload";
}

}

As you can see I am declaring UploadItem.java in controller GET method.

Clear ComboBox selected text

This is what you need:

comboBox1.ResetText();

How to strip comma in Python string

unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))

My Routes are Returning a 404, How can I Fix Them?

Have you tried adding this to your routes file instead Route::get('user', "user@index")?

The piece of text before the @, user in this case, will direct the page to the user controller and the piece of text after the @, index, will direct the script to the user function public function get_index().

I see you're using $restful, in which case you could set your Route to Route::any('user', 'user@index'). This will handle both POST and GET, instead of writing them both out separately.

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

how to get date of yesterday using php?

Another OOP method for DateTime with setting the exact hour:

$yesterday = new DateTime("yesterday 09:00:59", new DateTimeZone('Europe/London'));
echo $yesterday->format('Y-m-d H:i:s') . "\n";

Check if the file exists using VBA

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

Works very well, almost, at my site. If I call it with "" the empty string, Dir returns "connection.odc"!! Would be great if you guys could share your result.

Anyway, I do like this:

Function FileExists(fullFileName As String) As Boolean
  If fullFileName = "" Then
    FileExists = False
  Else
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
  End If
End Function

SQL Error: ORA-12899: value too large for column

example : 1 and 2 table is available

1 table delete entry and select nor 2 table records and insert to no 1 table . when delete time no 1 table dont have second table records example emp id not available means this errors appeared

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

android.os.NetworkOnMainThreadException with android 4.2

Use StrictMode Something like this:-

   if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 
        }

How do I get the width and height of a HTML5 canvas?

It might be worth looking at a tutorial: MDN Canvas Tutorial

You can get the width and height of a canvas element simply by accessing those properties of the element. For example:

var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;

If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:

const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;

Or using the shorter object destructuring syntax:

const { width, height } = canvas.getBoundingClientRect();

The context is an object you get from the canvas to allow you to draw into it. You can think of the context as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.

Generate 'n' unique random numbers within a range

You could add to a set until you reach n:

setOfNumbers = set()
while len(setOfNumbers) < n:
    setOfNumbers.add(random.randint(numLow, numHigh))

Be careful of having a smaller range than will fit in n. It will loop forever, unable to find new numbers to insert up to n

How can I check if a string is a number?

use this

 double num;
    string candidate = "1";
    if (double.TryParse(candidate, out num))
    {
        // It's a number!


 }

Insert ellipsis (...) into HTML tag if content too wide

I built this code using a number of other posts, with the following enhancements:

  1. It uses a binary search to find the text length that is just right.
  2. It handles cases where the ellipsis element(s) are initially hidden by setting up a one-shot show event that re-runs the ellipsis code when the item is first displayed. This is handy for master-detail views or tree-views where some items aren't initially displayed.
  3. It optionally adds a title attribute with the original text for a hoverover effect.
  4. Added display: block to the style, so spans work
  5. It uses the ellipsis character instead of 3 periods.
  6. It auto-runs the script for anything with the .ellipsis class

CSS:

.ellipsis {
        white-space: nowrap;
        overflow: hidden;
        display: block;
}

.ellipsis.multiline {
        white-space: normal;
}

jquery.ellipsis.js

(function ($) {

    // this is a binary search that operates via a function
    // func should return < 0 if it should search smaller values
    // func should return > 0 if it should search larger values
    // func should return = 0 if the exact value is found
    // Note: this function handles multiple matches and will return the last match
    // this returns -1 if no match is found
    function binarySearch(length, func) {
        var low = 0;
        var high = length - 1;
        var best = -1;
        var mid;

        while (low <= high) {
            mid = ~ ~((low + high) / 2); //~~ is a fast way to convert something to an int
            var result = func(mid);
            if (result < 0) {
                high = mid - 1;
            } else if (result > 0) {
                low = mid + 1;
            } else {
                best = mid;
                low = mid + 1;
            }
        }

        return best;
    }

    // setup handlers for events for show/hide
    $.each(["show", "toggleClass", "addClass", "removeClass"], function () {

        //get the old function, e.g. $.fn.show   or $.fn.hide
        var oldFn = $.fn[this];
        $.fn[this] = function () {

            // get the items that are currently hidden
            var hidden = this.find(":hidden").add(this.filter(":hidden"));

            // run the original function
            var result = oldFn.apply(this, arguments);

            // for all of the hidden elements that are now visible
            hidden.filter(":visible").each(function () {
                // trigger the show msg
                $(this).triggerHandler("show");
            });

            return result;
        };
    });

    // create the ellipsis function
    // when addTooltip = true, add a title attribute with the original text
    $.fn.ellipsis = function (addTooltip) {

        return this.each(function () {
            var el = $(this);

            if (el.is(":visible")) {

                if (el.css("overflow") === "hidden") {
                    var content = el.html();
                    var multiline = el.hasClass('multiline');
                    var tempElement = $(this.cloneNode(true))
                        .hide()
                        .css('position', 'absolute')
                        .css('overflow', 'visible')
                        .width(multiline ? el.width() : 'auto')
                        .height(multiline ? 'auto' : el.height())
                    ;

                    el.after(tempElement);

                    var tooTallFunc = function () {
                        return tempElement.height() > el.height();
                    };

                    var tooWideFunc = function () {
                        return tempElement.width() > el.width();
                    };

                    var tooLongFunc = multiline ? tooTallFunc : tooWideFunc;

                    // if the element is too long...
                    if (tooLongFunc()) {

                        var tooltipText = null;
                        // if a tooltip was requested...
                        if (addTooltip) {
                            // trim leading/trailing whitespace
                            // and consolidate internal whitespace to a single space
                            tooltipText = $.trim(el.text()).replace(/\s\s+/g, ' ');
                        }

                        var originalContent = content;

                        var createContentFunc = function (i) {
                            content = originalContent.substr(0, i);
                            tempElement.html(content + "…");
                        };

                        var searchFunc = function (i) {
                            createContentFunc(i);
                            if (tooLongFunc()) {
                                return -1;
                            }
                            return 0;
                        };

                        var len = binarySearch(content.length - 1, searchFunc);

                        createContentFunc(len);

                        el.html(tempElement.html());

                        // add the tooltip if appropriate
                        if (tooltipText !== null) {
                            el.attr('title', tooltipText);
                        }
                    }

                    tempElement.remove();
                }
            }
            else {
                // if this isn't visible, then hook up the show event
                el.one('show', function () {
                    $(this).ellipsis(addTooltip);
                });
            }
        });
    };

    // ellipsification for items with an ellipsis
    $(document).ready(function () {
        $('.ellipsis').ellipsis(true);
    });

} (jQuery));

Downloading Java JDK on Linux via wget is shown license page instead

Here's how to get the command yourself. This works for any version:

  1. Access packages page here: https://www.oracle.com/java/technologies/javase-jdk11-downloads.html
  2. Click the download link for your desired package
  3. Check the box indicating that you have "reviewed and accept..."
  4. Right-click & Copy the link address from the button
  5. Paste into a text editor and then copy everything AFTER 'nexturl=', beginning with 'https://'
  6. Update the download URL in this command and you should be good to go:

    wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" https://download.oracle.com/otn/java/jdk/11.0.6+8/90eb79fb590d45c8971362673c5ab495/jdk-11.0.6_linux-x64_bin.tar.gz

To further explain the wget, the --no-check-certificate should be clear enough, but the header content (for any call) is discoverable by using the Developer Tools Network Tab in your browser. The developer tools are powerful and are well worth the time to learn. Enjoy.

How to generate a random string of 20 characters

You may use the class java.util.Random with method

char c = (char)(rnd.nextInt(128-32))+32 

20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.

32 is the offset, from where the characters are printable in general.

Python can't find module in the same folder

I ran into this issue. I had three folders in the same directory so I had to specify which folder. Ex: from Folder import script

.setAttribute("disabled", false); changes editable attribute to false

just replace 'myselect' with your id

to disable->

document.getElementById("mySelect").disabled = true;  

to enable->

document.getElementById("mySelect").disabled = false; 

How do I calculate someone's age based on a DateTime type birthday?

The following approach (extract from Time Period Library for .NET class DateDiff) considers the calendar of the culture info:

// ----------------------------------------------------------------------
private static int YearDiff( DateTime date1, DateTime date2 )
{
  return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );
} // YearDiff

// ----------------------------------------------------------------------
private static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )
{
  if ( date1.Equals( date2 ) )
  {
    return 0;
  }

  int year1 = calendar.GetYear( date1 );
  int month1 = calendar.GetMonth( date1 );
  int year2 = calendar.GetYear( date2 );
  int month2 = calendar.GetMonth( date2 );

  // find the the day to compare
  int compareDay = date2.Day;
  int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );
  if ( compareDay > compareDaysPerMonth )
  {
    compareDay = compareDaysPerMonth;
  }

  // build the compare date
  DateTime compareDate = new DateTime( year1, month2, compareDay,
    date2.Hour, date2.Minute, date2.Second, date2.Millisecond );
  if ( date2 > date1 )
  {
    if ( compareDate < date1 )
    {
      compareDate = compareDate.AddYears( 1 );
    }
  }
  else
  {
    if ( compareDate > date1 )
    {
      compareDate = compareDate.AddYears( -1 );
    }
  }
  return year2 - calendar.GetYear( compareDate );
} // YearDiff

Usage:

// ----------------------------------------------------------------------
public void CalculateAgeSamples()
{
  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );
  // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years
  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );
  // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years
} // CalculateAgeSamples

// ----------------------------------------------------------------------
public void PrintAge( DateTime birthDate, DateTime moment )
{
  Console.WriteLine( "Birthdate={0:d}, Age at {1:d} is {2} years", birthDate, moment, YearDiff( birthDate, moment ) );
} // PrintAge

How to get string objects instead of Unicode from JSON?

I'm afraid there's no way to achieve this automatically within the simplejson library.

The scanner and decoder in simplejson are designed to produce unicode text. To do this, the library uses a function called c_scanstring (if it's available, for speed), or py_scanstring if the C version is not available. The scanstring function is called several times by nearly every routine that simplejson has for decoding a structure that might contain text. You'd have to either monkeypatch the scanstring value in simplejson.decoder, or subclass JSONDecoder and provide pretty much your own entire implementation of anything that might contain text.

The reason that simplejson outputs unicode, however, is that the json spec specifically mentions that "A string is a collection of zero or more Unicode characters"... support for unicode is assumed as part of the format itself. Simplejson's scanstring implementation goes so far as to scan and interpret unicode escapes (even error-checking for malformed multi-byte charset representations), so the only way it can reliably return the value to you is as unicode.

If you have an aged library that needs an str, I recommend you either laboriously search the nested data structure after parsing (which I acknowledge is what you explicitly said you wanted to avoid... sorry), or perhaps wrap your libraries in some sort of facade where you can massage the input parameters at a more granular level. The second approach might be more manageable than the first if your data structures are indeed deeply nested.

How can I send an Ajax Request on button click from a form with 2 buttons?

function sendAjaxRequest(element,urlToSend) {
             var clickedButton = element;
              $.ajax({type: "POST",
                  url: urlToSend,
                  data: { id: clickedButton.val(), access_token: $("#access_token").val() },
                  success:function(result){
                    alert('ok');
                  },
                 error:function(result)
                  {
                  alert('error');
                 }
             });
     }

       $(document).ready(function(){
          $("#button_1").click(function(e){
              e.preventDefault();
              sendAjaxRequest($(this),'/pages/test/');
          });

          $("#button_2").click(function(e){
              e.preventDefault();
              sendAjaxRequest($(this),'/pages/test/');
          });
        });
  1. created as separate function for sending the ajax request.
  2. Kept second parameter as URL because in future you want to send data to different URL

What causes the Broken Pipe Error?

When peer close, you just do not know whether it just stop sending or both sending and receiving.Because TCP allows this, btw, you should know the difference between close and shutdown. If peer both stop sending and receiving, first you send some bytes, it will succeed. But the peer kernel will send you RST. So subsequently you send some bytes, your kernel will send you SIGPIPE signal, if you catch or ignore this signal, when your send returns, you just get Broken pipe error, or if you don't , the default behavior of your program is crashing.

How to solve error message: "Failed to map the path '/'."

The following works for me: 1. Right click on "Default web site" 2. Choose Advance settings 3. Setup Physical Path to C:\inetpub\wwwroot 4. Click OK. 5. Browse the Default web site. --> It works.

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

Textarea resize control is available via the CSS3 resize property:

textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }

Allowable values self-explanatory: none (disables textarea resizing), both, vertical and horizontal.

Notice that in Chrome, Firefox and Safari the default is both.

If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height, max-width, min-height, and min-width CSS properties to provide resizing within certain proportions.

Code example:

_x000D_
_x000D_
#textarea-wrapper {_x000D_
  padding: 10px;_x000D_
  background-color: #f4f4f4;_x000D_
  width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
  min-height:50px;_x000D_
  max-height:120px;_x000D_
  width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
  resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
  <label for="resize-default">Textarea (default):</label>_x000D_
  <textarea name="resize-default" id="resize-default"></textarea>_x000D_
  _x000D_
  <label for="resize-vertical">Textarea (vertical):</label>_x000D_
  <textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Running Facebook application on localhost

Forward is a great tool for helping with development of facebook apps locally, it supports SSL so the cert thing isn't a problem.

https://forwardhq.com/in-use/facebook

DISCLAIMER: I'm one of the devs

Possible to iterate backwards through a foreach?

It is possible if you can change the collection code that implements IEnumerable or IEnumerable (e.g. your own implementation of IList).

Create an Iterator doing this job for you, for example like the following implementation through the IEnumerable interface (assuming 'items' is a List field in this sample):

public IEnumerator<TObject> GetEnumerator()
{
    for (var i = items.Count - 1; i >= 0; i--)
    { 
        yield return items[i];
    }
}

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

Because of this your List will iterate in reverse order through your list.

Just a hint: You should clearly state this special behaviour of your list within the documentation (even better by choosing a self-explaining class name like Stack or Queue, too).

ASP.NET Core return JSON with status code

Awesome answers I found here and I also tried this return statement see StatusCode(whatever code you wish) and it worked!!!

return Ok(new {
                    Token = new JwtSecurityTokenHandler().WriteToken(token),
                    Expiration = token.ValidTo,
                    username = user.FullName,
                    StatusCode = StatusCode(200)
                });

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

embedding image in html email

I don't find any of the answers here useful, so I am providing my solution.

  1. The problem is that you are using multipart/related as the content type which is not good in this case. I am using multipart/mixed and inside it multipart/alternative (it works on most clients).

  2. The message structure should be as follows:

    [Headers]
    Content-type:multipart/mixed; boundary="boundary1"
    --boundary1
    Content-type:multipart/alternative; boundary="boundary2"
    --boundary2
    Content-Type: text/html; charset=ISO-8859-15
    Content-Transfer-Encoding: 7bit
    [HTML code with a href="cid:..."]
    
    --boundary2
    Content-Type: image/png;
    name="moz-screenshot.png"
    Content-Transfer-Encoding: base64
    Content-ID: <part1.06090408.01060107>
    Content-Disposition: inline; filename="moz-screenshot.png"
    [base64 image data here]
    
    --boundary2--
    --boundary1--
    

Then it will work

SQL using sp_HelpText to view a stored procedure on a linked server

Little addition in answer if you have different user rather then dbo then do like this.

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'

Finish an activity from another activity

I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me

I overrode onPause and called finish() inside that method.

Uploading both data and files in one form using Ajax?

I was having this same issue in ASP.Net MVC with HttpPostedFilebase and instead of using form on Submit I needed to use button on click where I needed to do some stuff and then if all OK the submit form so here is how I got it working

$(".submitbtn").on("click", function(e) {

    var form = $("#Form");

    // you can't pass Jquery form it has to be javascript form object
    var formData = new FormData(form[0]);

    //if you only need to upload files then 
    //Grab the File upload control and append each file manually to FormData
    //var files = form.find("#fileupload")[0].files;

    //$.each(files, function() {
    //  var file = $(this);
    //  formData.append(file[0].name, file[0]);
    //});

    if ($(form).valid()) {
        $.ajax({
            type: "POST",
            url: $(form).prop("action"),
            //dataType: 'json', //not sure but works for me without this
            data: formData,
            contentType: false, //this is requireded please see answers above
            processData: false, //this is requireded please see answers above
            //cache: false, //not sure but works for me without this
            error   : ErrorHandler,
            success : successHandler
        });
    }
});

this will than correctly populate your MVC model, please make sure in your Model, The Property for HttpPostedFileBase[] has the same name as the Name of the input control in html i.e.

<input id="fileupload" type="file" name="UploadedFiles" multiple>

public class MyViewModel
{
    public HttpPostedFileBase[] UploadedFiles { get; set; }
}

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

It will be better to Create a New role, then grant execute, select ... etc permissions to this role and finally assign users to this role.

Create role

CREATE ROLE [db_SomeExecutor] 
GO

Grant Permission to this role

GRANT EXECUTE TO db_SomeExecutor
GRANT INSERT  TO db_SomeExecutor

to Add users database>security> > roles > databaseroles>Properties > Add ( bottom right ) you can search AD users and add then

OR

   EXEC sp_addrolemember 'db_SomeExecutor', 'domainName\UserName'

Please refer this post

gradient descent using python and numpy

I know this question already have been answer but I have made some update to the GD function :

  ### COST FUNCTION

def cost(theta,X,y):
     ### Evaluate half MSE (Mean square error)
     m = len(y)
     error = np.dot(X,theta) - y
     J = np.sum(error ** 2)/(2*m)
     return J

 cost(theta,X,y)



def GD(X,y,theta,alpha):

    cost_histo = [0]
    theta_histo = [0]

    # an arbitrary gradient, to pass the initial while() check
    delta = [np.repeat(1,len(X))]
    # Initial theta
    old_cost = cost(theta,X,y)

    while (np.max(np.abs(delta)) > 1e-6):
        error = np.dot(X,theta) - y
        delta = np.dot(np.transpose(X),error)/len(y)
        trial_theta = theta - alpha * delta
        trial_cost = cost(trial_theta,X,y)
        while (trial_cost >= old_cost):
            trial_theta = (theta +trial_theta)/2
            trial_cost = cost(trial_theta,X,y)
            cost_histo = cost_histo + trial_cost
            theta_histo = theta_histo +  trial_theta
        old_cost = trial_cost
        theta = trial_theta
    Intercept = theta[0] 
    Slope = theta[1]  
    return [Intercept,Slope]

res = GD(X,y,theta,alpha)

This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.

Why is my Button text forced to ALL CAPS on Lollipop?

Use this line android:textAllCaps="false" in your xml

<Button
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/login_str"
            android:background="@color/colorBlue"
            android:textColor="@color/colorWhite"
            android:textAllCaps="false"
           />

Insert a new row into DataTable

@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);

DataRow dr = dt.NewRow();

dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";

dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

Assigning variables with dynamic names in Java

If you want to access the variables some sort of dynamic you may use reflection. However Reflection works not for local variables. It is only applyable for class attributes.

A rough quick and dirty example is this:

public class T {
    public Integer n1;
    public Integer n2;
    public Integer n3;

    public void accessAttributes() throws IllegalArgumentException, SecurityException, IllegalAccessException,
            NoSuchFieldException {

        for (int i = 1; i < 4; i++) {
            T.class.getField("n" + i).set(this, 5);
        }
    }
}

You need to improve this code in various ways it is only an example. This is also not considered to be good code.

Uncaught TypeError: undefined is not a function on loading jquery-min.js

Assuming this problem still has not be resolved, a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with (jQuery) and you need to have (jQuery);.

As separate files the script will load just fine but as one individual file you need the semicolons.

jQuery.css() - marginLeft vs. margin-left?

jQuery is simply supporting the way CSS is written.

Also, it ensures that no matter how a browser returns a value, it will be understood

jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').

babel-loader jsx SyntaxError: Unexpected token

I ran into a similar issue when migrating from babel 5 to babel 6.

I was just running babel to compile the src to lib folder babel src --out-dir lib

I will share my setup for babel 6:

Ensure you have the following babel 6 devDependencies installed

"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0"

Add your .babelrc file to the project:

{
  "presets": ["es2015", "stage-0", "react"]
}

PHP cURL not working - WAMP on Windows 7 64 bit

This work for me: http://www.mediafire.com/?3ay381k3cq59cm2 download a paste the file in ext folder PHP 5.4.3

How to extract epoch from LocalDate and LocalDateTime?

Look at this method to see which fields are supported. You will find for LocalDateTime:

•NANO_OF_SECOND 
•NANO_OF_DAY 
•MICRO_OF_SECOND 
•MICRO_OF_DAY 
•MILLI_OF_SECOND 
•MILLI_OF_DAY 
•SECOND_OF_MINUTE 
•SECOND_OF_DAY 
•MINUTE_OF_HOUR 
•MINUTE_OF_DAY 
•HOUR_OF_AMPM 
•CLOCK_HOUR_OF_AMPM 
•HOUR_OF_DAY 
•CLOCK_HOUR_OF_DAY 
•AMPM_OF_DAY 
•DAY_OF_WEEK 
•ALIGNED_DAY_OF_WEEK_IN_MONTH 
•ALIGNED_DAY_OF_WEEK_IN_YEAR 
•DAY_OF_MONTH 
•DAY_OF_YEAR 
•EPOCH_DAY 
•ALIGNED_WEEK_OF_MONTH 
•ALIGNED_WEEK_OF_YEAR 
•MONTH_OF_YEAR 
•PROLEPTIC_MONTH 
•YEAR_OF_ERA 
•YEAR 
•ERA 

The field INSTANT_SECONDS is - of course - not supported because a LocalDateTime cannot refer to any absolute (global) timestamp. But what is helpful is the field EPOCH_DAY which counts the elapsed days since 1970-01-01. Similar thoughts are valid for the type LocalDate (with even less supported fields).

If you intend to get the non-existing millis-since-unix-epoch field you also need the timezone for converting from a local to a global type. This conversion can be done much simpler, see other SO-posts.

Coming back to your question and the numbers in your code:

The result 1605 is correct
  => (2014 - 1970) * 365 + 11 (leap days) + 31 (in january 2014) + 3 (in february 2014)
The result 71461 is also correct => 19 * 3600 + 51 * 60 + 1

16105L * 86400 + 71461 = 1391543461 seconds since 1970-01-01T00:00:00 (attention, no timezone) Then you can subtract the timezone offset (watch out for possible multiplication by 1000 if in milliseconds).

UPDATE after given timezone info:

local time = 1391543461 secs
offset = 3600 secs (Europe/Oslo, winter time in february)
utc = 1391543461 - 3600 = 1391539861

As JSR-310-code with two equivalent approaches:

long secondsSinceUnixEpoch1 =
  LocalDateTime.of(2014, 2, 4, 19, 51, 1).atZone(ZoneId.of("Europe/Oslo")).toEpochSecond();

long secondsSinceUnixEpoch2 =
  LocalDate
    .of(2014, 2, 4)
    .atTime(19, 51, 1)
    .atZone(ZoneId.of("Europe/Oslo"))
    .toEpochSecond();

What's the difference between using CGFloat and float?

just mention that - Jan, 2020 Xcode 11.3/iOS13

Swift 5

From the CoreGraphics source code

public struct CGFloat {
    /// The native type used to store the CGFloat, which is Float on
    /// 32-bit architectures and Double on 64-bit architectures.
    public typealias NativeType = Double

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

As mentioned here, you need to remove the unused references and the warnings will go.

jQuery first child of "this"

Have you tried

$(":first-child", element).toggleClass("redClass");

I think you want to set your element as a context for your search. There might be a better way to do this which some other jQuery guru will hop in here and throw out at you :)

Assign output to variable in Bash

Same with something more complex...getting the ec2 instance region from within the instance.

INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")

echo $INSTANCE_REGION

How to declare empty list and then add string in scala?

In your case I use: val dm = ListBuffer[String]() and val dk = ListBuffer[Map[String,anyRef]]()

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

How to quit android application programmatically

If you want to close your app:

For API >= 21, use:

finishAndRemoveTask();

For API < 21 use:

finishAffinity();

Append text to textarea with javascript

Use event delegation by assigning the onclick to the <ol>. Then pass the event object as the argument, and using that, grab the text from the clicked element.

_x000D_
_x000D_
function addText(event) {_x000D_
    var targ = event.target || event.srcElement;_x000D_
    document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
  <li>Hello</li>_x000D_
  <li>World</li>_x000D_
  <li>Earthlings</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Note that this method of passing the event object works in older IE as well as W3 compliant systems.

how to zip a folder itself using java

This method zips a folder and adds all of the child files & folders (including empty folders) into the zip file.

void zipFolder(Path sourceDir, Path targetFile) throws IOException {
    ZipDirectoryVisitor zipVisitor = new ZipDirectoryVisitor(sourceDir);
    Files.walkFileTree(sourceDir, zipVisitor);
    FileOutputStream fos = new FileOutputStream(targetFile.toString());
    ZipOutputStream zos = new ZipOutputStream(fos);
    byte[] buffer = new byte[1024];
    for (ZipEntry entry : zipVisitor.getZipEntries()) {
        zos.putNextEntry(entry);
        Path curFile = Paths.get(sourceDir.getParent().toString(), entry.toString());
        if (!curFile.toFile().isDirectory()) {
            FileInputStream in = new FileInputStream(Paths.get(sourceDir.getParent().toString(), entry.toString()).toString());
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
    }
    zos.close();

}

And here is the ZipDirectoryVisitor implementation:

class ZipDirectoryVisitor extends SimpleFileVisitor<Path> {
    private Path dirToZip;
    private List<ZipEntry> zipEntries; // files and folders inside source folder as zip entries
    public ZipDirectoryVisitor(Path dirToZip) throws IOException {
        this.dirToZip = dirToZip;
        zipEntries = new ArrayList<>();
    }

    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException {
        // According to zip standard backslashes
        // should not be used in zip entries
        String zipFile = dirToZip.getParent().relativize(path).toString().replace("\\", "/");
        ZipEntry entry = new ZipEntry(zipFile);
        zipEntries.add(entry);
        return FileVisitResult.CONTINUE;
    }


    @Override
    public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes) throws IOException {
        String zipDir = dirToZip.getParent().relativize(path).toString().replace("\\", "/");
        // Zip directory entries should end with a forward slash
        ZipEntry entry = new ZipEntry(zipDir + "/");
        zipEntries.add(entry);
        return FileVisitResult.CONTINUE;
    }


    @Override
    public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
        System.err.format("Could not visit file %s while creating a file list from file tree", path);
        return FileVisitResult.TERMINATE;
    }

    public List<ZipEntry> getZipEntries() {
        return zipEntries;
    }
}

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Believe or not, keytool does not provide such basic functionality like importing private key to keystore. You can try this workaround with merging PKSC12 file with private key to a keystore:

keytool -importkeystore \
  -deststorepass storepassword \
  -destkeypass keypassword \
  -destkeystore my-keystore.jks \
  -srckeystore cert-and-key.p12 \
  -srcstoretype PKCS12 \
  -srcstorepass p12password \
  -alias 1

Or just use more user-friendly KeyMan from IBM for keystore handling instead of keytool.

Mac OS X - EnvironmentError: mysql_config not found

brew install mysql added mysql to /usr/local/Cellar/..., so I needed to add :/usr/local/Cellar/ to my $PATH and then which mysql_config worked!

Store JSON object in data attribute in HTML jQuery

The trick for me was to add double quotes around keys and values. If you use a PHP function like json_encode will give you a JSON encoded string and an idea how to properly encode yours.

jQuery('#elm-id').data('datakey') will return an object of the string, if the string is properly encoded as json.

As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)

Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:

  1. "{test: 1}" (test does not have double quotes around it).
  2. "{'test': 1}" ('test' is using single quotes instead of double quotes).
  3. "'test'" ('test' is using single quotes instead of double quotes).
  4. ".1" (a number must start with a digit; "0.1" would be valid).
  5. "undefined" (undefined cannot be represented in a JSON string; null, however, can be).
  6. "NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is also n

How to set a default value with Html.TextBoxFor?

You can simply do :

<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>

or better, this will switch to default value '0' if the model is null, for example if you have the same view for both editing and creating :

@Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })