Programs & Examples On #Django authopenid

django-authopenid is a pluggable Django app that allows you to authenticate your users while using the django auth contrib

How to check whether a pandas DataFrame is empty?

1) If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame
is empty or not then try this code.
2) when this situation can happen? 
This situation happens when a single function is used to plot more than one DataFrame 
which are passed as parameter.In such a situation the function try to plot the data even 
when a DataFrame is empty and thus plot an empty figure!.
It will make sense if simply display 'DataFrame has no data' message.
3) why? 
if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values 
is considered non empty) then it is desirable not to plot but put out a message :
Suppose we have two DataFrames df1 and df2.
The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message 
if a DataFrame is empty(instead of plotting):
df1                     df2
col1 col2           col1 col2 
Nan   2              Nan  Nan 
2     Nan            Nan  Nan  

and the function:

def myfunc(df):
  if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
     print('not empty')
     df.plot(kind='barh')
  else:
     display a message instead of plotting if it is empty
     print('empty')

Get all table names of a particular database by SQL query?

This works Fine

SELECT * FROM information_schema.tables;

What to gitignore from the .idea folder?

in my case /**/.idea/* works well

Call a PHP function after onClick HTML event

You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:

<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
    {
    $new = '{';
    $new .= '"fullname":"' . $_GET['fullname'] . '",';
    $new .= '"email":"' . $_GET['email'] . '",';
    $new .= '"phone":"' . $_GET['phone'] . '",';
    $new .= '}';
    return $new;
    }

function saveContact()
    {
    $datafile = fopen ("data/data.json", "a+");
    if(!$datafile){
        echo "<script>alert('Data not existed!')</script>";
        } 
    else{
        $contact_list = $contact_list . addNewContact();
        file_put_contents("data/data.json", $contact_list);
        }
    fclose($datafile);
    }

// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled

{ ?>

<form>
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact"/>
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->

Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...

Other thought, IE doesn't support placeholder.

How to set a JavaScript breakpoint from code in Chrome?

You can also use debug(function), to break when function is called.

Command Line API Reference: debug

Converting a view to Bitmap without displaying it in Android?

Try this,

/**
 * Draw the view into a bitmap.
 */
public static Bitmap getViewBitmap(View v) {
    v.clearFocus();
    v.setPressed(false);

    boolean willNotCache = v.willNotCacheDrawing();
    v.setWillNotCacheDrawing(false);

    // Reset the drawing cache background color to fully transparent
    // for the duration of this operation
    int color = v.getDrawingCacheBackgroundColor();
    v.setDrawingCacheBackgroundColor(0);

    if (color != 0) {
        v.destroyDrawingCache();
    }
    v.buildDrawingCache();
    Bitmap cacheBitmap = v.getDrawingCache();
    if (cacheBitmap == null) {
        Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
        return null;
    }

    Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

    // Restore the view
    v.destroyDrawingCache();
    v.setWillNotCacheDrawing(willNotCache);
    v.setDrawingCacheBackgroundColor(color);

    return bitmap;
}

Generating random strings with T-SQL

I realize that this is an old question with many fine answers. However when I found this I also found a more recent article on TechNet by Saeid Hasani

T-SQL: How to Generate Random Passwords

While the solution focuses on passwords it applies to the general case. Saeid works through various considerations to arrive at a solution. It is very instructive.

A script containing all the code blocks form the article is separately available via the TechNet Gallery, but I would definitely start at the article.

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

Windows equivalent of the 'tail' command

you can also use Git bash where head and tail are emulated as well

The name 'model' does not exist in current context in MVC3

It is a horrible mistake but:

Be sure you have Web.config files in your View at Remote. Maybe you skipped to upload it by your Ftp programme's filters.

Find the last time table was updated

Find last time of update on a table

SELECT
tbl.name
,ius.last_user_update
,ius.user_updates
,ius.last_user_seek
,ius.last_user_scan
,ius.last_user_lookup
,ius.user_seeks
,ius.user_scans
,ius.user_lookups
FROM
sys.dm_db_index_usage_stats ius INNER JOIN
sys.tables tbl ON (tbl.OBJECT_ID = ius.OBJECT_ID)
WHERE ius.database_id = DB_ID()

http://www.sqlserver-dba.com/2012/10/sql-server-find-last-time-of-update-on-a-table.html

Properly Handling Errors in VBA (Excel)

I keep things simple:
At the module level I define two variables and set one to the name of the module itself.

    Private Const ThisModuleName            As String = "mod_Custom_Functions"
    Public sLocalErrorMsg                   As String

Within each Sub/Function of the module I define a local variable

    Dim ThisRoutineName                     As String

I set ThisRoutineName to the name of the sub or function

' Housekeeping
    On Error Goto ERR_RTN
    ThisRoutineName = "CopyWorksheet"

I then send all errors to an ERR_RTN: when they occur, but I first set the sLocalErrorMsg to define what the error actually is and provide some debugging info.

    If Len(Trim(FromWorksheetName)) < 1 Then
        sLocalErrorMsg = "Parameter 'FromWorksheetName' Is Missing."
        GoTo ERR_RTN
    End If

At the bottom of each sub/function, I direct the logic flow as follows

    '
    ' The "normal" logic goes here for what the routine does
    '
    GoTo EXIT_RTN

    ERR_RTN:

        On Error Resume Next

    ' Call error handler if we went this far.
        ErrorHandler ThisModuleName, ThisRoutineName, sLocalErrorMsg, Err.Description, Err.Number, False

    EXIT_RTN:

        On Error Resume Next
     '
     ' Some closing logic
     '
    End If

I then have a seperate module I put in all projects called "mod_Error_Handler".

    '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Subroutine Name:     ErrorHandler                                                     '
    '                                                                                       '
    ' Description:                                                                          '
    '   This module will handle the common error alerts.                                    '
    '                                                                                       '
    ' Inputs:                                                                               '
    '   ModuleName                String    'The name of the module error is in.            '
    '   RoutineName               String    'The name of the routine error in in.           '
    '   LocalErrorMsg             String    'A local message to assist with troubleshooting.'
    '   ERRDescription            String    'The Windows Error Description.                 '
    '   ERRCode                   Long      'The Windows Error Code.                        '
    '   Terminate                 Boolean   'End program if error encountered?              '
    '                                                                                       '
    ' Revision History:                                                                     '
    ' Date (YYYYMMDD) Author                Change                                          '
    ' =============== ===================== =============================================== '
    ' 20140529        XXXXX X. XXXXX        Original                                        '
    '                                                                                       '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '
    Public Sub ErrorHandler(ModuleName As String, RoutineName As String, LocalErrorMsg As String, ERRDescription As String, ERRCode As Long, Terminate As Boolean)
        Dim sBuildErrorMsg                 As String

    ' Build Error Message To Display
        sBuildErrorMsg = "Error Information:" & vbCrLf & vbCrLf

        If Len(Trim(ModuleName)) < 1 Then
            ModuleName = "Unknown"
        End If

        If Len(Trim(RoutineName)) < 1 Then
           RoutineName = "Unknown"
        End If

        sBuildErrorMsg = sBuildErrorMsg & "Module Name:        " & ModuleName & vbCrLf & vbCrLf
        sBuildErrorMsg = sBuildErrorMsg & "Routine Name:       " & RoutineName & vbCrLf & vbCrLf

        If Len(Trim(LocalErrorMsg)) > 0 Then
            sBuildErrorMsg = sBuildErrorMsg & "Local Error Msg:    " & LocalErrorMsg & vbCrLf & vbCrLf
        End If

        If Len(Trim(ERRDescription)) > 0 Then
            sBuildErrorMsg = sBuildErrorMsg & "Program Error Msg:  " & ERRDescription & vbCrLf & vbCrLf
            If IsNumeric(ERRCode) Then
                sBuildErrorMsg = sBuildErrorMsg & "Program Error Code: " & Trim(Str(ERRCode)) & vbCrLf & vbCrLf
            End If
        End If

        MsgBox sBuildErrorMsg, vbOKOnly + vbExclamation, "Error Detected!"

        If Terminate Then
            End
        End If

    End Sub

The end result is a pop-up error message teling me in what module, what soubroutine, and what the error message specifically was. In addition, it also will insert the Windows error message and code.

how to add button click event in android studio

SetOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)

This means in other words (due to your current scenario) that your MainActivity need to implement OnClickListener:

public class Main extends ActionBarActivity implements View.OnClickListener {
   // do your stuff
}

This:

buttonname.setOnClickListener(this);

means that you want to assign listener for your Button "on this instance" -> this instance represents OnClickListener and for this reason your class have to implement that interface.

It's similar with anonymous listener class (that you can also use):

buttonname.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

   }
});

What does the "More Columns than Column Names" error mean?

you have have strange characters in your heading # % -- or ,

C++ Calling a function from another class

    void CallFunction ()
    {   // <----- At this point the compiler knows
        //        nothing about the members of B.
        B b;
        b.bFunction();
    }

This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.

To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.

class A
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    { ... }
};

void A::CallFunction ()
{
    B b;
    b.bFunction();
}

Invert colors of an image in CSS or JavaScript

For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.

HTML if image is not found

Try using border=0 in the img tag to make the ugly square go away.

<img src="someimage.png" border="0" alt="some alternate text" />

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark directives show up in Xcode in the menus for direct access to methods. They have no impact on the program at all.

For example, using it with Xcode 4 will make those items appear directly in the Jump Bar.

There is a special pragma mark - which creates a line.

enter image description here

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

SQL - How to find the highest number in a column?

You can also use relational algebra. A bit lengthy procedure, but here it is just to understand how MAX() works:

E := pID (Table_Name)
E1 := pID (sID >= ID' ((?ID' E) ? E)) – pID (sID < ID’ ((?ID' E) ? E))

Your answer: Table_Name ? E1

Basically what you do is subtract set of ordered relation(a,b) in which a<b from A where a, b ? A.

For relation algebra symbols see: Relational algebra From Wikipedia

How can I output leading zeros in Ruby?

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

cannot convert data (type interface {}) to type string: need type assertion

Type Assertion

This is known as type assertion in golang, and it is a common practice.

Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.

Pitfalls

Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance

As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

can not find module "@angular/material"

I followed each of the suggestions here (I'm using Angular 7), but nothing worked. My app refused to acknowledge that @angular/material existed, so it showed an error on this line:

import { MatCheckboxModule } from '@angular/material';

Even though I was using the --save parameter to add Angular Material to my project:

npm install --save @angular/material @angular/cdk

...it refused to add anything to my "package.json" file.

I even tried deleting the package-lock.json file, as some articles suggest that this causes problems, but this had no effect.

To fix this issue, I had to manually add these two lines to my "package.json" file.

{
    "devDependencies": {
        ...
        "@angular/material": "~7.2.2",
        "@angular/cdk": "~7.2.2",
        ...

What I can't tell is whether this is an issue related to using Angular 7, or if it's been around for years....

ImportError: No module named sklearn.cross_validation

Make sure you have Anaconda installed and then create a virtualenv using conda. This will ensure all the imports work

Python 2.7.9 |Anaconda 2.2.0 (64-bit)| (default, Mar  9 2015, 16:20:48) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> from sklearn.cross_validation import train_test_split

How to import and export components using React + ES6 + webpack?

Wrapping components with braces if no default exports:

import {MyNavbar} from './comp/my-navbar.jsx';

or import multiple components from single module file

import {MyNavbar1, MyNavbar2} from './module';

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

deleted the c#... here is the vb.net

<%=Html.ActionLink("Home", "Index", "Home", New With {.class = "tab"}, Nothing)%>

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

How to distinguish between left and right mouse click with jQuery

there is also a way, to do it without JQuery!

check out this:

document.addEventListener("mousedown", function(evt) {
    switch(evt.buttons) {
      case 1: // left mouse
      case 2: // right mouse
      case 3: // middle mouse <- I didn't tested that, I just got a touchpad
    }
});

background-size in shorthand background property (CSS3)

try out like this

body {
   background: #fff url("!--MIZO-PRO--!") no-repeat center 15px top 15px/100px;
     }


/* 100px is the background size */

How to print variable addresses in C?

To print the address of a variable, you need to use the %p format. %d is for signed integers. For example:

#include<stdio.h>

void main(void)
{
  int a;

  printf("Address is %p:",&a);
}

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

How to get error information when HttpWebRequest.GetResponse() fails

I faced a similar situation:

I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.

However, when reading the response using GetResponseStream(), got the error:

Stream not readable

So, this code worked for me:

try
{
    response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
    var webException = exception.InnerException as WebException;
    var rawResponse = string.Empty;

    var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
    using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
    using (var reader = new StreamReader(brandNewStream))
        rawResponse = reader.ReadToEnd();
}

Scrollbar without fixed height/Dynamic height with scrollbar

Use this:

#head {
    border: green solid 1px;
    height:auto;
}    
#content{
            border: red solid 1px;
            overflow-y: scroll;
            height:150px;       
        }

HTTP POST using JSON in Java

Here is what you need to do:

  1. Get the Apache HttpClient, this would enable you to make the required request
  2. Create an HttpPost request with it and add the header application/x-www-form-urlencoded
  3. Create a StringEntity that you will pass JSON to it
  4. Execute the call

The code roughly looks like (you will still need to debug it and make it work):

// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/x-www-form-urlencoded");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
    // @Deprecated httpClient.getConnectionManager().shutdown(); 
}

How to fill Dataset with multiple tables?

         string connetionString = null;
        SqlConnection connection ;
        SqlCommand command ;
        SqlDataAdapter adapter = new SqlDataAdapter();
        DataSet ds = new DataSet();
        int i = 0;
        string firstSql = null;
        string secondSql = null;

        connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
        firstSql = "Your First SQL Statement Here";
        secondSql = "Your Second SQL Statement Here";
        connection = new SqlConnection(connetionString);

        try
        {
            connection.Open();

            command = new SqlCommand(firstSql, connection);
            adapter.SelectCommand = command;
            adapter.Fill(ds, "First Table");

            adapter.SelectCommand.CommandText = secondSql;
            adapter.Fill(ds, "Second Table");

            adapter.Dispose();
            command.Dispose();
            connection.Close();

            //retrieve first table data 
            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
            }
            //retrieve second table data 
            for (i = 0; i <= ds.Tables[1].Rows.Count - 1; i++)
            {
                MessageBox.Show(ds.Tables[1].Rows[i].ItemArray[0] + " -- " + ds.Tables[1].Rows[i].ItemArray[1]);

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Can not open connection ! ");
        }

Print Pdf in C#

The easiest way is to create C# Process and launch external tool to print your PDF file

private static void ExecuteRawFilePrinter() {
    Process process = new Process();
    process.StartInfo.FileName = "c:\\Program Files (x86)\\RawFilePrinter\\RawFilePrinter.exe";
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.Arguments = string.Format("-p \"c:\\Users\\Me\\Desktop\\mypdffile.pdf\" \"gdn02ptr006\"");
    process.Start();
    process.WaitForExit();
}

Code above launches RawFilePrinter.exe (similar to 2Printer.exe), but with better support. It is not free, but by making donation allow you to use it everywhere and redistribute with your application. Latest version to download: http://bigdotsoftware.pl/rawfileprinter

What is the difference between DBMS and RDBMS?

There are other database systems, such as document stores, key value stores, columnar stores, object oriented databases. These are databases too but they are not based on relations (relational theory) ie they are not relational database systems.

So there are lot of differences. Database management system is the name for all databases.

SELECT inside a COUNT

SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc

How to use table variable in a dynamic sql statement?

On SQL Server 2008+ it is possible to use Table Valued Parameters to pass in a table variable to a dynamic SQL statement as long as you don't need to update the values in the table itself.

So from the code you posted you could use this approach for @TSku but not for @RelPro

Example syntax below.

CREATE TYPE MyTable AS TABLE 
( 
Foo int,
Bar int
);
GO


DECLARE @T AS MyTable;

INSERT INTO @T VALUES (1,2), (2,3)

SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T

EXEC sp_executesql
  N'SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
    FROM @T',
  N'@T MyTable READONLY',
  @T=@T 

The physloc column is included just to demonstrate that the table variable referenced in the child scope is definitely the same one as the outer scope rather than a copy.

Java check to see if a variable has been initialized

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

Jquery UI datepicker. Disable array of Dates

beforeShowDate didn't work for me, so I went ahead and developed my own solution:

$('#embeded_calendar').datepicker({
               minDate: date,
                localToday:datePlusOne,
               changeDate: true,
               changeMonth: true,
               changeYear: true,
               yearRange: "-120:+1",
               onSelect: function(selectedDateFormatted){

                     var selectedDate = $("#embeded_calendar").datepicker('getDate');

                    deactivateDates(selectedDate);
                   }

           });


              var excludedDates = [ "10-20-2017","10-21-2016", "11-21-2016"];

              deactivateDates(new Date());

            function deactivateDates(selectedDate){
                setTimeout(function(){ 
                      var thisMonthExcludedDates = thisMonthDates(selectedDate);
                      thisMonthExcludedDates = getDaysfromDate(thisMonthExcludedDates);
                       var excludedTDs = page.find('td[data-handler="selectDay"]').filter(function(){
                           return $.inArray( $(this).text(), thisMonthExcludedDates) >= 0
                       });

                       excludedTDs.unbind('click').addClass('ui-datepicker-unselectable');
                   }, 10);
            }

            function thisMonthDates(date){
              return $.grep( excludedDates, function( n){
                var dateParts = n.split("-");
                return dateParts[0] == date.getMonth() + 1  && dateParts[2] == date.getYear() + 1900;
            });
            }

            function getDaysfromDate(datesArray){
                  return  $.map( datesArray, function( n){
                    return n.split("-")[1]; 
                });
             }

How do I get only directories using Get-ChildItem?

Use:

dir -Directory -Recurse | Select FullName

This will give you an output of the root structure with the folder name for directories only.

Difference between a SOAP message and a WSDL?

A SOAP document is sent per request. Say we were a book store, and had a remote server we queried to learn the current price of a particular book. Say we needed to pass the Book's title, number of pages and ISBN number to the server.

Whenever we wanted to know the price, we'd send a unique SOAP message. It'd look something like this;

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <m:GetBookPrice xmlns:m="http://namespaces.my-example-book-info.com">
      <ISBN>978-0451524935</ISBN>
      <Title>1984</Title>
      <NumPages>328</NumPages>
    </m:GetBookPrice>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope> 

And we expect to get a SOAP response message back like;

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <m:GetBookPriceResponse xmlns:m="http://namespaces.my-example-book-info.com">
      <CurrentPrice>8.99</CurrentPrice>
      <Currency>USD</Currency>
    </m:GetBookPriceResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The WSDL then describes how to handle/process this message when a server receives it. In our case, it describes what types the Title, NumPages & ISBN would be, whether we should expect a response from the GetBookPrice message and what that response should look like.

The types would look like this;

<wsdl:types>

  <!-- all type declarations are in a chunk of xsd -->
  <xsd:schema targetNamespace="http://namespaces.my-example-book-info.com"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">

    <xsd:element name="GetBookPrice">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="ISBN" type="string"/>
          <xsd:element name="Title" type="string"/>
          <xsd:element name="NumPages" type="integer"/>
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>

    <xsd:element name="GetBookPriceResponse">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="CurrentPrice" type="decimal" />
          <xsd:element name="Currency" type="string" />
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>

  </xsd:schema>
</wsdl:types>

But the WSDL also contains more information, about which functions link together to make operations, and what operations are avaliable in the service, and whereabouts on a network you can access the service/operations.

See also W3 Annotated WSDL Examples

What does it mean when an HTTP request returns status code 0?

As detailed by this answer on this page, a status code of 0 means the request failed for some reason, and a javascript library interpreted the fail as a status code of 0.

To test this you can do either of the following:

1) Use this chrome extension, Requestly to redirect your url from the https version of your url to the http version, as this will cause a mixed content security error, and ultimately generate a status code of 0. The advantage of this approach is that you don't have to change your app at all, and you can simply "rewrite" your url using this extension.

2) Change the code of your app to optionally make your endpoint redirect to the http version of your url instead of the https version (or vice versa). If you do this, the request will fail with status code 0.

How to include js and CSS in JSP with spring MVC

Put your style.css directly into the webapp/css folder, not into the WEB-INF folder.

Then add the following code into your spring-dispatcher-servlet.xml

<mvc:resources mapping="/css/**" location="/css/" />

and then add following code into your jsp page

<link rel="stylesheet" type="text/css" href="css/style.css"/>

I hope it will work.

WARNING: sanitizing unsafe style value url

There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272

I didn't read in detail when this warning is printed when nothing was sanitized.

How to change the color of text in javafx TextField?

If you are designing your Javafx application using SceneBuilder then use -fx-text-fill(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield.

I came here for the same problem and solved it in this way.

How to find numbers from a string?

Alternative via Byte Array

If you assign a string to a Byte array you typically get the number equivalents of each character in pairs of the array elements. Use a loop for numeric check via the Like operator and return the joined array as string:

Function Nums(s$)
  Dim by() As Byte, i&, ii&
  by = s: ReDim tmp(UBound(by))                    ' assign string to byte array; prepare temp array
  For i = 0 To UBound(by) - 1 Step 2               ' check num value in byte array (0, 2, 4 ... n-1)
      If Chr(by(i)) Like "#" Then tmp(ii) = Chr(by(i)): ii = ii + 1
  Next i
  Nums = Trim(Join(tmp, vbNullString))             ' return string with numbers only
  End Function

Example call

Sub testByteApproach()
  Dim s$: s = "a12bx99y /\:3,14159"                 ' [1] define original string
  Debug.Print s & " => " & Nums(s)                  ' [2] display original string and result
End Sub

would display the original string and the result string in the immediate window:

  a12bx99y /\:3,14159 => 1299314159

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

In your build.gradle file add useLibrary 'org.apache.http.legacy' as per Android 6.0 Changes > Apache HTTP Client Removal notes.

android {
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

To avoid missing link errors add to dependencies

dependencies {
    provided 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

using 'provided' the dependency will be not included in the apk

refresh leaflet map: map container is already initialized

if you want update map view, for example change map center, you don’t have to delete and then recreate the map, you can just update coordinate

const mapInit = () => {
 let map.current = w.L.map('map');

 L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright" target="_blank">OpenStreetMap</a> contributors'
 }).addTo(map.current);
}

const setCoordinate = (gps_lat, gps_long) => {
  map.setView([gps_lat, gps_long], 13);
}

initMap();

setCoordinate(50.403723 30.623538);

setTimeout(() => {
  setCoordinate(51.505, -0.09);
}, 3000);

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

you need to do one step:

run->cmd

run "c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i"

Thats it

How can I get column names from a table in Oracle?

I did it like this

SELECT 
    TOP 0
    *
FROM
    Posts

It works even in http://data.stackexchange.com whose service tables I am not aware of!

_csv.Error: field larger than field limit (131072)

You can use read_csv from pandas to skip these lines.

import pandas as pd

data_df = pd.read_csv('data.csv', error_bad_lines=False)

Python3 project remove __pycache__ folders and .pyc files

This is my alias that works both with Python 2 and Python 3 removing all .pyc .pyo files as well __pycache__ directories recursively.

alias pyclean='find . -name "*.py[co]" -o -name __pycache__ -exec rm -rf {} +'

POST data to a URL in PHP

If you're looking to post data to a URL from PHP code itself (without using an html form) it can be done with curl. It will look like this:

$url = 'http://www.someurl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

This will send the post variables to the specified url, and what the page returns will be in $response.

Modify tick label text

One can also do this with pylab and xticks

import matplotlib
import matplotlib.pyplot as plt
x = [0,1,2]
y = [90,40,65]
labels = ['high', 'low', 37337]
plt.plot(x,y, 'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()

http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html

How do I sort a Set to a List in Java?

Sorted set:

return new TreeSet(setIWantSorted);

or:

return new ArrayList(new TreeSet(setIWantSorted));

Will #if RELEASE work like #if DEBUG does in C#?

why not just

#if RELEASE
#undef DEBUG
#endif

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

To install npm on windows just unzip the npm archive where node is. See the docs for more detail.

npm is shipped with node, that is how you should install it. nvm is only for changing node versions and does not install npm. A cleaner way to use npm and nvm is to first install node as it is (with npm), then install the nvm package by npm install nvm

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

Character Limit in HTML

For the <input> element there's the maxlength attribute:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

(by the way, the type is "text", not "textbox" as others are writing), however, you have to use javascript with <textarea>s. Either way the length should be checked on the server anyway.

Accessing an SQLite Database in Swift

Yet another SQLite wrapper for Swift 2 and Swift 3: http://github.com/groue/GRDB.swift

Features:

  • An API that will look familiar to users of ccgus/fmdb

  • A low-level SQLite API that leverages the Swift standard library

  • A pretty Swift query interface for SQL-allergic developers

  • Support for the SQLite WAL mode, and concurrent database access for extra performance

  • A Record class that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations

  • Swift type freedom: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types.

  • Database Migrations

  • Speed: https://github.com/groue/GRDB.swift/wiki/Performance

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

Like the docs say, think about it this way. If you were to do an application like a book reader, you will not want to load all the fragments into memory at once. You would like to load and destroy Fragments as the user reads. In this case you will use FragmentStatePagerAdapter. If you are just displaying 3 "tabs" that do not contain a lot of heavy data (like Bitmaps), then FragmentPagerAdapter might suit you well. Also, keep in mind that ViewPager by default will load 3 fragments into memory. The first Adapter you mention might destroy View hierarchy and re load it when needed, the second Adapter only saves the state of the Fragment and completely destroys it, if the user then comes back to that page, the state is retrieved.

Remove the last character in a string in T-SQL?

@result = substring(@result, 1, (LEN(@result)-1))

Use of for_each on map elements

Just an example:

template <class key, class value>
class insertIntoVec
{
public:
    insertIntoVec(std::vector<value>& vec_in):m_vec(vec_in)
    {}

    void operator () (const std::pair<key, value>& rhs)  
    {   
        m_vec.push_back(rhs.second);
    }

private:
    std::vector<value>& m_vec;
};

int main()
{
std::map<int, std::string> aMap;
aMap[1] = "test1";
aMap[2] = "test2";
aMap[3] = "test3";
aMap[4] = "test4";

std::vector<std::string> aVec;

aVec.reserve(aMap.size());
std::for_each(aMap.begin(), aMap.end(),
          insertIntoVec<int, std::string>(aVec) 
    );

}

Calling Javascript function from server side

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:test();", true);

foreach vs someList.ForEach(){}

You could name the anonymous delegate :-)

And you can write the second as:

someList.ForEach(s => s.ToUpper())

Which I prefer, and saves a lot of typing.

As Joachim says, parallelism is easier to apply to the second form.

How to implement an STL-style iterator and avoid common pitfalls?

Here is sample of raw pointer iterator.

You shouldn't use iterator class to work with raw pointers!

#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <assert.h>

template<typename T>
class ptr_iterator
    : public std::iterator<std::forward_iterator_tag, T>
{
    typedef ptr_iterator<T>  iterator;
    pointer pos_;
public:
    ptr_iterator() : pos_(nullptr) {}
    ptr_iterator(T* v) : pos_(v) {}
    ~ptr_iterator() {}

    iterator  operator++(int) /* postfix */         { return pos_++; }
    iterator& operator++()    /* prefix */          { ++pos_; return *this; }
    reference operator* () const                    { return *pos_; }
    pointer   operator->() const                    { return pos_; }
    iterator  operator+ (difference_type v)   const { return pos_ + v; }
    bool      operator==(const iterator& rhs) const { return pos_ == rhs.pos_; }
    bool      operator!=(const iterator& rhs) const { return pos_ != rhs.pos_; }
};

template<typename T>
ptr_iterator<T> begin(T *val) { return ptr_iterator<T>(val); }


template<typename T, typename Tsize>
ptr_iterator<T> end(T *val, Tsize size) { return ptr_iterator<T>(val) + size; }

Raw pointer range based loop workaround. Please, correct me, if there is better way to make range based loop from raw pointer.

template<typename T>
class ptr_range
{
    T* begin_;
    T* end_;
public:
    ptr_range(T* ptr, size_t length) : begin_(ptr), end_(ptr + length) { assert(begin_ <= end_); }
    T* begin() const { return begin_; }
    T* end() const { return end_; }
};

template<typename T>
ptr_range<T> range(T* ptr, size_t length) { return ptr_range<T>(ptr, length); }

And simple test

void DoIteratorTest()
{
    const static size_t size = 10;
    uint8_t *data = new uint8_t[size];
    {
        // Only for iterator test
        uint8_t n = '0';
        auto first = begin(data);
        auto last = end(data, size);
        for (auto it = first; it != last; ++it)
        {
            *it = n++;
        }

        // It's prefer to use the following way:
        for (const auto& n : range(data, size))
        {
            std::cout << " char: " << static_cast<char>(n) << std::endl;
        }
    }
    {
        // Only for iterator test
        ptr_iterator<uint8_t> first(data);
        ptr_iterator<uint8_t> last(first + size);
        std::vector<uint8_t> v1(first, last);

        // It's prefer to use the following way:
        std::vector<uint8_t> v2(data, data + size);
    }
    {
        std::list<std::vector<uint8_t>> queue_;
        queue_.emplace_back(begin(data), end(data, size));
        queue_.emplace_back(data, data + size);
    }
}

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

CSS text-overflow in a table cell?

It is worked for me

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

td {
   text-overflow: ellipsis;
   white-space: nowrap;
}

How to make responsive table

To make a responsive table, you can make the width of each td 100% and insert a related heading in the td on mobile browsers (that are less 768px width.)

Here is a website that demonstrates this technique: http://www.quizexpo.com/list-of-banks-in-india/

kill -3 to get java thread dump

In the same location where the JVM's stdout is placed. If you have a Tomcat server, this will be the catalina_(date).out file.

javascript scroll event for iPhone/iPad?

Sorry for adding another answer to an old post but I usually get a scroll event very well by using this code (it works at least on 6.1)

element.addEventListener('scroll', function() {
    console.log(this.scrollTop);
});

// This is the magic, this gives me "live" scroll events
element.addEventListener('gesturechange', function() {});

And that works for me. Only thing it doesn't do is give a scroll event for the deceleration of the scroll (Once the deceleration is complete you get a final scroll event, do as you will with it.) but if you disable inertia with css by doing this

-webkit-overflow-scrolling: none;

You don't get inertia on your elements, for the body though you might have to do the classic

document.addEventListener('touchmove', function(e) {e.preventDefault();}, true);

How to get temporary folder for current user

DO NOT use this:

System.Environment.GetEnvironmentVariable("TEMP")

Environment variables can be overridden, so the TEMP variable is not necessarily the directory.

The correct way is to use System.IO.Path.GetTempPath() as in the accepted answer.

Create an instance of a class from a string

I've used this method successfully:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

You'll need to cast the returned object to your desired object type.

Check for a substring in a string in Oracle without LIKE

You can do it this way using INSTR:

SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;

INSTR returns zero if the substring is not in the string.

Out of interest, why don't you want to use like?

Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)

Open existing file, append a single line

using (StreamWriter w = File.AppendText("myFile.txt"))
{
  w.WriteLine("hello");
}

How do I call a function twice or more times consecutively?

from itertools import repeat, starmap

results = list(starmap(do, repeat((), 3)))

See the repeatfunc recipe from the itertools module that is actually much more powerful. If you need to just call the method but don't care about the return values you can use it in a for loop:

for _ in starmap(do, repeat((), 3)): pass

but that's getting ugly.

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

Vertically centering a div inside another div

You can center the div vertically and horizontally in CSS using flex;

#outerDiv{
width: 500px;
    height: 500px;
    position:relative;
    border:1px solid #000;
    margin:0 auto;
    display: flex;
    -webkit-flex-direction: row;
    flex-direction: row;
    -webkit-align-items: center;
    align-items: center;
    -webkit-justify-content: center;
    justify-content: center;

    }

#innerDiv{
    width: 284px;
    height: 290px;
    border:1px solid #eee;

}

And the second one is as following;

    #outerDiv{
        width: 500px;
        height: 500px;
        position:relative;
        border:1px solid #000;
        }

        #innerDiv{
        max-width: 300px;
        height: 200px;
        background-color: blue;
        position:absolute; 
        left:0;
        right:0;
        top:0;
        bottom:0;
        margin:auto;
        border:1px solid #000;
        border-radius:4px;
    }

And the resulting HTML:

    <div id="outerDiv">
        <div id="innerDiv"></div>
    </div>

How to add spacing between UITableViewCell

Using a bunch of different sections is not needed. The other answers use frame insets and CGRect and layers and... BLAH. Not good; use auto layout and a custom UITableViewCell. In that UITableViewCell, instead of sub viewing your content inside the contentView, make a new containerView (a UIView), subview the container view inside the contentView, then subview all your views inside the container view.

To make the spacing now, simply edit the layout margins of the container view, like so:

class CustomTableViewCell: UITableViewCell {
    let containerView = UIView()
    let imageView = UIImageView()

    required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        containerView.translatesAutoResizingMaskIntoConstraints = false
        imageView.translatesAutoResizingMaskIntoConstraints = false
        contentView.addSubview(containerView)
        containerView.addSubview(imageView)

        contentView.layoutMargins = UIEdgeInsets(top: 15, left: 3, bottom: 15, right: 3)
        containerView.layoutMargins = UIEdgeInsets(top: 15, left: 17, bottom: 15, right: 17) // It isn't really necessary unless you've got an extremely complex table view cell. Otherwise, you could just write e.g. containerView.topAnchor

        let cg = contentView.layoutMarginsGuide
        let lg = containerView.layoutMarginsGuide
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: cg.topAnchor),
            containerView.leadingAnchor.constraint(equalTo: cg.leadingAnchor),
            containerView.trailingAnchor.constraint(equalTo: cg.trailingAnchor),
            containerView.bottomAnchor.constraint(equalTo: cg.bottomAnchor),
            imageView.topAnchor.constraint(equalTo: lg.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: lg.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: lg.bottomAnchor)
        ])
    }
}

What is PostgreSQL equivalent of SYSDATE from Oracle?

You may want to use statement_timestamp(). This give the timestamp when the statement was executed. Whereas NOW() and CURRENT_TIMESTAMP give the timestamp when the transaction started.

More details in the manual

How do I get the fragment identifier (value after hash #) from a URL?

No need for jQuery

var type = window.location.hash.substr(1);

Jquery to get SelectedText from dropdown

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-3.1.0.js"></script>
    <script>
        $(function () {
            $('#selectnumber').change(function(){
                alert('.val() = ' + $('#selectnumber').val() + '  AND  html() = ' + $('#selectnumber option:selected').html() + '  AND .text() = ' + $('#selectnumber option:selected').text());
            })
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <select id="selectnumber">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
        </select>

    </div>
    </form>
</body>
</html>

Click to see Output Screen

Thanks...:)

Powershell get ipv4 address into a variable

Here is another solution:

$env:HostIP = (
    Get-NetIPConfiguration |
    Where-Object {
        $_.IPv4DefaultGateway -ne $null -and
        $_.NetAdapter.Status -ne "Disconnected"
    }
).IPv4Address.IPAddress

HTML email with Javascript

Here's what you CAN do:

You can attach (to the email) an html document that contains javascript.

Then, when the recipient opens the attachment, their web browser will facilitate the dynamic features you've implemented.

Declare an empty two-dimensional array in Javascript?

const grid = Array.from(Array(3), e => Array(4));

Array.from(arrayLike, mapfn)

mapfn is called, being passed the value undefined, returning new Array(4).

An iterator is created and the next value is repeatedly called. The value returned from next, next().value is undefined. This value, undefined, is then passed to the newly-created array's iterator. Each iteration's value is undefined, which you can see if you log it.

var grid2 = Array.from(Array(3), e => {
  console.log(e); // undefined
  return Array(4); // a new Array.
});

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I believe the critical thing here is to be consistent within the sphere of your code's visibility, i.e. as long as everyone who needs to look at/work on your code understands your naming convention then that should be fine, even if you decide to call them 'CompanyThingamabob' and 'UserDoohickey'. The first stop, if you work for a company, is to see if there is a company convention for naming. If there isn't or you don't work for a company then create your own using terms that make sense to you, pass it around a few trusted colleagues/friends who at least code casually, and incorporate any feedback that makes sense.

Applying someone else's convention, even when it's widely accepted, if it doesn't leap off the page at you is a bit of a mistake in my book. First and foremost I need to understand my code without reference to other documentation but at the same time it needs to be generic enough that it's no incomprehensible to someone else in the same field in the same industry.

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

How can I detect the encoding/codepage of a text file

10Y (!) had passed since this was asked, and still I see no mention of MS's good, non-GPL'ed solution: IMultiLanguage2 API.

Most libraries already mentioned are based on Mozilla's UDE - and it seems reasonable that browsers have already tackled similar problems. I don't know what is chrome's solution, but since IE 5.0 MS have released theirs, and it is:

  1. Free of GPL-and-the-like licensing issues,
  2. Backed and maintained probably forever,
  3. Gives rich output - all valid candidates for encoding/codepages along with confidence scores,
  4. Surprisingly easy to use (it is a single function call).

It is a native COM call, but here's some very nice work by Carsten Zeumer, that handles the interop mess for .net usage. There are some others around, but by and large this library doesn't get the attention it deserves.

Count number of 1's in binary representation

There's only one way I can think of to accomplish this task in O(1)... that is to 'cheat' and use a physical device (with linear or even parallel programming I think the limit is O(log(k)) where k represents the number of bytes of the number).

However you could very easily imagine a physical device that connects each bit an to output line with a 0/1 voltage. Then you could just electronically read of the total voltage on a 'summation' line in O(1). It would be quite easy to make this basic idea more elegant with some basic circuit elements to produce the output in whatever form you want (e.g. a binary encoded output), but the essential idea is the same and the electronic circuit would produce the correct output state in fixed time.

I imagine there are also possible quantum computing possibilities, but if we're allowed to do that, I would think a simple electronic circuit is the easier solution.

How to do an INNER JOIN on multiple columns

something like....

SELECT f.*
      ,a1.city as from
      ,a2.city as to
FROM flights f
INNER JOIN airports a1
ON f.fairport = a1. code
INNER JOIN airports a2
ON f.tairport = a2. code

How to catch a unique constraint error in a PL/SQL block?

I suspect the condition you are looking for is DUP_VAL_ON_INDEX

EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')

MySQL count occurrences greater than 2

The HAVING option can be used for this purpose and query should be

SELECT word, COUNT(*) FROM words 
GROUP BY word
HAVING COUNT(*) > 1;

Set the location in iPhone Simulator

in iOS Simulator menu, go to Debug -> Location -> Custom Location. There you can set the latitude and longitude and test the app accordingly. This works with mapkit and also with CLLocationManager.

How to remove the first and the last character of a string

You can do something like that :

"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')

This regex is a common way to have the same behaviour of the trim function used in many languages.

A possible implementation of trim function is :

function trim(string, char){
    if(!char) char = ' '; //space by default
    char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
    var regex_1 = new RegExp("^" + char + "+", "g");
    var regex_2 = new RegExp(char + "+$", "g");
    return string.replace(regex_1, '').replace(regex_2, '');
}

Which will delete all / at the beginning and the end of the string. It handles cases like ///installers/services///

You can also simply do :

"/installers/".substring(1, string.length-1);

GridLayout (not GridView) how to stretch all children evenly

i have same problem and i think just set width and height programmatically :

set width of button's with metrics.widthPixels / 2 metrics is object of DisplayMetrics.

 GridLayout gridLayout=findViewById(R.id.grid);
    for (int i = 0; i <gridLayout.getChildCount() ; i++) {
        View view= gridLayout.getChildAt(i);
        if(view instanceof Button){
            Button btn = (Button) view;
            btn.setWidth(200);//metrics.widthPixels / 2
            btn.setHeight(200);//metrics.heightPixels / 7
        }
    } 

Connect with SSH through a proxy

$ which nc
/bin/nc

$ rpm -qf /bin/nc
nmap-ncat-7.40-7.fc26.x86_64

$ ssh -o "ProxyCommand nc --proxy <addr[:port]> %h %p" USER@HOST

$ ssh -o "ProxyCommand nc --proxy <addr[:port]> --proxy-type <type> --proxy-auth <auth> %h %p" USER@HOST

Getting command-line password input in Python

Use getpass.getpass():

from getpass import getpass
password = getpass()

An optional prompt can be passed as parameter; the default is "Password: ".

Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

Try running fuser command

[root@guest2 ~]# fuser -mv /home

USER PID ACCESS COMMAND

/home: root 2919 f.... automount

[root@guest2 ~]# kill -9 2919

autofs service is known to cause this issue.

You can use command

#service autofs stop

And try again.

How do I write a correct micro-benchmark in Java?

If you are trying to compare two algorithms, do at least two benchmarks for each, alternating the order. i.e.:

for(i=1..n)
  alg1();
for(i=1..n)
  alg2();
for(i=1..n)
  alg2();
for(i=1..n)
  alg1();

I have found some noticeable differences (5-10% sometimes) in the runtime of the same algorithm in different passes..

Also, make sure that n is very large, so that the runtime of each loop is at the very least 10 seconds or so. The more iterations, the more significant figures in your benchmark time and the more reliable that data is.

Convert string to datetime

DateTime.strptime allows you to specify the format and convert a String to a DateTime.

In Javascript/jQuery what does (e) mean?

In that example, e is just a parameter for that function, but it's the event object that gets passed in through it.

How do I REALLY reset the Visual Studio window layout?

If you have an old backup copy of CurrentSettings.vssettings, you can try restoring it.

I had a completely corrupted Visual Studio layout. When I tried to enter debug, I was told that VS had become unstable. When I restarted, my window layout would then be totally screwed. I tried restoring the VS current user settings in the registry from a backup, but that didn't help. However, restoring CurrentSettings.vssettings seems to have cured it.

There seems to be a bunch of binary stuff in there and I can imagine it gets irretrievably corrupted sometimes.

Time part of a DateTime Field in SQL

"For my project, I have to return data that has a timestamp of 5pm of a DateTime field, No matter what the date is."

So I think what you meant was that you needed the date, not the time. You can do something like this to get a date with 5:00 as the time:

SELECT CONVERT(VARCHAR(10), GetDate(), 110) + ' 05:00:00'

Remove an item from a dictionary when its key is unknown

There is nothing wrong with deleting items from the dictionary while iterating, as you've proposed. Be careful about multiple threads using the same dictionary at the same time, which may result in a KeyError or other problems.

Of course, see the docs at http://docs.python.org/library/stdtypes.html#typesmapping

HTML5 Video not working in IE 11

What is the resolution of the video? I had a similar problem with IE11 in Win7. The Microsoft H.264 decoder supports only 1920x1088 pixels in Windows 7. See my story: http://lars.st0ne.at/blog/html5+video+in+IE11+-+size+does+matter

Nginx serves .php files as downloads, instead of executing them

The answer above seemed to comment out too much for the solution I reached. This is what my file looked like:

/etc/nginx/sites-available/default

location ~ \.php$ {
# fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}

Hope this helps some folks who are frustrated on a sunday afternoon (c:

jquery loop on Json data using $.each

getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

XSLT - How to select XML Attribute by Attribute?

There are two problems with your xpath - first you need to remove the child selector from after Data like phihag mentioned. Also you forgot to include root in your xpath. Here is what you want to do:

select="/root/DataSet/Data[@Value1='2']/@Value2"

How to convert a byte array to its numeric value (Java)?

public static long byteArrayToLong(byte[] bytes) {
    return ((long) (bytes[0]) << 56)
            + (((long) bytes[1] & 0xFF) << 48)
            + ((long) (bytes[2] & 0xFF) << 40)
            + ((long) (bytes[3] & 0xFF) << 32)
            + ((long) (bytes[4] & 0xFF) << 24)
            + ((bytes[5] & 0xFF) << 16)
            + ((bytes[6] & 0xFF) << 8)
            + (bytes[7] & 0xFF);
}

convert bytes array (long is 8 bytes) to long

Drop shadow for PNG image in CSS

You can't do this reliably across all browsers. Microsoft no longer supports DX filters as of IE10+, so none of the solutions here work fully:

https://msdn.microsoft.com/en-us/library/hh801215(v=vs.85).aspx

The only property that works reliably across all browsers is box-shadow, and this just puts the border on your element (e.g. a div), resulting in a square border:

box-shadow: horizontalOffset verticalOffset blurDistance spreadDistance color inset;

e.g.

box-shadow: -2px 6px 12px 6px #CCCED0;

If you happen to have an image that is 'square' but with uniform rounded corners, the drop shadow works with border-radius, so you could always emulate the rounded corners of your image in your div.

Here's the Microsoft documentation for box-shadow:

https://msdn.microsoft.com/en-us/library/gg589484(v=vs.85).aspx

How to line-break from css, without using <br />?

For a List of Links

The other answers provide some good ways of adding line breaks, depending on the situation. But it should be noted that the :after selector is one of the better ways to do this for CSS control over lists of links (and similar things), for reasons noted below.

Here's an example, assuming a table of contents:

<style type="text/css">
    .toc a:after{ content: "\a"; white-space: pre; }
</style>

<span class="toc">
    <a href="#a1">Item A1</a> <a href="#a2">Item A2</a>
    <a href="#b1">Item B1</a> <a href="#b2">Item B2</a>
</span>

And here's Simon_Weaver's technique, which is simpler and more compatible. It doesn't separate style and content as much, requires more code, and there may be cases where you want to add breaks after the fact. Still a great solution though, especially for older IE.

<style type="text/css">
    .toc br{ display: none; } /* comment out for horizontal links */
</style>

<span class="toc">
    <a href="#a1">Item A1</a><br/> <a href="#a2">Item A2</a><br/>
    <a href="#b1">Item B1</a><br/> <a href="#b2">Item B2</a><br/>
</span>

Note the advantages of the above solutions:

  • No matter the whitespace in the HTML, the output is the same (vs. pre)
  • No extra padding is added to the elements (see NickG's display:block comments)
  • You can easily switch between horizontal and vertical lists of links with some shared CSS without going into every HTML file for a style change
  • No float or clear styles affecting surrounding content
  • The style is separate from the content (vs. <br/>, or pre with hard-coded breaks)
  • This can also work for loose links using a.toc:after and <a class="toc">
  • You can add multiple breaks and even prefix/suffix text

How do I make a WPF TextBlock show my text on multiple lines?

Nesting a stackpanel will cause the textbox to wrap properly:

<Viewbox Margin="120,0,120,0">
    <StackPanel Orientation="Vertical" Width="400">
        <TextBlock x:Name="subHeaderText" 
                   FontSize="20" 
                   TextWrapping="Wrap" 
                   Foreground="Black"
                   Text="Lorem ipsum dolor, lorem isum dolor,Lorem ipsum dolor sit amet, lorem ipsum dolor sit amet " />
    </StackPanel>
</Viewbox>

Java: Unresolved compilation problem

you just try to clean maven by command

mvn clean

and after that following command

mvn eclipse:clean eclipse:eclipse

and rebuild your project....

Downloading images with node.js

Building on the above, if anyone needs to handle errors in the write/read streams, I used this version. Note the stream.read() in case of a write error, it's required so we can finish reading and trigger close on the read stream.

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    if (err) callback(err, filename);
    else {
        var stream = request(uri);
        stream.pipe(
            fs.createWriteStream(filename)
                .on('error', function(err){
                    callback(error, filename);
                    stream.read();
                })
            )
        .on('close', function() {
            callback(null, filename);
        });
    }
  });
};

Does JavaScript have the interface type (such as Java's 'interface')?

You need interfaces in Java since it is statically typed and the contract between classes should be known during compilation. In JavaScript it is different. JavaScript is dynamically typed; it means that when you get the object you can just check if it has a specific method and call it.

TypeError: tuple indices must be integers, not str

Just adding a parameter like the below worked for me.

cursor=conn.cursor(dictionary=True)

I hope this would be helpful either.

IE7 Z-Index Layering Issues

I encountered this issue, but on a large project where HTML changes had to be requested and became a whole issue, so I was looking for a pure css solution.

By placing position:relative; z-index:-1 on my main body content my header drop down content suddenly displayed above the body content in ie7 (it was already displaying without issue in all other browsers and in ie8+)

The problem with that was then this disabled all hover and click actions on all content in the element with the z-index:-1 so i went to the parent element of the whole page and gave it a position:relative; z-index:1

Which fixed the issue and retained the correct layering functionality.

Feels a bit hacky, but worked as required.

Web colors in an Android color xml resource file

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="Black">#FF000000</color>   
<color name="Black_overlay">#66000000</color>

<color name="Black_transparent_black_hex_1">#11000000</color>
<color name="Black_transparent_black_hex_10">#aa000000</color>
<color name="Black_transparent_black_hex_11">#bb000000</color>
<color name="Black_transparent_black_hex_12">#cc000000</color>
<color name="Black_transparent_black_hex_13">#dd000000</color>
<color name="Black_transparent_black_hex_14">#ee000000</color>
<color name="Black_transparent_black_hex_15">#ff000000</color>
<color name="Black_transparent_black_hex_2">#22000000</color>
<color name="Black_transparent_black_hex_3">#33000000</color>
<color name="Black_transparent_black_hex_4">#44000000</color>
<color name="Black_transparent_black_hex_5">#55000000</color>
<color name="Black_transparent_black_hex_6">#66000000</color>
<color name="Black_transparent_black_hex_7">#77000000</color>
<color name="Black_transparent_black_hex_8">#88000000</color>
<color name="Black_transparent_black_hex_9">#99000000</color>

<color name="Black_transparent_black_percent_10">#1A000000</color>
<color name="Black_transparent_black_percent_15">#26000000</color>
<color name="Black_transparent_black_percent_20">#33000000</color>
<color name="Black_transparent_black_percent_25">#40000000</color>
<color name="Black_transparent_black_percent_30">#4D000000</color>
<color name="Black_transparent_black_percent_35">#59000000</color>
<color name="Black_transparent_black_percent_40">#66000000</color>
<color name="Black_transparent_black_percent_45">#73000000</color>
<color name="Black_transparent_black_percent_5">#0D000000</color>
<color name="Black_transparent_black_percent_50">#80000000</color>
<color name="Black_transparent_black_percent_55">#8C000000</color>
<color name="Black_transparent_black_percent_60">#99000000</color>
<color name="Black_transparent_black_percent_65">#A6000000</color>
<color name="Black_transparent_black_percent_70">#B3000000</color>
<color name="Black_transparent_black_percent_75">#BF000000</color>
<color name="Black_transparent_black_percent_80">#CC000000</color>
<color name="Black_transparent_black_percent_85">#D9000000</color>
<color name="Black_transparent_black_percent_90">#E6000000</color>
<color name="Black_transparent_black_percent_95">#F2000000</color>

 <color name="BlanchedAlmond">#FFEBCD</color>
 <color name="Blue_AliceBlue">#F0F8FF</color>
 <color name="Blue_Aqua">#00FFFF</color>
 <color name="Blue_Aquamarine">#7FFFD4</color>
 <color name="Blue">#0000FF</color>
 <color name="Blue_BlueNavy">#000080</color>
 <color name="Blue_BlueViolet">#8A2BE2</color>
 <color name="Blue_CadetBlue">#5F9EA0</color>
 <color name="Blue_CornflowerBlue">#6495ED</color>
 <color name="Blue_DarkBlue">#00008B</color>
 <color name="Blue_DarkSlateBlue">#483D8B</color>
 <color name="Blue_DeepSkyBlue">#00BFFF</color>
 <color name="Blue_DodgerBlue">#1E90FF</color>
 <color name="Blue_Lavender">#E6E6FA</color>
 <color name="Blue_LavenderBlush">#FFF0F5</color>
 <color name="Blue_LightBlue">#ADD8E6</color>
 <color name="Blue_LightSkyBlue">#87CEFA</color>
 <color name="Blue_LightSteelBlue">#B0C4DE</color>
 <color name="Blue_MediumBlue">#0000CD</color>
 <color name="Blue_MediumSlateBlue">#7B68EE</color>
 <color name="Blue_MidnightBlue">#191970</color>
 <color name="Blue_Navy">#000080</color>
 <color name="Blue_PowderBlue">#B0E0E6</color>
 <color name="Blue_RoyalBlue">#4169E1</color>
 <color name="Blue_SkyBlue">#87CEEB</color>
 <color name="Blue_SlateBlue">#6A5ACD</color>
 <color name="Blue_SteelBlue">#4682B4</color>

 <color name="Brown">#A52A2A</color>
 <color name="Brown_BurlyWood">#DEB887</color>
 <color name="Brown_Chocolate">#D2691E</color>
 <color name="Brown_DarkKhaki">#BDB76B</color>
 <color name="Brown_RosyBrown">#BC8F8F</color>
 <color name="Brown_SandyBrown">#F4A460</color>

 <color name="Chartreuse">#7FFF00</color>
 <color name="Coral">#FF7F50</color>
 <color name="Cornsilk">#FFF8DC</color>
 <color name="Cyan">#00FFFF</color>
 <color name="DarkMagenta">#8B008B</color>
 <color name="DarkOrchid">#9932CC</color>
 <color name="DarkSalmon">#E9967A</color>
 <color name="DarkTurquoise">#00CED1</color>
 <color name="DarkViolet">#9400D3</color>
 <color name="Fuchsia">#FF00FF</color>
 <color name="Gainsboro">#DCDCDC</color>

 <color name="Gray">#808080</color>
 <color name="Gray_DarkGray1">#A9A9A9</color>
 <color name="Gray_DarkGray">#2F4F4F</color>
 <color name="Gray_DimGray">#696969</color>
 <color name="Gray_LightGray">#D3D3D3</color>
 <color name="Gray_LightSlateGray">#778899</color>
 <color name="Gray_SlateGray">#708090</color>

 <color name="Green">#008000</color>
 <color name="Green_DarkGreen">#006400</color>
 <color name="Green_DarkOliveGreen">#556B2F</color>
 <color name="Green_DarkSeaGreen">#8FBC8F</color>
 <color name="Green_ForestGreen">#228B22</color>
 <color name="Green_GreenYellow">#ADFF2F</color>
 <color name="Green_LawnGreen">#7CFC00</color>
 <color name="Green_LightGreen">#90EE90</color>
 <color name="Green_LightSeaGreen">#20B2AA</color>
 <color name="Green_LimeGreen">#32CD32</color>
 <color name="Green_MediumSeaGreen">#3CB371</color>
 <color name="Green_MediumSpringGreen">#00FA9A</color>
 <color name="Green_PaleGreen">#98FB98</color>
 <color name="Green_SeaGreen">#2E8B57</color>
 <color name="Green_SpringGreen">#00FF7F</color>
 <color name="Green_YellowGreen">#9ACD32</color>

 <color name="Indigo">#4B0082</color>
 <color name="Khaki">#F0E68C</color>
 <color name="LemonChiffon">#FFFACD</color>
 <color name="LightCoral">#F08080</color>
 <color name="LightGoldenrodYellow">#FAFAD2</color>
 <color name="LightSalmon">#FFA07A</color>
 <color name="Lime">#00FF00</color>
 <color name="Linen">#FAF0E6</color>
 <color name="Magenta">#FF00FF</color>
 <color name="Maroon">#800000</color>
 <color name="MediumAquamarine">#66CDAA</color>
 <color name="MediumOrchid">#BA55D3</color>
 <color name="MediumPurple">#9370DB</color>
 <color name="MediumTurquoise">#48D1CC</color>
 <color name="MintCream">#F5FFFA</color>
 <color name="Moccasin">#FFE4B5</color>
 <color name="OldLace">#FDF5E6</color>
 <color name="Olive">#808000</color>
 <color name="OliveDrab">#6B8E23</color>

 <color name="Orange">#FFA500</color>
 <color name="Orange_DarkOrange">#FF8C00</color>
 <color name="Orchid">#DA70D6</color>
 <color name="PaleTurquoise">#AFEEEE</color>
 <color name="PapayaWhip">#FFEFD5</color>
 <color name="PeachPuff">#FFDAB9</color>
 <color name="Peru">#CD853F</color>

 <color name="Pink">#FFC0CB</color>
 <color name="Pink_DeepPink">#FF1493</color>
 <color name="Pink_HotPink">#FF69B4</color>
 <color name="Pink_LightPink">#FFB6C1</color>

 <color name="Plum">#DDA0DD</color>
 <color name="Purple">#800080</color>

 <color name="Red">#FF0000</color>
 <color name="Red_Crimson">#DC143C</color>
 <color name="Red_DarkCyan">#008B8B</color>
 <color name="Red_DarkRed">#8B0000</color>
 <color name="Red_FireBrick">#B22222</color>
 <color name="Red_IndianRed">#CD5C5C</color>
 <color name="Red_LightCyan">#E0FFFF</color>
 <color name="Red_MediumVioletRed">#C71585</color>
 <color name="Red_MistyRose">#FFE4E1</color>
 <color name="Red_OrangeRed">#FF4500</color>
 <color name="Red_PaleVioletRed">#DB7093</color>
 <color name="Red_Tomato">#FF6347</color>

 <color name="SaddleBrown">#8B4513</color>
 <color name="Salmon">#FA8072</color>
 <color name="Seashell">#FFF5EE</color>
 <color name="Sienna">#A0522D</color>
 <color name="Silver">#C0C0C0</color>
 <color name="Tan">#D2B48C</color>
 <color name="Thistle">#D8BFD8</color>
 <color name="Turquoise">#40E0D0</color>
 <color name="Violet">#EE82EE</color>

 <color name="White_AntiqueWhite">#FAEBD7</color>
 <color name="White_Azure">#F0FFFF</color>
 <color name="White_Beige">#F5F5DC</color>
 <color name="White_Bisque">#FFE4C4</color>
 <color name="White_FloralWhite">#FFFAF0</color>
 <color name="White_GhostWhite">#F8F8FF</color>
 <color name="White_Honeydew">#F0FFF0</color>
 <color name="White_Ivory">#FFFFF0</color>
 <color name="White_NavajoWhite">#FFDEAD</color>
 <color name="White_Snow">#FFFAFA</color>
 <color name="White_Teal">#008080</color>

<color name="White_transparent_white_hex_1">#11ffffff</color>
<color name="White_transparent_white_hex_10">#aaffffff</color>
<color name="White_transparent_white_hex_11">#bbffffff</color>
<color name="White_transparent_white_hex_12">#ccffffff</color>
<color name="White_transparent_white_hex_13">#ddffffff</color>
<color name="White_transparent_white_hex_14">#eeffffff</color>
<color name="White_transparent_white_hex_15">#ffffffff</color>
<color name="White_transparent_white_hex_2">#22ffffff</color>
<color name="White_transparent_white_hex_3">#33ffffff</color>
<color name="White_transparent_white_hex_4">#44ffffff</color>
<color name="White_transparent_white_hex_5">#55ffffff</color>
<color name="White_transparent_white_hex_6">#66ffffff</color>
<color name="White_transparent_white_hex_7">#77ffffff</color>
<color name="White_transparent_white_hex_8">#88ffffff</color>
<color name="White_transparent_white_hex_9">#99ffffff</color>

<color name="White_transparent_white_percent_10">#1Affffff</color>
<color name="White_transparent_white_percent_15">#26ffffff</color>
<color name="White_transparent_white_percent_20">#33ffffff</color>
<color name="White_transparent_white_percent_25">#40ffffff</color>
<color name="White_transparent_white_percent_30">#4Dffffff</color>
<color name="White_transparent_white_percent_35">#59ffffff</color>
<color name="White_transparent_white_percent_40">#66ffffff</color>
<color name="White_transparent_white_percent_45">#73ffffff</color>
<color name="White_transparent_white_percent_5">#0Dffffff</color>
<color name="White_transparent_white_percent_50">#80ffffff</color>
<color name="White_transparent_white_percent_55">#8Cffffff</color>
<color name="White_transparent_white_percent_60">#99ffffff</color>
<color name="White_transparent_white_percent_65">#A6ffffff</color>
<color name="White_transparent_white_percent_70">#B3ffffff</color>
<color name="White_transparent_white_percent_75">#BFffffff</color>
<color name="White_transparent_white_percent_80">#CCffffff</color>
<color name="White_transparent_white_percent_85">#D9ffffff</color>
<color name="White_transparent_white_percent_90">#E6ffffff</color>
<color name="White_transparent_white_percent_95">#F2ffffff</color>

 <color name="White_Wheat">#F5DEB3</color>
 <color name="White_White">#FFFFFF</color>
 <color name="White_WhiteSmoke">#F5F5F5</color>

 <color name="Yellow">#FFFF00</color>
 <color name="Yellow_DarkGoldenrod">#B8860B</color>
 <color name="Yellow_Gold">#FFD700</color>
 <color name="Yellow_GoldenRod">#DAA520</color>
 <color name="Yellow_LightYellow">#FFFFE0</color>
 <color name="Yellow_PaleGoldenrod">#EEE8AA</color>

How to create a file with a given size in Linux?

This will generate 4 MB text file with random characters in current directory and its name "4mb.txt" You can change parameters to generate different sizes and names.

base64 /dev/urandom | head -c 4000000 > 4mb.txt

Signed to unsigned conversion in C - is it always safe?

Horrible Answers Galore

Ozgur Ozcitak

When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.

This is completely wrong.

Mats Fredriksson

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.

smh

Your addition operation causes the int to be converted to an unsigned int.

Wrong. Maybe it does and maybe it doesn't.

Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)

Wrong. It is either undefined behavior if it causes overflow or the value is preserved.

Anonymous

The value of i is converted to unsigned int ...

Wrong. Depends on the precision of an int relative to an unsigned int.

Taylor Price

As was previously answered, you can cast back and forth between signed and unsigned without a problem.

Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.

Now I can finally answer the question.

Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.

Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.

What is precision?

Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.

[Gotchas]

The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.

[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.

What exactly is \r in C language?

It's Carriage Return. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx

The following repeats the loop until the user has pressed the Return key.

while(ch!='\r')
{
  ch=getche();
}

ValueError when checking if variable is None or numpy.array

Using not a to test whether a is None assumes that the other possible values of a have a truth value of True. However, most NumPy arrays don't have a truth value at all, and not cannot be applied to them.

If you want to test whether an object is None, the most general, reliable way is to literally use an is check against None:

if a is None:
    ...
else:
    ...

This doesn't depend on objects having a truth value, so it works with NumPy arrays.

Note that the test has to be is, not ==. is is an object identity test. == is whatever the arguments say it is, and NumPy arrays say it's a broadcasted elementwise equality comparison, producing a boolean array:

>>> a = numpy.arange(5)
>>> a == None
array([False, False, False, False, False])
>>> if a == None:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous.
 Use a.any() or a.all()

On the other side of things, if you want to test whether an object is a NumPy array, you can test its type:

# Careful - the type is np.ndarray, not np.array. np.array is a factory function.
if type(a) is np.ndarray:
    ...
else:
    ...

You can also use isinstance, which will also return True for subclasses of that type (if that is what you want). Considering how terrible and incompatible np.matrix is, you may not actually want this:

# Again, ndarray, not array, because array is a factory function.
if isinstance(a, np.ndarray):
    ...
else:
    ...    

Get file name from URI string in C#

Most other answers are either incomplete or don't deal with stuff coming after the path (query string/hash).

readonly static Uri SomeBaseUri = new Uri("http://canbeanything");

static string GetFileNameFromUrl(string url)
{
    Uri uri;
    if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
        uri = new Uri(SomeBaseUri, url);

    return Path.GetFileName(uri.LocalPath);
}

Test results:

GetFileNameFromUrl("");                                         // ""
GetFileNameFromUrl("test");                                     // "test"
GetFileNameFromUrl("test.xml");                                 // "test.xml"
GetFileNameFromUrl("/test.xml");                                // "test.xml"
GetFileNameFromUrl("/test.xml?q=1");                            // "test.xml"
GetFileNameFromUrl("/test.xml?q=1&x=3");                        // "test.xml"
GetFileNameFromUrl("test.xml?q=1&x=3");                         // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3");        // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3#aidjsf"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/a/b/c/d");                 // "d"
GetFileNameFromUrl("http://www.a.com/a/b/c/d/e/");              // ""

How do I interpret precision and scale of a number in a database?

Precision, Scale, and Length in the SQL Server 2000 documentation reads:

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.

Merge some list items in a Python List

my telepathic abilities are not particularly great, but here is what I think you want:

def merge(list_of_strings, indices):
    list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
    list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
    return list_of_strings

I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.

Detect if range is empty

Found a solution from the comments I got.

Sub TestIsEmpty()
    If WorksheetFunction.CountA(Range("A38:P38")) = 0 Then
        MsgBox "Empty"
    Else
        MsgBox "Not Empty"
    End If
End Sub

Fullscreen Activity in Android?

Just paste this code into onCreate() method

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

how to change a selections options based on another select option selected?

Here is an example of what you are trying to do => fiddle

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $("#type").change(function () {_x000D_
        var val = $(this).val();_x000D_
        if (val == "item1") {_x000D_
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
        } else if (val == "item2") {_x000D_
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
        } else if (val == "item3") {_x000D_
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
        } else if (val == "item0") {_x000D_
            $("#size").html("<option value=''>--select one--</option>");_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
    <option value="item0">--Select an Item--</option>_x000D_
    <option value="item1">item1</option>_x000D_
    <option value="item2">item2</option>_x000D_
    <option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
    <option value="">-- select one -- </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Programmatically obtain the phone number of the Android phone

A little contribution. In my case, the code launched an error exception. I have needed put an annotation that for the code be run and fix that problem. Here I let this code.

public static String getLineNumberPhone(Context scenario) {
    TelephonyManager tMgr = (TelephonyManager) scenario.getSystemService(Context.TELEPHONY_SERVICE);
    @SuppressLint("MissingPermission") String mPhoneNumber = tMgr.getLine1Number();
    return mPhoneNumber;
}

Cross-browser bookmark/add to favorites JavaScript

function bookmark(title, url) {
  if (window.sidebar) { 
    // Firefox
    window.sidebar.addPanel(title, url, '');
  } 
  else if (window.opera && window.print) 
  { 
    // Opera
    var elem = document.createElement('a');
    elem.setAttribute('href', url);
    elem.setAttribute('title', title);
    elem.setAttribute('rel', 'sidebar');
    elem.click(); //this.title=document.title;
  } 
  else if (document.all) 
  { 
    // ie
    window.external.AddFavorite(url, title);
  }
}

I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!

What are libtool's .la file for?

It is a textual file that includes a description of the library.

It allows libtool to create platform-independent names.

For example, libfoo goes to:

Under Linux:

/lib/libfoo.so       # Symlink to shared object
/lib/libfoo.so.1     # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library

Under Cygwin:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # libtool library
/bin/cygfoo_1.dll    # DLL

Under Windows MinGW:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library
/bin/foo_1.dll       # DLL

So libfoo.la is the only file that is preserved between platforms by libtool allowing to understand what happens with:

  • Library dependencies
  • Actual file names
  • Library version and revision

Without depending on a specific platform implementation of libraries.

ASP.NET postback with JavaScript

Per Phairoh: Use this in the Page/Component just in case the panel name changes

<script type="text/javascript">
     <!--
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');
         }
     -->
     </script>

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

Could you explain STA and MTA?

The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of its runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

Elegant way to read file into byte[] array in Java

A long time ago:

Call any of these

byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

From

http://commons.apache.org/io/

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

Today (Java 7+ or Android API Level 26+)

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

Import existing source code to GitHub

Here are some instructions on how to initiate a GitHub repository and then push code you've already created to it. The first set of instructions are directly from GitHub.

Source: https://help.github.com/articles/create-a-repo/

  1. In the upper-right corner of any page, click, and then click New repository.

  2. Create a short, memorable name for your repository. For example, "hello-world".

  3. Optionally, add a description of your repository. For example, "My first repository on GitHub."

  4. Choose between creating a public or private repository.

  5. Initialize this repository with a README.

  6. Create repository.

Congratulations! You've successfully created your first repository, and initialized it with a README file.

Now after these steps you will want to push the code on your local computer up to the repository you just created and you do this following these steps:

  1. git init (in the root folder where your code is located)

  2. git add -A (this will add all the files and folders in your directory to be committed)

  3. git commit -am "First Project commit"

  4. git remote add origin [email protected]:YourGithubName/your-repo-name.git (you'll find this address on the GitHub repository you just created under "ssh clone URL" on the main page)

  5. git push -u origin master

That's it. Your code will now be pushed up to GitHub. Now every time you want to keep pushing code that has changed just do.

  1. git commit -m "New changes"

  2. git push origin master (if master is the branch you are working on)

How can I monitor the thread count of a process on linux?

ps -eLf on the shell shall give you a list of all the threads and processes currently running on the system. Or, you can run top command then hit 'H' to toggle thread listings.

How to take input in an array + PYTHON?

arr = []
elem = int(raw_input("insert how many elements you want:"))
for i in range(0, elem):
    arr.append(int(raw_input("Enter next no :")))
print arr

You must enable the openssl extension to download files via https

You need to enable "extension=php_openssl.dll" in both files (php and apache). my pc files path are these :

  1. C:\wamp\bin\php\php5.3.13\php.ini

  2. C:\wamp\bin\apache\apache2.2.22\bin\php.ini

How to add a new project to Github using VS Code

There is a nice GUI way to do this. Press CTRL+SHIFT+G ( or View-CSM in menu) and here you have a lot of options. With (...) you can do almost anything you want. After things be done, type your commit message into input box and press CTRL+ENTER. Pretty easy. If you have remote repo - you'll see a little spinner mark in bottom left corner near repo name. Press it and sync to remote easily.
But in order to do all of this you must have repo to be initialized in your working directory before (git init from terminal).

How can I programmatically generate keypress events in C#?

I've not used it, but SendKeys may do what you want.

Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.

System.Windows.Forms.SendKeys.Send("A");
System.Windows.Forms.SendKeys.Send("{ENTER}");

Microsoft has some more usage examples here.

Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.

How to convert Set<String> to String[]?

Guava style:

Set<String> myset = myMap.keySet();
FluentIterable.from(mySet).toArray(String.class);

more info: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/FluentIterable.html

Update OpenSSL on OS X with Homebrew

  1. install port: https://guide.macports.org/
  2. install or upgrade openssl package: sudo port install openssl or sudo port upgrade openssl
  3. that's it, run openssl version to see the result.

How to parse JSON and access results

Try:

$result = curl_exec($cURL);
$result = json_decode($result,true);

Now you can access MessageID from $result['MessageID'].

As for the database, it's simply using a query like so:

INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');

Prepared.

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

How to get post slug from post in WordPress?

use global variable $post

<?php 
    global $post;
    $post_slug=$post->post_name;
?>

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you could.

  • A null pointer is converted to false implicitly
  • a non-null pointer is converted to true.

This is part of the C++ standard conversion, which falls in Boolean conversion clause:

§ 4.12 Boolean conversions

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

How to compare two maps by their values

If you assume that there can be duplicate values the only way to do this is to put the values in lists, sort them and compare the lists viz:

List<String> values1 = new ArrayList<String>(map1.values());
List<String> values2 = new ArrayList<String>(map2.values());
Collections.sort(values1);
Collections.sort(values2);
boolean mapsHaveEqualValues = values1.equals(values2);

If values cannot contain duplicate values then you can either do the above without the sort using sets.

What MIME type should I use for CSV?

My users are allowed to upload CSV files and text/csv and application/csv did not appear by now. These are the ones identified through finfo():

text/plain
text/x-csv

And these are the ones transmitted through the browser:

text/plain
application/vnd.ms-excel
text/x-csv

The following types did not appear, but could:

application/csv
application/x-csv
text/csv
text/comma-separated-values
text/x-comma-separated-values
text/tab-separated-values

Reverse colormap in matplotlib

There is no built-in way (yet) of reversing arbitrary colormaps, but one simple solution is to actually not modify the colorbar but to create an inverting Normalize object:

from matplotlib.colors import Normalize

class InvertedNormalize(Normalize):
    def __call__(self, *args, **kwargs):
        return 1 - super(InvertedNormalize, self).__call__(*args, **kwargs)

You can then use this with plot_surface and other Matplotlib plotting functions by doing e.g.

inverted_norm = InvertedNormalize(vmin=10, vmax=100)
ax.plot_surface(..., cmap=<your colormap>, norm=inverted_norm)

This will work with any Matplotlib colormap.

Are there bookmarks in Visual Studio Code?

You need to do this via an extension as of the version 1.8.1.

  1. Go to View ? Extensions. This will open Extensions Panel.

  2. Type bookmark to list all related extensions.

  3. Install


I personally like "Numbered Bookmarks" - it is pretty simple and powerful.

Go to the line you need to create a bookmark.

Click Ctrl + Shift + [some number]

Ex: Ctrl + Shift + 2

Now you can jump to this line from anywhere by pressing Ctrl + number

Ex: Ctrl + 2

validate natural input number with ngpattern

<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone  required  name='strMobileNo' ng-model="formModel.strMobileNo" type="text"  placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>

the following code will help for phone number validation and the respected directive is

app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = PHONE_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

What is the difference between MySQL, MySQLi and PDO?

There are (more than) three popular ways to use MySQL from PHP. This outlines some features/differences PHP: Choosing an API:

  1. (DEPRECATED) The mysql functions are procedural and use manual escaping.
  2. MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements.
  3. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.

I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.

Maintaining the final state at end of a CSS3 animation

Use animation-fill-mode: forwards;

animation-fill-mode: forwards;

The element will retain the style values that is set by the last keyframe (depends on animation-direction and animation-iteration-count).

Note: The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.

Working example

_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position :relative;_x000D_
  -webkit-animation: mymove 3ss forwards; /* Safari 4.0 - 8.0 */_x000D_
  animation: bubble 3s forwards;_x000D_
  /* animation-name: bubble; _x000D_
  animation-duration: 3s;_x000D_
  animation-fill-mode: forwards; */_x000D_
}_x000D_
_x000D_
/* Safari */_x000D_
@-webkit-keyframes bubble  {_x000D_
  0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}_x000D_
_x000D_
/* Standard syntax */_x000D_
@keyframes bubble  {_x000D_
   0%   { transform:scale(0.5); opacity:0.0; left:0}_x000D_
    50%  { transform:scale(1.2); opacity:0.5; left:100px}_x000D_
    100% { transform:scale(1.0); opacity:1.0; left:200px}_x000D_
}
_x000D_
<h1>The keyframes </h1>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How do I resolve "Cannot find module" error using Node.js?

Removing node/npm and then re-installing the stable(not the latest) version worked for me.

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

https://nodejs.org/en/download/

How do emulators work and how are they written?

Emulator are very hard to create since there are many hacks (as in unusual effects), timing issues, etc that you need to simulate.

For an example of this, see http://queue.acm.org/detail.cfm?id=1755886.

That will also show you why you ‘need’ a multi-GHz CPU for emulating a 1MHz one.

How can I count the number of elements of a given value in a matrix?

this would be perfect cause we are doing operation on matrix, and the answer should be a single number

sum(sum(matrix==value))

animating addClass/removeClass with jQuery

I was looking into this but wanted to have a different transition rate for in and out.

This is what I ended up doing:

//css
.addedClass {
    background: #5eb4fc;
}

// js
function setParentTransition(id, prop, delay, style, callback) {
    $(id).css({'-webkit-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'-moz-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'-o-transition' : prop + ' ' + delay + ' ' + style});
    $(id).css({'transition' : prop + ' ' + delay + ' ' + style});
    callback();
}
setParentTransition(id, 'background', '0s', 'ease', function() {
    $('#elementID').addClass('addedClass');
});

setTimeout(function() {
    setParentTransition(id, 'background', '2s', 'ease', function() {
        $('#elementID').removeClass('addedClass');
    });
});

This instantly turns the background color to #5eb4fc and then slowly fades back to normal over 2 seconds.

Here's a fiddle

How to use `replace` of directive definition?

Also i got this error if i had the comment in tn top level of template among with the actual root element.

<!-- Just a commented out stuff -->
<div>test of {{value}}</div>

What's the difference between a 302 and a 307 redirect?

EXPECTED for 302: redirect uses same request method POST on NEW_URL

CLIENT POST OLD_URL -> SERVER 302 NEW_URL -> CLIENT POST NEW_URL

ACTUAL for 302, 303: redirect changes request method from POST to GET on NEW_URL

CLIENT POST OLD_URL -> SERVER 302 NEW_URL -> CLIENT GET NEW_URL (redirect uses GET)
CLIENT POST OLD_URL -> SERVER 303 NEW_URL -> CLIENT GET NEW_URL (redirect uses GET)

ACTUAL for 307: redirect uses same request method POST on NEW_URL

CLIENT POST OLD_URL -> SERVER 307 NEW_URL -> CLIENT POST NEW_URL

How to get the CUDA version?

if nvcc --version is not working for you then use cat /usr/local/cuda/version.txt

How do I create a comma delimited string from an ArrayList?

foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()

or

string.Concat(foo.ToArray().Select(a => a += ",").ToArray())

Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.

Intersection and union of ArrayLists in Java

I think you should use a Set to hold the files if you want to do intersection and union on them. Then you can use Guava's Sets class to do union, intersection and filtering by a Predicate as well. The difference between these methods and the other suggestions is that all of these methods create lazy views of the union, intersection, etc. of the two sets. Apache Commons creates a new collection and copies data to it. retainAll changes one of your collections by removing elements from it.

Responsive Google Map?

Check this for a solution: http://jsfiddle.net/panchroma/5AEEV/

I can't take the credit for the code though, it comes from quick and easy way to make google maps iframe embed responsive.

Good luck!

CSS

#map_canvas{
width:50%;
height:300px !important;
}

HTML

    <!DOCTYPE html>
<html>
  <head>
    <title>Google Maps JavaScript API v3 Example: Map Simple</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
    <meta charset="utf-8"/>
    <style>
      html, body, #map_canvas {
        margin: 0;
        padding: 0;
        height: 100%;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
      var map;
      function initialize() {
        var mapOptions = {
          zoom: 8,
          center: new google.maps.LatLng(-34.397, 150.644),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
            mapOptions);
      }

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html> 

Observable Finally on Subscribe

I'm now using RxJS 5.5.7 in an Angular application and using finalize operator has a weird behavior for my use case since is fired before success or error callbacks.

Simple example:

// Simulate an AJAX callback...
of(null)
  .pipe(
    delay(2000),
    finalize(() => {
      // Do some work after complete...
      console.log('Finalize method executed before "Data available" (or error thrown)');
    })
  )
  .subscribe(
      response => {
        console.log('Data available.');
      },
      err => {
        console.error(err);
      }
  );

I have had to use the add medhod in the subscription to accomplish what I want. Basically a finally callback after the success or error callbacks are done. Like a try..catch..finally block or Promise.finally method.

Simple example:

// Simulate an AJAX callback...
of(null)
  .pipe(
    delay(2000)
  )
  .subscribe(
      response => {
        console.log('Data available.');
      },
      err => {
        console.error(err);
      }
  );
  .add(() => {
    // Do some work after complete...
    console.log('At this point the success or error callbacks has been completed.');
  });

Should I use int or Int32

There is no difference between int and Int32, but as int is a language keyword many people prefer it stylistically (just as with string vs String).

Convert base-2 binary number string to int

You use the built-in int function, and pass it the base of the input number, i.e. 2 for a binary number:

>>> int('11111111', 2)
255

Here is documentation for python2, and for python3.

make an html svg object also a clickable link

The easiest way is to not use <object>. Instead use an <img> tag and the anchor should work just fine.

Get Bitmap attached to ImageView

Write below code

ImageView yourImageView = (ImageView) findViewById(R.id.yourImageView);
Bitmap bitmap = ((BitmapDrawable)yourImageView.getDrawable()).getBitmap();

Powershell Log Off Remote Session

Try the Terminal Services PowerShell Module:

Get-TSSession -ComputerName comp1 -UserName user1 | Stop-TSSession -Force

How to vertically center a "div" element for all browsers using CSS?

This method doesn't use any transform. So it doesn't have a problem with the output becoming blurry.

position: absolute;
width: 100vw;
top: 25%;
bottom: 25%;
text-align: center;

Measuring function execution time in R

Another possible way of doing this would be to use Sys.time():

start.time <- Sys.time()
...Relevent codes...
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

Not the most elegant way to do it, compared to the answere above , but definitely a way to do it.

How do I delete everything in Redis?

Heads up that FLUSHALL may be overkill. FLUSHDB is the one to flush a database only. FLUSHALL will wipe out the entire server. As in every database on the server. Since the question was about flushing a database I think this is an important enough distinction to merit a separate answer.

How do I get a YouTube video thumbnail from the YouTube API?

Here's the top answer optimized for manual use. The video ID token without separators enables selecting with a double click.

Each YouTube video has four generated images. They are predictably formatted as follows:

https://img.youtube.com/vi/YOUTUBEVIDEOID/0.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/1.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/2.jpg
https://img.youtube.com/vi/YOUTUBEVIDEOID/3.jpg

The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (ie. one of 1.jpg, 2.jpg, 3.jpg) is:

https://img.youtube.com/vi/YOUTUBEVIDEOID/default.jpg

For the high quality version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a URL similar to the HQ:

https://img.youtube.com/vi/YOUTUBEVIDEOID/mqdefault.jpg

For the standard definition version of the thumbnail, use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/sddefault.jpg

For the maximum resolution version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/YOUTUBEVIDEOID/maxresdefault.jpg

All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example URLs above.

Alternatively, you can use the YouTube Data API (v3) to get thumbnail images.

Best practice to validate null and empty collection in Java

Personally, I prefer to use empty collections instead of null and have the algorithms work in a way that for the algorithm it does not matter if the collection is empty or not.

How to get current language code with Swift?

swift 3

let preferredLanguage = Locale.preferredLanguages[0] as String
print (preferredLanguage) //en-US

let arr = preferredLanguage.components(separatedBy: "-")
let deviceLanguage = arr.first
print (deviceLanguage) //en

jQuery Keypress Arrow Keys

$(document).keydown(function(e) {
    console.log(e.keyCode);
});

Keypress events do detect arrow keys, but not in all browsers. So it's better to use keydown.

These are keycodes you should be getting in your console log:

  • left = 37
  • up = 38
  • right = 39
  • down = 40

Add placeholder text inside UITextView in Swift?

No need to add any third party library. Just use below code...

class SubmitReviewVC : UIViewController, UITextViewDelegate {

@IBOutlet var txtMessage : UITextView!
var lblPlaceHolder : UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    txtMessage.delegate = self
    lblPlaceHolder = UILabel()
    lblPlaceHolder.text = "Enter message..."
    lblPlaceHolder.font = UIFont.systemFont(ofSize: txtMessage.font!.pointSize)
    lblPlaceHolder.sizeToFit()
    txtMessage.addSubview(lblPlaceHolder)
    lblPlaceHolder.frame.origin = CGPoint(x: 5, y: (txtMessage.font?.pointSize)! / 2)
    lblPlaceHolder.textColor = UIColor.lightGray
    lblPlaceHolder.isHidden = !txtMessage.text.isEmpty
}

func textViewDidChange(_ textView: UITextView) {
    lblPlaceHolder.isHidden = !textView.text.isEmpty
}

}

How to replace url parameter with javascript/jquery?

In addition to @stenix, this worked perfectly to me

 url =  window.location.href;
    paramName = 'myparam';
        paramValue = $(this).val();
        var pattern = new RegExp('('+paramName+'=).*?(&|$)') 
        var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
        var n=url.indexOf(paramName);
        alert(n)
        if(n == -1){
            newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
        }
        window.location.href = newUrl;

Here no need to save the "url" variable, just replace in current url

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

I'd suggest using RVM it allows you have multiple versions of Ruby/Rails installed with gem profiles and basically keep all your gems contained from one another. You may want to check out a similar post How can I install Ruby on Rails 3 on OSX

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

php artisan dump-autoload was deprecated on Laravel 5, so you need to use composer dump-autoload

Creating PHP class instance with a string

Yes, you can!

$str = 'One';
$class = 'Class'.$str;
$object = new $class();

When using namespaces, supply the fully qualified name:

$class = '\Foo\Bar\MyClass'; 
$instance = new $class();

Other cool stuff you can do in php are:
Variable variables:

$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123

And variable functions & methods.

$func = 'my_function';
$func('param1'); // calls my_function('param1');

$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method. 

vertical divider between two columns in bootstrap

With Bootstrap 4 you can use borders, avoiding writing other CSS.

border-left

And if you want space between content and border you can use padding. (in this example padding left 4px)

pl-4

Example:

_x000D_
_x000D_
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
    <div class="row">_x000D_
      <div class="offset-6 border-left pl-4">First</div>_x000D_
      <div class="offset-6 border-left pl-4">Second</div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Producer/Consumer threads using a Queue

  1. Java code "BlockingQueue" which has synchronized put and get method.
  2. Java code "Producer" , producer thread to produce data.
  3. Java code "Consumer" , consumer thread to consume the data produced.
  4. Java code "ProducerConsumer_Main", main function to start the producer and consumer thread.

BlockingQueue.java

public class BlockingQueue 
{
    int item;
    boolean available = false;

    public synchronized void put(int value) 
    {
        while (available == true)
        {
            try 
            {
                wait();
            } catch (InterruptedException e) { 
            } 
        }

        item = value;
        available = true;
        notifyAll();
    }

    public synchronized int get()
    {
        while(available == false)
        {
            try
            {
                wait();
            }
            catch(InterruptedException e){
            }
        }

        available = false;
        notifyAll();
        return item;
    }
}

Consumer.java

package com.sukanya.producer_Consumer;

public class Consumer extends Thread
{
    blockingQueue queue;
    private int number;
    Consumer(BlockingQueue queue,int number)
    {
        this.queue = queue;
        this.number = number;
    }

    public void run()
    {
        int value = 0;

        for (int i = 0; i < 10; i++) 
        {
            value = queue.get();
            System.out.println("Consumer #" + this.number+ " got: " + value);
        }
    }
}

ProducerConsumer_Main.java

package com.sukanya.producer_Consumer;

public class ProducerConsumer_Main 
{
    public static void main(String args[])
    {
        BlockingQueue queue = new BlockingQueue();
        Producer producer1 = new Producer(queue,1);
        Consumer consumer1 = new Consumer(queue,1);
        producer1.start();
        consumer1.start();
    }
}

How to get the jQuery $.ajax error response text?

you can try it too:

$(document).ajaxError(
    function (event, jqXHR, ajaxSettings, thrownError) {
        alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
    });

What happens to a declared, uninitialized variable in C? Does it have a value?

Because computers have finite storage capacity, automatic variables will typically be held in storage elements (whether registers or RAM) that have previously been used for some other arbitrary purpose. If a such a variable is used before a value has been assigned to it, that storage may hold whatever it held previously, and so the contents of the variable will be unpredictable.

As an additional wrinkle, many compilers may keep variables in registers which are larger than the associated types. Although a compiler would be required to ensure that any value which is written to a variable and read back will be truncated and/or sign-extended to its proper size, many compilers will perform such truncation when variables are written and expect that it will have been performed before the variable is read. On such compilers, something like:

uint16_t hey(uint32_t x, uint32_t mode)
{ uint16_t q; 
  if (mode==1) q=2; 
  if (mode==3) q=4; 
  return q; }

 uint32_t wow(uint32_t mode) {
   return hey(1234567, mode);
 }

might very well result in wow() storing the values 1234567 into registers 0 and 1, respectively, and calling foo(). Since x isn't needed within "foo", and since functions are supposed to put their return value into register 0, the compiler may allocate register 0 to q. If mode is 1 or 3, register 0 will be loaded with 2 or 4, respectively, but if it is some other value, the function may return whatever was in register 0 (i.e. the value 1234567) even though that value is not within the range of uint16_t.

To avoid requiring compilers to do extra work to ensure that uninitialized variables never seem to hold values outside their domain, and avoid needing to specify indeterminate behaviors in excessive detail, the Standard says that use of uninitialized automatic variables is Undefined Behavior. In some cases, the consequences of this may be even more surprising than a value being outside the range of its type. For example, given:

void moo(int mode)
{
  if (mode < 5)
    launch_nukes();
  hey(0, mode);      
}

a compiler could infer that because invoking moo() with a mode which is greater than 3 will inevitably lead to the program invoking Undefined Behavior, the compiler may omit any code which would only be relevant if mode is 4 or greater, such as the code which would normally prevent the launch of nukes in such cases. Note that neither the Standard, nor modern compiler philosophy, would care about the fact that the return value from "hey" is ignored--the act of trying to return it gives a compiler unlimited license to generate arbitrary code.

How do I handle newlines in JSON?

According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:

A string is a sequence of Unicode code points wrapped with quotation marks (U+0022). All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F. There are two-character escape sequence representations of some characters.

So you can't pass 0x0A or 0x0C codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000 to U+001F:

  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).

As most of programming languages uses \ for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):

jsonStr = "{ \"name\": \"Multi\\nline.\" }";

Reading a file character by character in C

The problem here is twofold

  • a) you increment the pointer before you check the value read in, and
  • b) you ignore the fact that fgetc() returns an int instead of a char.

The first is easily fixed:

char *orig = code; // the beginning of the array
// ...
do {
  *code = fgetc(file);
} while(*code++ != EOF);
*code = '\0'; // nul-terminate the string
return orig; // don't return a pointer to the end

The second problem is more subtle -fgetc returns an int so that the EOF value can be distinguished from any possible char value. Fixing this uses a temporary int for the EOF check and probably a regular while loop instead of do / while.

Batch Renaming of Files in a Directory

Try: http://www.mattweber.org/2007/03/04/python-script-renamepy/

I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.

This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.

The program's source code is also available.

Convert XML String to Object

public string Serialize<T>(T settings)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    StringWriter outStream = new StringWriter();
    serializer.Serialize(outStream, settings);
    return outStream.ToString();
}

How to install mysql-connector via pip

pip install mysql-connector

Last but not least,You can also install mysql-connector via source code

Download source code from: https://dev.mysql.com/downloads/connector/python/