Programs & Examples On #Silverlight embedded

How do I resolve `The following packages have unmet dependencies`

First of all try this

sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove

If error still persists then do this

sudo apt --fix-broken install
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f

Afterwards try this again:

sudo apt-get install npm

But if it still couldn't resolve issues check for the dependencies using sudo dpkg --configure -a and remove them one-by-one . Let's say dependencies are on npm then go for this ,

sudo apt-get remove nodejs
sudo apt-get remove npm

Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a

sudo apt-get update

Then check for the dependencies problem again using sudo dpkg --configure -a and if it's all clear then you are done . Later on install npm again using this

v=8   # set to 4, 5, 6, ... as needed
curl -sL https://deb.nodesource.com/setup_$v.x | sudo -E bash -

Then install the Node.js package.

sudo apt-get install -y nodejs

The answer above will work for general cases also(for dependencies on other packages like django ,etc) just after first two processes use the same process for the package you are facing dependency with.

jquery get all form elements: input, textarea & select

Just to add another way:

$('form[name=' + formName + ']').find(':input')

Connect to Active Directory via LDAP

If your email address is '[email protected]', try changing the createDirectoryEntry() as below.

XYZ is an optional parameter if it exists in mydomain directory

static DirectoryEntry createDirectoryEntry()
{
    // create and return new LDAP connection with desired settings
    DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
    ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
    ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
    return ldapConnection;
}

This will basically check for com -> mydomain -> XYZ -> Users -> abcd

The main function looks as below:

try
{
    username = "Firstname LastName"
    DirectoryEntry myLdapConnection = createDirectoryEntry();
    DirectorySearcher search = new DirectorySearcher(myLdapConnection);
    search.Filter = "(cn=" + username + ")";
    ....    

Javascript getElementsByName.value not working

document.getElementsByName("name") will get several elements called by same name . document.getElementsByName("name")[Number] will get one of them. document.getElementsByName("name")[Number].value will get the value of paticular element.

The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.

How can I build for release/distribution on the Xcode 4?

XCode>Product>Schemes>Edit Schemes>Run>Build Configuration

Key value pairs using JSON

I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.

Simple Key Pair JSON structure

var data = {
    'XXXXXX' : '100.0',
    'YYYYYYY' : '200.0',
    'ZZZZZZZ' : '500.0',
}

Usage JavaScript code to access the key pairs

for (var key in data) 
  { if (!data.hasOwnProperty(key))
    { continue; } 
    console.log(key + ' -> ' +  data[key]);
  };

Console output should look like this

XXXXXX -> 100.0 
YYYYYYY -> 200.0 
ZZZZZZZ -> 500.0

Here is a JSFiddle to show how it works.

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

How to check if current thread is not main thread

Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

set value of input field by php variable's value

One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input> tag.
Try this -

<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
    $value1=$_POST['value1'];
    $value2=$_POST['value2'];
    $sign=$_POST['sign'];
    ...
        //Adding to $result variable
    if($sign=='-') {
      $result = $value1-$value2;
    }
    //Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">

How do I convert datetime to ISO 8601 in PHP

If you try set a value in datetime-local

date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

There was no information in my Console so that sent me searching for additional solutions and found these - unique to the solutions presented here. I encountered this with Eclipse Oxygen trying to run an old Ant build on a project.

Cause 1 I had configured Eclipse to use an external Ant install which was version 1.10.2 which apparently had classes in it that were compiled with JDK 9. In Eclipse I got the JNI error described above (running the Ant build at the command line gave me the reknowned 'unsupported major.minor version' error - the Java I was using on the system was JDK 8).

The solution was to rollback to the embedded Eclipse version of Ant being 1.10.1. I verified this as the correct solution by downloading Ant 1.10.1 separately and reconfiguring Eclipse to use the new 1.10.1 externally and it still worked.

Cause 2 This can also happen when you have the Ant Runtime settings configured incorrectly in Eclipse's Preferences. Depending on the version of Ant you're running you will need to add the tools.jar from the appropriate JDK to the classpath used for the Ant Runtime (Home Entries). More specifically, without a proper configuration, Eclipse will complain when launching an Ant target that the JRE version is less than a particular required version.

Essentially, 'proper configuration' means aligning each of the configuration items in Eclipse for running Ant so that they all work together. This involves the Ant Runtime Home entry (must point to an Ant version that is compatible with your chosen JDK -- you can't run Ant with JDK 8 when it was compiled against JDK 9); specifying the tools.jar that belongs to the JDK you want to run Ant with in the Ant Runtime settings; and lastly setting the JRE environment of your build script to the JDK you want to run Ant with in the External Tools Configuration. All 3 of these settings need to agree to avoid the error described above. You'll also need to consider the attributes used in your javac tag to ensure the JDK you're using is capable of executing as you've directed (i.e. JDK 7 can't compile code using source and target version 8).

Moreover If you're really just trying to run an Ant build script to compile code to an older JDK (e.g. less than 8 for Oxygen), this article helped gain access to run Ant against an older JDK. There are Ant plugin replacements for a handful of versions of Eclipse, the instructions are brief and getting the correct plugin version for your particular Eclipse is important.

Or more simply you can use this very good solution to do your legacy compile which doesn't require replacing your Eclipse plugin but instead changing the javac tag in your build script (while using the latest JDK).

linq where list contains any in list

Sounds like you want:

var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());

Updating an object with setState in React

Without using Async and Await Use this...

funCall(){    
     this.setState({...this.state.jasper, name: 'someothername'});
}

If you using with Async And Await use this...

async funCall(){
      await this.setState({...this.state.jasper, name: 'someothername'});
}

ORDER BY date and time BEFORE GROUP BY name in mysql

As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:

SELECT *
FROM (
     SELECT *
     ORDER BY date ASC, time ASC
     LIMIT 18446744073709551615
     ) AS sub
GROUP BY sub.name

https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/

Android - drawable with rounded corners at the top only

Building upon busylee's answer, this is how you can make a drawable that only has one unrounded corner (top-left, in this example):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <!-- A numeric value is specified in "radius" for demonstrative purposes only,
                  it should be @dimen/val_name -->
            <corners android:radius="10dp" />
        </shape>
    </item>
    <!-- To keep the TOP-LEFT corner UNROUNDED set both OPPOSITE offsets (bottom+right): -->
    <item
        android:bottom="10dp"
        android:right="10dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
        </shape>
    </item>
</layer-list>

Please note that the above drawable is not shown correctly in the Android Studio preview (2.0.0p7). To preview it anyway, create another view and use this as android:background="@drawable/...".

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

to remove all shared memory segments on FreeBSD

#!/bin/sh
for i in $(ipcs -m | awk '{ print $2 }' | sed 1,2d);
do
    echo "ipcrm -m $i"
    ipcrm -m $i
done

to remove all semaphores

#!/bin/sh
for i in $(ipcs -s | awk '{ print $2 }' | sed 1,2d);
do
    echo "ipcrm -s $i"
    ipcrm -s $i
done

how to include js file in php?

I tried this, I've got something like

script type="text/javascript" src="createDiv.php?id=" script

AND In createDiv.php I Have

document getElementbyid(imgslide).appendchild(imgslide5).innerHTML = 'php echo $helloworld; ';

And I got supermad because the php at the beginning of the createDiv.php I made the $helloWorld php variable was formatted cut and paste from the html page

But it wouldn't work cause Of whitespaces was anyone gonna tell anyone about the whitespace problem cause my real php whitespace still works but not this one.

TSQL How do you output PRINT in a user defined function?

I got around this by temporarily rewriting my function to something like this:

IF OBJECT_ID ('[dbo].[fx_dosomething]', 'TF') IS NOT NULL
  drop function [dbo].[fx_dosomething];
GO

create FUNCTION dbo.fx_dosomething ( @x numeric )
returns @t table (debug varchar(100), x2 numeric)
as
begin
 declare @debug varchar(100)
 set @debug = 'printme';

 declare @x2 numeric
 set @x2 = 0.123456;

 insert into @t values (@debug, @x2)
 return 
end
go

select * from fx_dosomething(0.1)

select2 - hiding the search box

If you want to hide on initial opening and you are populating the dropdown via ajax call, add the following to the ajax block in your select2 declaration:

beforeSend: function () 
  {
    $('.select2-search--dropdown').addClass('hidden');
  }

To then show it again (and focus) after your ajax request is successful:

  success: function() {
      $('.select2-search--dropdown').removeClass('select2-search--hide'); // show search bar then focus
      $('.select2-search__field')[0].focus();
  }

Split string into array

ES6 :

const array = [...entry]; // entry="i am" => array=["i"," ","a","m"]

Mail not sending with PHPMailer over SSL using SMTP

First, Google created the "use less secure accounts method" function:

https://myaccount.google.com/security

Then created the another permission:

https://accounts.google.com/b/0/DisplayUnlockCaptcha

Hope it helps.

LINQ equivalent of foreach for IEnumerable<T>

I respectually disagree with the notion that link extension methods should be side-effect free (not only because they aren't, any delegate can perform side effects).

Consider the following:

   public class Element {}

   public Enum ProcessType
   {
      This = 0, That = 1, SomethingElse = 2
   }

   public class Class1
   {
      private Dictionary<ProcessType, Action<Element>> actions = 
         new Dictionary<ProcessType,Action<Element>>();

      public Class1()
      {
         actions.Add( ProcessType.This, DoThis );
         actions.Add( ProcessType.That, DoThat );
         actions.Add( ProcessType.SomethingElse, DoSomethingElse );
      }

      // Element actions:

      // This example defines 3 distict actions
      // that can be applied to individual elements,
      // But for the sake of the argument, make
      // no assumption about how many distict
      // actions there may, and that there could
      // possibly be many more.

      public void DoThis( Element element )
      {
         // Do something to element
      }

      public void DoThat( Element element )
      {
         // Do something to element
      }

      public void DoSomethingElse( Element element )
      {
         // Do something to element
      }

      public void Apply( ProcessType processType, IEnumerable<Element> elements )
      {
         Action<Element> action = null;
         if( ! actions.TryGetValue( processType, out action ) )
            throw new ArgumentException("processType");
         foreach( element in elements ) 
            action(element);
      }
   }

What the example shows is really just a kind of late-binding that allows one invoke one of many possible actions having side-effects on a sequence of elements, without having to write a big switch construct to decode the value that defines the action and translate it into its corresponding method.

What is the difference between DSA and RSA?

Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.

WPF Image Dynamically changing Image source during runtime

Try Stretch="UniformToFill" on the Image

Git fast forward VS no fast forward merge

The --no-ff option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff.

If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.

For example, the author of this article thinks that --no-ff option should be default and his reasoning is close to that I outlined above:

Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff is not used], whereas it is easily done if the --no-ff flag was used [because it's just one commit]."

Graphic showing how --no-ff groups together all commits from feature branch into one commit on master branch

FULL OUTER JOIN vs. FULL JOIN

Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:

  • LEFT OUTER JOIN or LEFT JOIN

  • RIGHT OUTER JOIN or RIGHT JOIN

  • FULL OUTER JOIN or FULL JOIN

From MSDN

The full outer join or full join returns all rows from both tables, matching up the rows wherever a match can be made and placing NULLs in the places where no matching row exists.

How do you add an SDK to Android Studio?

Download your sdk file, go to Android studio: File->New->Import Module

How do I change button size in Python?

Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"

To change the size of a button called button1 you simple call

button1.config( height = WHATEVER, width = WHATEVER2 )

If you know what size you want at initialization these options can be added to the constructor.

button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100) 

php string to int

You can remove the spaces before casting to int:

(int)str_replace(' ', '', $b);

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):

(int)str_replace(array(' ', ','), '', $b);

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Use data type 'MultilineText':

[DataType(DataType.MultilineText)]
public string Text { get; set; }

See ASP.NET MVC3 - textarea with @Html.EditorFor

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

If you just want to know how long it takes for the command to execute, you may consider using the time command. You for example use time ffmpeg -i myvideoofoneminute.aformat out.anotherformat

jQuery checkbox checked state changed event

Just another solution

$('.checkbox_class').on('change', function(){ // on change of state
   if(this.checked) // if changed state is "CHECKED"
    {
        // do the magic here
    }
})

What is causing "Unable to allocate memory for pool" in PHP?

Probably is APC related.

For the people having this problem, please specify you .ini settings. Specifically your apc.mmap_file_mask setting.

For file-backed mmap, it should be set to something like:

apc.mmap_file_mask=/tmp/apc.XXXXXX

To mmap directly from /dev/zero, use:

apc.mmap_file_mask=/dev/zero

For POSIX-compliant shared-memory-backed mmap, use:

apc.mmap_file_mask=/apc.shm.XXXXXX

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

This is what I would call a classically Apple Xcode UX design bug.

The error said there is a bunch of stuff YOU DID WRONG LOCALLY.

The error actually meant "we have a new agreement you did not accept online".

After checking and unchecking the Automatic Signing button, I got this agreement error to display

After checking and unchecking the Automatic Signing button I got this agreement error to display:

Signing into the developer portal I was able to see a banner for the agreement update notice

Signing into the developer portal I was able to see a banner for the agreement update notice:

Restarting Xcode 8 then cleared that error and only forced me to reselect the certificate I already had on my machine and tied to the project. Restarting Xcode 8 then cleared that error and only forced me to reselect the certificate I already had on my machine and tied to the project.

This could have been handled in a less confusing implementation, but this is how I fixed it. I am putting it here because it's way different than the steps everyone else gave.

Oh and yeah, having the pre-latest iOS 10 device and latest Xcode (I was on 7.3.1 or something) also threw errors until I updated.

How to sort List of objects by some property

In java you need to use the static Collections.sort method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.

private static void order(List<TextComponent> roles) {

    Collections.sort(roles, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            int x1 = ((CompanyRole) o1).getBegin();
            int x2 = ((CompanyRole) o2).getBegin();

            if (x1 != x2) {
                return x1 - x2;
            } else {
                int y1 = ((CompanyRole) o1).getEnd();
                int y2 = ((CompanyRole) o2).getEnd();
                return y2 - y1;
            }
        }
    });
}

Save a file in json format using Notepad++

You can save it as .txt and change it manually using a mouse click and your keyboard. OR, when saving the file:

  • choose All types(*.*) in the Save as type field.
  • type filename.json in File name field

How do I install chkconfig on Ubuntu?

In Ubuntu /etc/init.d has been replaced by /usr/lib/systemd. Scripts can still be started and stoped by 'service'. But the primary command is now 'systemctl'. The chkconfig command was left behind, and now you do this with systemctl.

So instead of:

chkconfig enable apache2

You should look for the service name, and then enable it

systemctl status apache2
systemctl enable apache2.service

Systemd has become more friendly about figuring out if you have a systemd script, or an /etc/init.d script, and doing the right thing.

C# : 'is' keyword and checking for Not

C# 9 (released with .NET 5) includes the logical patterns and, or and not, which allows us to write this more elegantly:

if (child is not IContainer) { ... }

Likewise, this pattern can be used to check for null:

if (child is not null) { ... }

Convert Pandas column containing NaNs to dtype `int`

In version 0.24.+ pandas has gained the ability to hold integer dtypes with missing values.

Nullable Integer Data Type.

Pandas can represent integer data with possibly missing values using arrays.IntegerArray. This is an extension types implemented within pandas. It is not the default dtype for integers, and will not be inferred; you must explicitly pass the dtype into array() or Series:

arr = pd.array([1, 2, np.nan], dtype=pd.Int64Dtype())
pd.Series(arr)

0      1
1      2
2    NaN
dtype: Int64

For convert column to nullable integers use:

df['myCol'] = df['myCol'].astype('Int64')

Transpose a data frame

You can use the transpose function from the data.table library. Simple and fast solution that keeps numeric values as numeric.

library(data.table)

# get data
  data("mtcars")

# transpose
  t_mtcars <- transpose(mtcars)

# get row and colnames in order
  colnames(t_mtcars) <- rownames(mtcars)
  rownames(t_mtcars) <- colnames(mtcars)

JQuery, select first row of table

Ok so if an image in a table is clicked you want the data of the first row of the table this image is in.

//image click stuff here {
$(this). // our image
closest('table'). // Go upwards through our parents untill we hit the table
children('tr:first'); // Select the first row we find

var $row = $(this).closest('table').children('tr:first');

parent() will only get the direct parent, closest should do what we want here. From jQuery docs: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

How do I remove my IntelliJ license in 2019.3?

Not sure about older versions, but in 2016.2 removing the .key file(s) didn't work for me.

I'm using my JetBrains account and used the 'Remove License' button found at the bottom of the registration dialog. You can find this under the Help menu or from the startup dialog via Configure -> Manage License....

How/when to generate Gradle wrapper files?

This is the command to use to tell Gradle to upgrade the wrapper such that it will grab the distribution versions of libraries that includes source code:

./gradlew wrapper --gradle-version <version> --distribution-type all

Specifying the distribution-type with "all" will make sure Gradle downloads source files for use by your development environment.

Pros:

  • IDEs will have immediate access to source code. For example, Intellij IDEA won't prompt you to update your build scripts to include the source distro (because this command already did that)

Cons:

  • Longer/Bigger build process because it's downloading source code. This is a waste of time/space on a build or CI server where the source code is not necessary.

Please comment or provide another answer if you know of any command line option to tell Gradle not to download sources on a build server.

Bash ignoring error for a particular command

I kind of like this solution :

: `particular_script`

The command/script between the back ticks is executed and its output is fed to the command ":" (which is the equivalent of "true")

$ false
$ echo $?
1
$ : `false`
$ echo $?
0

edit: Fixed ugly typo

What does the "map" method do in Ruby?

Map is a part of the enumerable module. Very similar to "collect" For Example:

  Class Car

    attr_accessor :name, :model, :year

    Def initialize (make, model, year)
      @make, @model, @year = make, model, year
    end

  end

  list = []
  list << Car.new("Honda", "Accord", 2016)
  list << Car.new("Toyota", "Camry", 2015)
  list << Car.new("Nissan", "Altima", 2014)

  p list.map {|p| p.model}

Map provides values iterating through an array that are returned by the block parameters.

Adding values to Arraylist

First simple rule: never use the String(String) constructor, it is absolutely useless (*).

So arr.add("ss") is just fine.

With 3 it's slightly different: 3 is an int literal, which is not an object. Only objects can be put into a List. So the int will need to be converted into an Integer object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as Integer.valueOf(3) which can (and will) avoid creating a new Integer instance in some cases.

So actually writing arr.add(3) is usually a better idea than using arr.add(new Integer(3)), because it can avoid creating a new Integer object and instead reuse and existing one.

Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.

(*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)

How to check sbt version?

$ sbt sbtVersion

This prints the sbt version used in your current project, or if it is a multi-module project for each module.

$ sbt 'inspect sbtVersion'
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.13.1
[info] Description:
[info]  Provides the version of sbt.  This setting should be not be modified.
[info] Provided by:
[info]  */*:sbtVersion
[info] Defined at:
[info]  (sbt.Defaults) Defaults.scala:68
[info] Delegates:
[info]  *:sbtVersion
[info]  {.}/*:sbtVersion
[info]  */*:sbtVersion
[info] Related:
[info]  */*:sbtVersion

You may also want to use sbt about that (copying Mark Harrah's comment):

The about command was added recently to try to succinctly print the most relevant information, including the sbt version.

How to change the window title of a MATLAB plotting figure?

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

How to use GROUP BY to concatenate strings in SQL Server?

Eight years later... Microsoft SQL Server vNext Database Engine has finally enhanced Transact-SQL to directly support grouped string concatenation. The Community Technical Preview version 1.0 added the STRING_AGG function and CTP 1.1 added the WITHIN GROUP clause for the STRING_AGG function.

Reference: https://msdn.microsoft.com/en-us/library/mt775028.aspx

Most simple code to populate JTable from ResultSet

Well I'm sure that this is the simplest way to populate JTable from ResultSet, without any external library. I have included comments in this method.

public void resultSetToTableModel(ResultSet rs, JTable table) throws SQLException{
        //Create new table model
        DefaultTableModel tableModel = new DefaultTableModel();

        //Retrieve meta data from ResultSet
        ResultSetMetaData metaData = rs.getMetaData();

        //Get number of columns from meta data
        int columnCount = metaData.getColumnCount();

        //Get all column names from meta data and add columns to table model
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
            tableModel.addColumn(metaData.getColumnLabel(columnIndex));
        }

        //Create array of Objects with size of column count from meta data
        Object[] row = new Object[columnCount];

        //Scroll through result set
        while (rs.next()){
            //Get object from column with specific index of result set to array of objects
            for (int i = 0; i < columnCount; i++){
                row[i] = rs.getObject(i+1);
            }
            //Now add row to table model with that array of objects as an argument
            tableModel.addRow(row);
        }

        //Now add that table model to your table and you are done :D
        table.setModel(tableModel);
    }

Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

How to add Google Maps Autocomplete search box?

I am using jQuery here to get the entered text and wrapping all code in $(document).ready(). Make sure you have your API key ready for Google Places API Web service. Replace it in the below script file.

<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}

MongoDB: Is it possible to make a case-insensitive query?

db.company_profile.find({ "companyName" : { "$regex" : "Nilesh" , "$options" : "i"}});

How can I find my php.ini on wordpress?

I just came across this thread while searching for an answer to why the php.ini file would be within the /wp-admin/ folder for WordPress that I have just seen in an odd setup - because it really really shouldn't be there.

WordPress by default doesn't include a php.ini file within the /wp-admin/ folder, so you should not have one there yourself. The php.ini file is designed to override the main server PHP configuration settings so that your account on the server is treated differently, within limits. As such, if you do need to use this file, please, for your own sanity (and that of others who happen to work with your systems in the future...), place the php.ini file in the root of your account, not hidden away in the /wp-admin/ folder, or any other folder for that matter.

I'm surprised to see so many others commenting that it should be in the /wp-admin/ folder to be honest. I'd love to see some official documentation from WordPress stating that this is best practice, as this is certainly something that I would completely avoid.

How to sort a Collection<T>?

You can't if T is all you get. It must be injected by the provider:

Collection<T extends Comparable>

or pass in the Comparator

Collections.sort(...)

How to set 777 permission on a particular folder?

  1. Right click the folder, click on Properties.
  2. Click on the Security tab
  3. Add the name Everyone to the user list.

Add php variable inside echo statement as href link address?

Basically like this,

<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>

Are there any log file about Windows Services Status?

The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.

Reverting single file in SVN to a particular revision

The best way is to:

svn merge -c -RevisionToUndo ^/trunk

This will undo all files of the revision than simply revert those file you don't like to undo. Don't forget the dash (-) as prefix for the revision.

svn revert File1 File2

Now commit the changes back.

How do I supply an initial value to a text field?

This can be achieved using TextEditingController.

To have an initial value you can add

TextEditingController _controller = TextEditingController(text: 'initial value');

or

If you are using TextFormField you have a initialValue property there. Which basically provides this initialValue to the controller automatically.

TextEditingController _controller = TextEditingController();
TextFormField(
  controller: _controller,
  initialValue: 'initial value'
)

To clear the text you can use _controller.clear() method.

Pass Multiple Parameters to jQuery ajax call

I successfully passed multiple parameters using json

data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + "'," + "'tempdata':'" +"myvalue" + "'}",

get client time zone from browser

For now, the best bet is probably jstz as suggested in mbayloon's answer.

For completeness, it should be mentioned that there is a standard on it's way: Intl. You can see this in Chrome already:

> Intl.DateTimeFormat().resolvedOptions().timeZone
"America/Los_Angeles"

(This doesn't actually follow the standard, which is one more reason to stick with the library)

One DbContext per web request... why?

Not a single answer here actually answers the question. The OP did not ask about a singleton/per-application DbContext design, he asked about a per-(web)request design and what potential benefits could exist.

I'll reference http://mehdi.me/ambient-dbcontext-in-ef6/ as Mehdi is a fantastic resource:

Possible performance gains.

Each DbContext instance maintains a first-level cache of all the entities its loads from the database. Whenever you query an entity by its primary key, the DbContext will first attempt to retrieve it from its first-level cache before defaulting to querying it from the database. Depending on your data query pattern, re-using the same DbContext across multiple sequential business transactions may result in a fewer database queries being made thanks to the DbContext first-level cache.

It enables lazy-loading.

If your services return persistent entities (as opposed to returning view models or other sorts of DTOs) and you'd like to take advantage of lazy-loading on those entities, the lifetime of the DbContext instance from which those entities were retrieved must extend beyond the scope of the business transaction. If the service method disposed the DbContext instance it used before returning, any attempt to lazy-load properties on the returned entities would fail (whether or not using lazy-loading is a good idea is a different debate altogether which we won't get into here). In our web application example, lazy-loading would typically be used in controller action methods on entities returned by a separate service layer. In that case, the DbContext instance that was used by the service method to load these entities would need to remain alive for the duration of the web request (or at the very least until the action method has completed).

Keep in mind there are cons as well. That link contains many other resources to read on the subject.

Just posting this in case someone else stumbles upon this question and doesn't get absorbed in answers that don't actually address the question.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I found the solution as Its problem with Android Studio 3.1 Canary 6

My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.

Now My build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.example.demo"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    dataBinding {
        enabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.squareup.retrofit2:retrofit:2.3.0"
    implementation "com.google.code.gson:gson:2.8.2"
    implementation "com.android.support.constraint:constraint-layout:1.0.2"
    implementation "com.squareup.retrofit2:converter-gson:2.3.0"
    implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
    implementation "com.squareup.picasso:picasso:2.5.2"
    implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
    compile 'com.github.elevenetc:badgeview:v1.0.0'
    annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
    testImplementation "junit:junit:4.12"
    androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
        exclude group: "com.android.support", module: "support-annotations"
    })
}

and My gradle is:

classpath 'com.android.tools.build:gradle:3.1.0-alpha06'

and its working finally.

I think there problem in Android Studio 3.1 Canary 6

Thank you all for your time.

Make first letter of a string upper case (with maximum performance)

send a string to this function. it will first check string is empty or null, if not string will be all lower chars. then return first char of string upper rest of them lower.

string FirstUpper(string s)
    {
        // Check for empty string.
        if (string.IsNullOrEmpty(s))
        {
            return string.Empty;
        }
        s = s.ToLower();
        // Return char and concat substring.
        return char.ToUpper(s[0]) + s.Substring(1);
    }

How to use cURL to get jSON data and decode the data?

to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php

$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");

$json_object = json_decode($unparsed_json);

then json_decode() parses JSON into a PHP object, or an array if you pass true to the second parameter. http://php.net/manual/en/function.json-decode.php

For example:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array

CodeIgniter: Create new helper?

Just define a helper in application helper directory then call from your controller just function name like

helper name = new_helper.php
function test_method($data){
 return $data
}   

in controller load the helper

$this->load->new_helper();
$result =  test_method('Hello world!');
if($result){
 echo $result
}

output will be

Hello World!

Better/Faster to Loop through set or list?

While a set may be what you want structure-wise, the question is what is faster. A list is faster. Your example code doesn't accurately compare set vs list because you're converting from a list to a set in set_loop, and then you're creating the list you'll be looping through in list_loop. The set and list you iterate through should be constructed and in memory ahead of time, and simply looped through to see which data structure is faster at iterating:

ids_list = range(1000000)
ids_set = set(ids)
def f(x):
    for i in x:
         pass

%timeit f(ids_set)
#1 loops, best of 3: 214 ms per loop
%timeit f(ids_list)
#1 loops, best of 3: 176 ms per loop

"insufficient memory for the Java Runtime Environment " message in eclipse

You need to diagnosis the jvm usages like how many process is running and what about heap allocation. there exists a lot of ways to do that for example

  • you can use java jcmd to check number of object, size of memory (for linux you can use for example "/usr/jdk1.8.0_25/bin/jcmd 19628 GC.class_histogram > /tmp/19628_ClassHistogram_1.txt", here 19628 is the running application process id). You can easily check if any strong reference exists in your code or else.

Psql could not connect to server: No such file or directory, 5432 error?

Does the /etc/postgresql/9.6/main/postgresql.conf show that port being assigned? On my default Xubuntu Linux install, mine showed port = 5433 for some reason as best as I can remember, but I did comment out the line in that same file that said listen_addresses = 'localhost' and uncommented the line listen_addresses = '*'. So maybe start and check there. Hope that helps.

Jquery- Get the value of first td in table

$(this).parent().siblings(":first").text()

parent gives you the <td> around the link,

siblings gives all the <td> tags in that <tr>,

:first gives the first matched element in the set.

text() gives the contents of the tag.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

How to make unicode string with python3

In a Python 2 program that I used for many years there was this line:

ocd[i].namn=unicode(a[:b], 'utf-8')

This did not work in Python 3.

However, the program turned out to work with:

ocd[i].namn=a[:b]

I don't remember why I put unicode there in the first place, but I think it was because the name can contains Swedish letters åäöÅÄÖ. But even they work without "unicode".

UNIX export command

export is used to set environment variables. For example:

export EDITOR=pico

Will set your default text editor to be the pico command.

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

Wait until boolean value changes it state

You need a mechanism which avoids busy-waiting. The old wait/notify mechanism is fraught with pitfalls so prefer something from the java.util.concurrent library, for example the CountDownLatch:

public final CountDownLatch latch = new CountDownLatch(1);

public void run () {
  latch.await();
  ...
}

And at the other side call

yourRunnableObj.latch.countDown();

However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService to which you submit as a task the work which must be done when the condition is met.

CSS Cell Margin

You can simply do that:

<html>
<table>
    <tr>
        <td>one</td>
        <td width="10px"></td>
        <td>two</td>
    </tr>
</table>
</html>

No CSS is required :) This 10px is your space.

Media Queries: How to target desktop, tablet, and mobile?

One extra feature is you can also use-media queries in the media attribute of the <link> tag.

<link href="style.css" rel="stylesheet">
<link href="justForFrint.css" rel="stylesheet" media="print">
<link href="deviceSizeDepending.css" rel="stylesheet" media="(min-width: 40em)">

With this, the browser will download all CSS resources, regardless of the media attribute. The difference is that if the media-query of the media attribute is evaluated to false then that .css file and his content will not be render-blocking.

Therefore, it is recommended to use the media attribute in the <link> tag since it guarantees a better user experience.

Here you can read a Google article about this issue https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css

Some tools that will help you to automate the separation of your css code in different files according to your media-querys

Webpack https://www.npmjs.com/package/media-query-plugin https://www.npmjs.com/package/media-query-splitting-plugin

PostCSS https://www.npmjs.com/package/postcss-extract-media-query

How do I exit from the text window in Git?

There is a default text editor that will be used when Git needs you to type in a message. By default, Git uses your system’s default editor, which is generally Vi or Vim. In your case, it is Vim that Git has chosen. See How do I make Git use the editor of my choice for commits? for details of how to choose another editor. Meanwhile...

You'll want to enter a message before you leave Vim:

O

...will start a new line for you to type in.

To exit (g)Vim type:

EscZZ or Esc:wqReturn.

It's worth getting to know Vim, as you can use it for editing text on almost any platform. I recommend the Vim Tutor, I used it many years ago and have never looked back (barely a day goes by when I don't use Vim).

Get connection string from App.config

It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.

Generate random 5 characters string

It seems like str_shuffle would be a good use for this. Seed the shuffle with whichever characters you want.

$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);

What is the difference between an abstract function and a virtual function?

From general object oriented view:

Regarding abstract method: When you put an abstract method in the parent class actually your are saying to the child classes: Hey note that you have a method signature like this. And if you wanna to use it you should implement your own!

Regarding virtual function: When you put a virtual method in the parent class you are saying to the derived classes : Hey there is a functionality here that do something for you. If this is useful for you just use it. If not, override this and implement your code, even you can use my implementation in your code !

this is some philosophy about different between this two concept in General OO

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.

Java Program to test if a character is uppercase/lowercase/number/vowel

This may not be what you are looking for but I thought you oughta know the real way to do this. You can use the java.lang.Character class's isUpperCase() to find aout about the case of the character. You can use isDigit() to differentiate between the numbers and letters(This is just FYI :) ). You can then do a toUpperCase() and then do the switch for vowels. This will improve your code quality.

Cannot push to Git repository on Bitbucket

I found the git command line didnt fancy my pageant generated keys (Windows 10).

See my answer on Serverfault

java.lang.ClassCastException

A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

Apple myApple = new Apple();
Fruit myFruit = (Fruit)myApple;

This works because an apple 'is a' fruit. However if we reverse this.

Fruit myFruit = new Fruit();
Apple myApple = (Apple)myFruit;

This will throw a ClasCastException because a Fruit is not (always) an Apple.

It is good practice to guard any explicit casts with an instanceof check first:

if (myApple instanceof Fruit) {
  Fruit myFruit = (Fruit)myApple;
}

PHP check if file is an image

Native way to get the mimetype:

For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

function getMimeType($filename)
{
    $mimetype = false;
    if(function_exists('finfo_open')) {
        // open with FileInfo
    } elseif(function_exists('getimagesize')) {
        // open with GD
    } elseif(function_exists('exif_imagetype')) {
       // open with EXIF
    } elseif(function_exists('mime_content_type')) {
       $mimetype = mime_content_type($filename);
    }
    return $mimetype;
}

How to remove all event handlers from an event

I found a solution on the MSDN forums. The sample code below will remove all Click events from button1.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        button1.Click += button1_Click;
        button1.Click += button1_Click2;
        button2.Click += button2_Click;
    }

    private void button1_Click(object sender, EventArgs e)  => MessageBox.Show("Hello");
    private void button1_Click2(object sender, EventArgs e) => MessageBox.Show("World");
    private void button2_Click(object sender, EventArgs e)  => RemoveClickEvent(button1);

    private void RemoveClickEvent(Button b)
    {
        FieldInfo f1 = typeof(Control).GetField("EventClick", 
            BindingFlags.Static | BindingFlags.NonPublic);

        object obj = f1.GetValue(b);
        PropertyInfo pi = b.GetType().GetProperty("Events",  
            BindingFlags.NonPublic | BindingFlags.Instance);

        EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
        list.RemoveHandler(obj, list[obj]);
    }
}

How can I quantify difference between two images?

A simple solution:

Encode the image as a jpeg and look for a substantial change in filesize.

I've implemented something similar with video thumbnails, and had a lot of success and scalability.

Converting a pointer into an integer

  1. #include <stdint.h>
  2. Use uintptr_t standard type defined in the included standard header file.

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

I would like to know what exactly is the difference between querySelector and querySelectorAll against getElementsByClassName and getElementById?

The syntax and the browser support.

querySelector is more useful when you want to use more complex selectors.

e.g. All list items descended from an element that is a member of the foo class: .foo li

document.querySelector("#view:_id1:inputText1") it doesn't work. But writing document.getElementById("view:_id1:inputText1") works. Any ideas why?

The : character has special meaning inside a selector. You have to escape it. (The selector escape character has special meaning in a JS string too, so you have to escape that too).

document.querySelector("#view\\:_id1\\:inputText1")

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

There's a nice way to eject webpack.config.js from angular-cli. Just run:

$ ng eject

This will generate webpack.config.js in the root folder of your project, and you're free to configure it the way you want. The downside of this is that build/start scripts in your package.json will be replaced with the new commands and instead of

$ ng serve

you would have to do something like

$ npm run build & npm run start

This method should work in all the recent versions of angular-cli (I personally tried a few, with the oldest being 1.0.0-beta.21, and the latest 1.0.0-beta.32.3)

Where are $_SESSION variables stored?

For ubuntu 16.10 are sessions save in /var/lib/php/session/...

typedef fixed length array

Building off the accepted answer, a multi-dimensional array type, that is a fixed-length array of fixed-length arrays, can't be declared with

typedef char[M] T[N];  // wrong!

instead, the intermediate 1D array type can be declared and used as in the accepted answer:

typedef char T_t[M];
typedef T_t T[N];

or, T can be declared in a single (arguably confusing) statement:

typedef char T[N][M];

which defines a type of N arrays of M chars (be careful about the order, here).

Java 8: How do I work with exception throwing methods in streams?

You can wrap and unwrap exceptions this way.

class A {
    void foo() throws Exception {
        throw new Exception();
    }
};

interface Task {
    void run() throws Exception;
}

static class TaskException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    public TaskException(Exception e) {
        super(e);
    }
}

void bar() throws Exception {
      Stream<A> as = Stream.generate(()->new A());
      try {
        as.forEach(a -> wrapException(() -> a.foo())); // or a::foo instead of () -> a.foo()
    } catch (TaskException e) {
        throw (Exception)e.getCause();
    }
}

static void wrapException(Task task) {
    try {
        task.run();
    } catch (Exception e) {
        throw new TaskException(e);
    }
}

Return multiple values in JavaScript?

In JS, we can easily return a tuple with an array or object, but do not forget! => JS is a callback oriented language, and there is a little secret here for "returning multiple values" that nobody has yet mentioned, try this:

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};

becomes

var newCodes = function(fg, cb) {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    cb(null, dCodes, dCodes2);
};

:)

bam! This is simply another way of solving your problem.

How to change HTML Object element data attribute value in javascript

document.getElementById("PdfContentArea").setAttribute('data', path);

OR

var objectEl = document.getElementById("PdfContentArea")

objectEl.outerHTML = objectEl.outerHTML.replace(/data="(.+?)"/, 'data="' + path + '"');

How can I pass an Integer class correctly by reference?

I think it is the autoboxing that is throwing you off.

This part of your code:

   public static Integer inc(Integer i) {
        i = i+1;    // I think that this must be **sneakally** creating a new integer...  
        System.out.println("Inc: "+i);
        return i;
    }

Really boils down to code that looks like:

  public static Integer inc(Integer i) {
        i = new Integer(i) + new Integer(1);      
        System.out.println("Inc: "+i);
        return i;
    }

Which of course.. will not changes the reference passed in.

You could fix it with something like this

  public static void main(String[] args) {
        Integer integer = new Integer(0);
        for (int i =0; i<10; i++){
            integer = inc(integer);
            System.out.println("main: "+integer);
        }
    }

How do I check if string contains substring?

ECMAScript 6 introduces String.prototype.includes, previously named contains.

It can be used like this:

'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false

It also accepts an optional second argument which specifies the position at which to begin searching:

'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true

It can be polyfilled to make it work on old browsers.

How to cast int to enum in C++?

int i = 1;
Test val = static_cast<Test>(i);

How can I strip HTML tags from a string in ASP.NET?

For those who are complining about Michael Tiptop's solution not working, here is the .Net4+ way of doing it:

public static string StripTags(this string markup)
{
    try
    {
        StringReader sr = new StringReader(markup);
        XPathDocument doc;
        using (XmlReader xr = XmlReader.Create(sr,
                           new XmlReaderSettings()
                           {
                               ConformanceLevel = ConformanceLevel.Fragment
                               // for multiple roots
                           }))
        {
            doc = new XPathDocument(xr);
        }

        return doc.CreateNavigator().Value; // .Value is similar to .InnerText of  
                                           //  XmlDocument or JavaScript's innerText
    }
    catch
    {
        return string.Empty;
    }
}

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

How to check for empty array in vba macro

You can check if the array is empty by retrieving total elements count using JScript's VBArray() object (works with arrays of variant type, single or multidimensional):

Sub Test()

    Dim a() As Variant
    Dim b As Variant
    Dim c As Long

    ' Uninitialized array of variant
    ' MsgBox UBound(a) ' gives 'Subscript out of range' error
    MsgBox GetElementsCount(a) ' 0

    ' Variant containing an empty array
    b = Array()
    MsgBox GetElementsCount(b) ' 0

    ' Any other types, eg Long or not Variant type arrays
    MsgBox GetElementsCount(c) ' -1

End Sub

Function GetElementsCount(aSample) As Long

    Static oHtmlfile As Object ' instantiate once

    If oHtmlfile Is Nothing Then
        Set oHtmlfile = CreateObject("htmlfile")
        oHtmlfile.parentWindow.execScript ("function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}"), "jscript"
    End If
    GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)

End Function

For me it takes about 0.3 mksec for each element + 15 msec initialization, so the array of 10M elements takes about 3 sec. The same functionality could be implemented via ScriptControl ActiveX (it is not available in 64-bit MS Office versions, so you can use workaround like this).

sass --watch with automatic minify?

If you're using compass:

compass watch --output-style compressed

How to generate gcc debug symbol outside the build target?

Check out the "--only-keep-debug" option of the strip command.

From the link:

The intention is that this option will be used in conjunction with --add-gnu-debuglink to create a two part executable. One a stripped binary which will occupy less space in RAM and in a distribution and the second a debugging information file which is only needed if debugging abilities are required.

How to encrypt String in Java

This is the first page that shows up via Google and the security vulnerabilities in all the implementations make me cringe so I'm posting this to add information regarding encryption for others as it has been 7 Years from the original post. I hold a Masters Degree in Computer Engineering and spent a lot of time studying and learning Cryptography so I'm throwing my two cents to make the internet a safer place.

Also, do note that a lot of implementation might be secure for a given situation, but why use those and potentially accidentally make a mistake? Use the strongest tools you have available unless you have a specific reason not to. Overall I highly advise using a library and staying away from the nitty gritty details if you can.

UPDATE 4/5/18: I rewrote some parts to make them simpler to understand and changed the recommended library from Jasypt to Google's new library Tink, I would recommend completely removing Jasypt from an existing setup.

Foreword

I will outline the basics of secure symmetric cryptography below and point out common mistakes I see online when people implement crypto on their own with the standard Java library. If you want to just skip all the details run over to Google's new library Tink import that into your project and use AES-GCM mode for all your encryptions and you shall be secure.

Now if you want to learn the nitty gritty details on how to encrypt in java read on :)

Block Ciphers

First thing first you need to pick a symmetric key Block Cipher. A Block Cipher is a computer function/program used to create Pseudo-Randomness. Pseudo-Randomness is fake randomness that no computer other than a Quantum Computer would be able to tell the difference between it and real randomness. The Block Cipher is like the building block to cryptography, and when used with different modes or schemes we can create encryptions.

Now regarding Block Cipher Algorithms available today, Make sure to NEVER, I repeat NEVER use DES, I would even say NEVER use 3DES. The only Block Cipher that even Snowden's NSA release was able to verify being truly as close to Pseudo-Random as possible is AES 256. There also exists AES 128; the difference is AES 256 works in 256-bit blocks, while AES 128 works in 128 blocks. All in all, AES 128 is considered secure although some weaknesses have been discovered, but 256 is as solid as it gets.

Fun fact DES was broken by the NSA back when it was initially founded and actually kept a secret for a few years. Although some people still claim 3DES is secure, there are quite a few research papers that have found and analyzed weaknesses in 3DES.

Encryption Modes

Encryption is created when you take a block cipher and use a specific scheme so that the randomness is combined with a key to creating something that is reversible as long as you know the key. This is referred to as an Encryption Mode.

Here is an example of an encryption mode and the simplest mode known as ECB just so you can visually understand what is happening:

ECB Mode

The encryption modes you will see most commonly online are the following:

ECB CTR, CBC, GCM

There exist other modes outside of the ones listed and researchers are always working toward new modes to improve existing problems.

Now let's move on to implementations and what is secure. NEVER use ECB this is bad at hiding repeating data as shown by the famous Linux penguin.Linux Penguin Example

When implementing in Java, note that if you use the following code, ECB mode is set by default:

Cipher cipher = Cipher.getInstance("AES");

... DANGER THIS IS A VULNERABILITY! and unfortunately, this is seen all over StackOverflow and online in tutorials and examples.

Nonces and IVs

In response to the issue found with ECB mode nounces also known as IVs were created. The idea is that we generate a new random variable and attach it to every encryption so that when you encrypt two messages that are the same they come out different. The beauty behind this is that an IV or nonce is public knowledge. That means an attacker can have access to this but as long as they don't have your key, they cant do anything with that knowledge.

Common issues I will see is that people will set the IV as a static value as in the same fixed value in their code. and here is the pitfall to IVs the moment you repeat one you actually compromise the entire security of your encryption.

Generating A Random IV

SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);

Note: SHA1 is broken but I couldn't find how to implement SHA256 into this use case properly, so if anyone wants to take a crack at this and update it would be awesome! Also SHA1 attacks still are unconventional as it can take a few years on a huge cluster to crack. Check out details here.

CTR Implementation

No padding is required for CTR mode.

 Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

CBC Implementation

If you choose to implement CBC Mode do so with PKCS7Padding as follows:

 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

CBC and CTR Vulnerability and Why You Should Use GCM

Although some other modes such as CBC and CTR are secure they run into the issue where an attacker can flip the encrypted data, changing its value when decrypted. So let's say you encrypt an imaginary bank message "Sell 100", your encrypted message looks like this "eu23ng" the attacker changes one bit to "eu53ng" and all of a sudden when decrypted your message, it reads as "Sell 900".

To avoid this the majority of the internet uses GCM, and every time you see HTTPS they are probably using GCM. GCM signs the encrypted message with a hash and checks to verify that the message has not been changed using this signature.

I would avoid implementing GCM because of its complexity. You are better off using Googles new library Tink because here again if you accidentally repeat an IV you are compromising the key in the case with GCM, which is the ultimate security flaw. New researchers are working towards IV repeat resistant encryption modes where even if you repeat the IV the key is not in danger but this has yet to come mainstream.

Now if you do want to implement GCM, here is a link to a nice GCM implementation. However, I can not ensure the security or if its properly implemented but it gets the basis down. Also note with GCM there is no padding.

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

Keys vs Passwords

Another very important note, is that when it comes to cryptography a Key and a Password are not the same things. A Key in cryptography needs to have a certain amount of entropy and randomness to be considered secure. This is why you need to make sure to use the proper cryptographic libraries to generate the key for you.

So you really have two implementations you can do here, the first is to use the code found on this StackOverflow thread for Random Key Generation. This solution uses a secure random number generator to create a key from scratch that you can the use.

The other less secure option is to use, user input such as a password. The issue as we discussed is that the password doesn't have enough entropy, so we would have to use PBKDF2, an algorithm that takes the password and strengthens it. Here is a StackOverflow implementation I liked. However Google Tink library has all this built in and you should take advantage of it.

Android Developers

One important point to point out here is know that your android code is reverse engineerable and most cases most java code is too. That means if you store the password in plain text in your code. A hacker can easily retrieve it. Usually, for these type of encryption, you want to use Asymmetric Cryptography and so on. This is outside the scope of this post so I will avoid diving into it.

An interesting reading from 2013: Points out that 88% of Crypto implementations in Android were done improperly.

Final Thoughts

Once again I would suggest avoid implementing the java library for crypto directly and use Google Tink, it will save you the headache as they have really done a good job of implementing all the algorithms properly. And even then make sure you check up on issues brought up on the Tink github, vulnerabilities popup here and there.

If you have any questions or feedback feel free to comment! Security is always changing and you need to do your best to keep up with it :)

Using IF ELSE statement based on Count to execute different Insert statements

Not very clear what you mean by

"I cant find any examples to help me understand how I can use this to run 2 different statements:"

. Is it using CASE like a SWITCH you are after?

select case when totalCount >= 0 and totalCount < 11 then '0-10'
            when tatalCount > 10 and totalCount < 101 then '10-100'
            else '>100' end as newColumn
from (
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) A

How to compare binary files to check if they are the same?

md5sum binary1 binary2

If the md5sum is same, binaries are same

E.g

md5sum new*
89c60189c3fa7ab5c96ae121ec43bd4a  new.txt
89c60189c3fa7ab5c96ae121ec43bd4a  new1.txt
root@TinyDistro:~# cat new*
aa55 aa55 0000 8010 7738
aa55 aa55 0000 8010 7738


root@TinyDistro:~# cat new*
aa55 aa55 000 8010 7738
aa55 aa55 0000 8010 7738
root@TinyDistro:~# md5sum new*
4a7f86919d4ac00c6206e11fca462c6f  new.txt
89c60189c3fa7ab5c96ae121ec43bd4a  new1.txt

How to Compare two Arrays are Equal using Javascript?

var array3 = array1 === array2

That will compare whether array1 and array2 are the same array object in memory, which is not what you want.

In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.

Assuming your array is filled with primitives—numbers and or strings—something like this should do

function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true; 
}

Expand div to max width when float:left is set

This is an updated solution for HTML 5 if anyone is interested & not fond of "floating".

Table works great in this case as you can set the fixed width to the table & table-cell.

.content-container{
    display: table;
    width: 300px;
}

.content .right{
    display: table-cell;   
    background-color:green;
    width: 100px;
}

http://jsfiddle.net/EAEKc/596/ original source code from @merkuro

Docker - Cannot remove dead container

Most likely, an error occurred when the daemon attempted to cleanup the container, and he is now stuck in this "zombie" state.

I'm afraid your only option here is to manually clean it up:

$ sudo rm -rf /var/lib/docker/<storage_driver>/11667ef16239.../

Where <storage_driver> is the name of your driver (aufs, overlay, btrfs, or devicemapper).

List vs tuple, when to use each?

Must it be mutable? Use a list. Must it not be mutable? Use a tuple.

Otherwise, it's a question of choice.

For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.

Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.

Why is the time complexity of both DFS and BFS O( V + E )

It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).

Remove json element

Do NOT have trailing commas in your OBJECT (JSON is a string notation)

UPDATE: you need to use array.splice and not delete if you want to remove items from the array in the object. Alternatively filter the array for undefined after removing

_x000D_
_x000D_
var data = {
  "result": [{
    "FirstName": "Test1",
    "LastName": "User"
  }, {
    "FirstName": "user",
    "LastName": "user"
  }]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.


data = {
  "result": [{
    "FirstName": "Test1",
    "LastName": "User"
  }, {
    "FirstName": "user",
    "LastName": "user"
  }]
}

console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.
_x000D_
_x000D_
_x000D_

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

WCF Service, the type provided as the service attribute values…could not be found

Right click on the .svc file in Solution Explorer and click View Markup

 <%@ ServiceHost Language="C#" Debug="true" 
     Service="MyService.**GetHistoryInfo**" 
     CodeBehind="GetHistoryInfo.svc.cs" %>

Update the service reference where you are referring to.

How can I view an old version of a file with Git?

You can use git show with a path from the root of the repository (./ or ../ for relative pathing):

$ git show REVISION:path/to/file

Replace REVISION with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)

For example, to view the version of file <repository-root>/src/main.c from 4 commits ago, use:

$ git show HEAD~4:src/main.c

Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show.

How can I echo HTML in PHP?

Try it like this (heredoc syntax):

$variable = <<<XYZ
<html>
<body>

</body>
</html>
XYZ;
echo $variable;

Get value from text area

Use .val() to get value of textarea and use $.trim() to empty spaces.

$(document).ready(function () {
    if ($.trim($("textarea").val()) != "") {
        alert($("textarea").val());
    }
});

Or, Here's what I would do for clean code,

$(document).ready(function () {
    var val = $.trim($("textarea").val());
    if (val != "") {
        alert(val);
    }
});

Demo: http://jsfiddle.net/jVUsZ/

How do I restart a service on a remote machine in Windows?

I would suggest you to have a look at RSHD

You do not need to bother for a client, Windows has it by default.

Where should I put <script> tags in HTML markup?

The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page.

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:

There are some great slides by Steve Souders (client-side performance expert) about:

  • Different techniques to load external JavaScript files in parallel
  • their effect on loading time and page rendering
  • what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).

How to get the current time in Google spreadsheet using script editor?

use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)

function myFunction() {
  var d = new Date();
  var timeStamp = d.getTime();  // Number of ms since Jan 1, 1970

  // OR:

  var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}

How to disable Django's CSRF validation?

@WoooHaaaa some third party packages use 'django.middleware.csrf.CsrfViewMiddleware' middleware. for example i use django-rest-oauth and i have problem like you even after disabling those things. maybe these packages responded to your request like my case, because you use authentication decorator and something like this.

How to test an Internet connection with bash?

Pong doesn't mean web service on the server is running; it merely means that server is replying to ICMP echo. I would recommend using curl and check its return value.

How to Correctly Check if a Process is running and Stop it

If you don't need to display exact result "running" / "not runnuning", you could simply:

ps notepad -ErrorAction SilentlyContinue | kill -PassThru

If the process was not running, you'll get no results. If it was running, you'll receive get-process output, and the process will be stopped.

How to return multiple objects from a Java method?

As I see it there are really three choices here and the solution depends on the context. You can choose to implement the construction of the name in the method that produces the list. This is the choice you've chosen, but I don't think it is the best one. You are creating a coupling in the producer method to the consuming method that doesn't need to exist. Other callers may not need the extra information and you would be calculating extra information for these callers.

Alternatively, you could have the calling method calculate the name. If there is only one caller that needs this information, you can stop there. You have no extra dependencies and while there is a little extra calculation involved, you've avoided making your construction method too specific. This is a good trade-off.

Lastly, you could have the list itself be responsible for creating the name. This is the route I would go if the calculation needs to be done by more than one caller. I think this puts the responsibility for the creation of the names with the class that is most closely related to the objects themselves.

In the latter case, my solution would be to create a specialized List class that returns a comma-separated string of the names of objects that it contains. Make the class smart enough that it constructs the name string on the fly as objects are added and removed from it. Then return an instance of this list and call the name generation method as needed. Although it may be almost as efficient (and simpler) to simply delay calculation of the names until the first time the method is called and store it then (lazy loading). If you add/remove an object, you need only remove the calculated value and have it get recalculated on the next call.

How can I get the client's IP address in ASP.NET MVC?

A lot of the code here was very helpful, but I cleaned it up for my purposes and added some tests. Here's what I ended up with:

using System;
using System.Linq;
using System.Net;
using System.Web;

public class RequestHelpers
{
    public static string GetClientIpAddress(HttpRequestBase request)
    {
        try
        {
            var userHostAddress = request.UserHostAddress;

            // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
            // Could use TryParse instead, but I wanted to catch all exceptions
            IPAddress.Parse(userHostAddress);

            var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(xForwardedFor))
                return userHostAddress;

            // Get a list of public ip addresses in the X_FORWARDED_FOR variable
            var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

            // If we found any, return the last one, otherwise return the user host address
            return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
        }
        catch (Exception)
        {
            // Always return all zeroes for any failure (my calling code expects it)
            return "0.0.0.0";
        }
    }

    private static bool IsPrivateIpAddress(string ipAddress)
    {
        // http://en.wikipedia.org/wiki/Private_network
        // Private IP Addresses are: 
        //  24-bit block: 10.0.0.0 through 10.255.255.255
        //  20-bit block: 172.16.0.0 through 172.31.255.255
        //  16-bit block: 192.168.0.0 through 192.168.255.255
        //  Link-local addresses: 169.254.0.0 through 169.254.255.255 (http://en.wikipedia.org/wiki/Link-local_address)

        var ip = IPAddress.Parse(ipAddress);
        var octets = ip.GetAddressBytes();

        var is24BitBlock = octets[0] == 10;
        if (is24BitBlock) return true; // Return to prevent further processing

        var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
        if (is20BitBlock) return true; // Return to prevent further processing

        var is16BitBlock = octets[0] == 192 && octets[1] == 168;
        if (is16BitBlock) return true; // Return to prevent further processing

        var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
        return isLinkLocalAddress;
    }
}

And here are some NUnit tests against that code (I'm using Rhino Mocks to mock the HttpRequestBase, which is the M<HttpRequestBase> call below):

using System.Web;
using NUnit.Framework;
using Rhino.Mocks;
using Should;

[TestFixture]
public class HelpersTests : TestBase
{
    HttpRequestBase _httpRequest;

    private const string XForwardedFor = "X_FORWARDED_FOR";
    private const string MalformedIpAddress = "MALFORMED";
    private const string DefaultIpAddress = "0.0.0.0";
    private const string GoogleIpAddress = "74.125.224.224";
    private const string MicrosoftIpAddress = "65.55.58.201";
    private const string Private24Bit = "10.0.0.0";
    private const string Private20Bit = "172.16.0.0";
    private const string Private16Bit = "192.168.0.0";
    private const string PrivateLinkLocal = "169.254.0.0";

    [SetUp]
    public void Setup()
    {
        _httpRequest = M<HttpRequestBase>();
    }

    [TearDown]
    public void Teardown()
    {
        _httpRequest = null;
    }

    [Test]
    public void PublicIpAndNullXForwardedFor_Returns_CorrectIp()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void PublicIpAndEmptyXForwardedFor_Returns_CorrectIp()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(string.Empty);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MalformedUserHostAddress_Returns_DefaultIpAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(MalformedIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(DefaultIpAddress);
    }

    [Test]
    public void MalformedXForwardedFor_Returns_DefaultIpAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MalformedIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(DefaultIpAddress);
    }

    [Test]
    public void SingleValidPublicXForwardedFor_Returns_XForwardedFor()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MicrosoftIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }

    [Test]
    public void MultipleValidPublicXForwardedFor_Returns_LastXForwardedFor()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(GoogleIpAddress + "," + MicrosoftIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }

    [Test]
    public void SinglePrivateXForwardedFor_Returns_UserHostAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(Private24Bit);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MultiplePrivateXForwardedFor_Returns_UserHostAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        const string privateIpList = Private24Bit + "," + Private20Bit + "," + Private16Bit + "," + PrivateLinkLocal;
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MultiplePublicXForwardedForWithPrivateLast_Returns_LastPublic()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        const string privateIpList = Private24Bit + "," + Private20Bit + "," + MicrosoftIpAddress + "," + PrivateLinkLocal;
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }
}

How to make HTTP Post request with JSON body in Swift

Perfect nRewik answer updated to 2019:

Make the dictionary:

let dic = [
    "username":u,
    "password":p,
    "gems":g ]

Assemble it like this:

var jsonData:Data?
do {
    jsonData = try JSONSerialization.data(
      withJSONObject: dic,
      options: .prettyPrinted)
} catch {
    print(error.localizedDescription)
}

Create the request exactly like this, notice it is a "post"

let url = URL(string: "https://blah.com/server/dudes/decide/this")!
var request = URLRequest(url: url)

request.setValue("application/json; charset=utf-8",
     forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8",
     forHTTPHeaderField: "Accept") 
request.httpMethod = "POST"
request.httpBody = jsonData

Then send, checking for either a networking error (so, no bandwidth etc) or an error response from the server:

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        // check for fundamental networking error
        print("fundamental networking error=\(error)")
        return
    }

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
        // check for http errors
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(response)")
    }

    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString)")

Fortunately it's now that easy.

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

In a unix shell, how to get yesterday's date into a variable?

You have atleast 2 options

  1. Use perl:

    perl -e '@T=localtime(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],$T[5]+1900)'
    
  2. Install GNU date (it's in the sh_utils package if I remember correctly)

    date --date yesterday "+%a %d/%m/%Y" | read dt
    echo ${dt}
    
  3. Not sure if this works, but you might be able to use a negative timezone. If you use a timezone that's 24 hours before your current timezone than you can simply use date.

Android check null or empty string in Android

From @Jon Skeet comment, really the String value is "null". Following code solved it

if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null")) 

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.

public static void RemoveEverythingButUserInfo()
{
    foreach (String o in HttpContext.Current.Session.Keys)
    {
        if (o != "UserInfoIDontWantToAskForAgain")
            keys.Add(o);
    }
}

store and retrieve a class object in shared preference

Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple. you can save most of the commonly used objects with it like arrays, integer, strings lists etc

Using variables inside a bash heredoc

As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.

Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE

Demo: https://ideone.com/rMF2XA

Note that any of the quoting mechanisms -- \____HERE or "____HERE" or '____HERE' -- will disable all variable interpolation, and turn the here-document into a piece of literal text.

A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.

local=$(uname)
ssh -t remote <<:
    echo "$local is the value from the host which ran the ssh command"
    # Prevent here doc from expanding locally; remote won't see backslash
    remote=\$(uname)
    # Same here
    echo "\$remote is the value from the host we ssh:ed to"
:

error: unknown type name ‘bool’

Just add the following:

#define __USE_C99_MATH

#include <stdbool.h>

Making button go full-width?

I would have thought this would be the most bootstrap-esque way of doing things:

<button type='button' class='btn btn-success col-xs-12'> First buttton baby </button>

All I'm doing is adding the class col-xs-12 to the button.

With ng-bind-html-unsafe removed, how do I inject HTML?

Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind. This is an unsafe option, but helpful when testing.

Example from the AngularJS documentation on $sce:

angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);
});

Attaching the above config section to your app will allow you inject html into ng-html-bind, but as the doc remarks:

SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.

Command line: search and replace in all filenames matched by grep

The answer already given of using find and sed

find -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;

is probably the standard answer. Or you could use perl -pi -e s/foo/bar/g' instead of the sed command.

For most quick uses, you may find the command rpl is easier to remember. Here is replacement (foo -> bar), recursively on all files in the current directory:

rpl -R foo bar .

It's not available by default on most Linux distros but is quick to install (apt-get install rpl or similar).

However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:

  • Support renaming of files as well as search-and-replace on file contents (including moving files between directories and creating new parent directories).
  • See changes before you commit to performing the search and replace.
  • Support regular expressions with back substitution, whole words, case insensitive, and case preserving (replace foo -> bar, Foo -> Bar, FOO -> BAR) modes.
  • Works with multiple replacements, including swaps (foo -> bar and bar -> foo) or sets of non-unique replacements (foo -> bar, f -> x).

Check the README for examples.

Converting pixels to dp

More elegant approach using kotlin's extension function

/**
 * Converts dp to pixel
 */
val Int.dpToPx: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt()

/**
 * Converts pixel to dp
 */
val Int.pxToDp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt()

Usage:

println("16 dp in pixel: ${16.dpToPx}")
println("16 px in dp: ${16.pxToDp}")

Check if file exists and whether it contains a specific string

If you have the test binary installed or ksh has a matching built-in function, you could use it to perform your checks. Usually /bin/[ is a symbolic link to test:

if [ -e "$file_name" ]; then
  echo "File exists"
fi

if [ -z "$used_var" ]; then
  echo "Variable is empty"
fi

How to add a new line of text to an existing file in Java?

Try: "\r\n"

Java 7 example:

// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true))) 
{
    output.printf("%s\r\n", "NEWLINE");
} 
catch (Exception e) {}

Remove x-axis label/text in chart.js

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

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

How to change Format of a Cell to Text using VBA

for large numbers that display with scientific notation set format to just '#'

Difference between HashMap, LinkedHashMap and TreeMap

Following are major difference between HashMap and TreeMap

  1. HashMap does not maintain any order. In other words , HashMap does not provide any guarantee that the element inserted first will be printed first, where as Just like TreeSet , TreeMap elements are also sorted according to the natural ordering of its elements

  2. Internal HashMap implementation use Hashing and TreeMap internally uses Red-Black tree implementation.

  3. HashMap can store one null key and many null values.TreeMap can not contain null keys but may contain many null values.

  4. HashMap take constant time performance for the basic operations like get and put i.e O(1).According to Oracle docs , TreeMap provides guaranteed log(n) time cost for the get and put method.

  5. HashMap is much faster than TreeMap, as performance time of HashMap is constant against the log time TreeMap for most operations.

  6. HashMap uses equals() method in comparison while TreeMap uses compareTo() method for maintaining ordering.

  7. HashMap implements Map interface while TreeMap implements NavigableMap interface.

Eclipse Build Path Nesting Errors

For Eclipse compiler to work properly you need to remove final/src from the source path and add final/src/main/java instead. This may also solve your problem as now the build directory won't be inside the Java source folder.

Is it possible to create a File object from InputStream

Create a temp file first.

File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
return tempFile;

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

It's a bit of a guess but could the quotes around happy be the problem? There have been some problems in the past where Android would either add or not recognize quotes around an SSID. Try setting up the hosted network connection again, but without the quotes that we see in the output for netsh wlan show hostednetwork.

libstdc++.so.6: cannot open shared object file: No such file or directory

For Fedora use:

yum install libstdc++44.i686

You can find out which versions are supported by running:

yum list all | grep libstdc | grep i686

Understanding lambda in python and using it to pass multiple arguments

Why do you need to state both 'x' and 'y' before the ':'?

Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to

def f(x, y) : return x + y

just without binding it to a name like f.

Also how do you make it return multiple arguments?

The same way like with a function. Preferably, you return a tuple:

lambda x, y: (x+y, x-y)

Or a list, or a class, or whatever.

The thing with self.entry_1.bind should be answered by Demosthenex.

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

Excel VBA Password via Hex Editor

If you deal with .xlsm file instead of .xls you can use the old method. I was trying to modify vbaProject.bin in .xlsm several times using DBP->DBx method by it didn't work, also changing value of DBP didn't. So I was very suprised that following worked :
1. Save .xlsm as .xls.
2. Use DBP->DBx method on .xls.
3. Unfortunately some erros may occur when using modified .xls file, I had to save .xls as .xlsx and add modules, then save as .xlsm.

How to store Query Result in variable using mysql

Surround that select with parentheses.

SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;

linux: kill background task

this is an out of topic answer, but, for those who are interested, it maybe valuable.

As in @John Kugelman's answer, % is related to job specification. how to efficiently find that? use less's &pattern command, seems man use less pager (not that sure), in man bash type &% then type Enter will only show lines that containing '%', to reshow all, type &. then Enter.

Remove multiple items from a Python list in just one statement

You can use filterfalse function from itertools module

Example

import random
from itertools import filterfalse

random.seed(42)

data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")


clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")

Output:

Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]

Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]

Invariant Violation: Objects are not valid as a React child

In case of using Firebase, if it doesn't work by putting at the end of import statements then you can try to put that inside one of the life-cycle method, that is, you can put it inside componentWillMount().

componentWillMount() {
    const firebase = require('firebase');
    firebase.initializeApp({
        //Credentials
    });
}

Python print statement “Syntax Error: invalid syntax”

Use print("use this bracket -sample text")

In Python 3 print "Hello world" gives invalid syntax error.

To display string content in Python3 have to use this ("Hello world") brackets.

Executing JavaScript without a browser?

I know this is old but you should also try Zombie.js. A headless browser which is insanely fast and ideal for testing !

Jquery change <p> text programmatically

"saving" is something wholly different from changing paragraph content with jquery.

If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").

Judging by your question, this is a topic on which you will have to do MUCH more research.

Input page (input.html):

<form action="/saveMyParagraph.php">
    <input name="pContent" type="text"></input>
</form>

Saving page (saveMyParagraph.php) and Ouput page (output.php):

Inserting Data Into a MySQL Database using PHP

Bash: Echoing a echo command with a variable in bash

echo "echo "we are now going to work with ${ser}" " >> $servfile

Escape all " within quotes with \. Do this with variables like \$servicetest too:

echo "echo \"we are now going to work with \${ser}\" " >> $servfile    
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

For downloading pdf from server , add below code in your service class. Hope this is helpful for you.

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName + ".pdf");
    intent = new Intent(Intent.ACTION_VIEW);
    //Log.e("pathOpen", file.getPath());

    Uri contentUri;
    contentUri = Uri.fromFile(file);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

    if (Build.VERSION.SDK_INT >= 24) {

        Uri apkURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
        intent.setDataAndType(apkURI, "application/pdf");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    } else {

        intent.setDataAndType(contentUri, "application/pdf");
    }

And yes , don't forget to add permissions and provider in your manifest.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

</application>

Multiple inputs with same name through POST in php

For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.

The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval] (string or int) which then allows you to refer to an existing record.

Declare an array in TypeScript

Few ways of declaring a typed array in TypeScript are

const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];

// or, if you have values to initialize 
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

On *nix, unlike Windows, the current directory is usually not in your $PATH variable. So the current directory is not searched when executing commands. You don't need ./ for running applications because these applications are in your $PATH; most likely they are in /bin or /usr/bin.

View's SELECT contains a subquery in the FROM clause

As per documentation:

MySQL Docs

  • The SELECT statement cannot contain a subquery in the FROM clause.

Your workaround would be to create a view for each of your subqueries.

Then access those views from within your view view_credit_status

What is the difference between signed and unsigned int

In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.

OpenCV !_src.empty() in function 'cvtColor' error

Another thing which might be causing this is a 'weird' symbol in your file and directory names. All umlaut (äöå) and other (éóâ etc) characters should be removed from the file and folder names. I've had this same issue sometimes because of these characters.

How do you load custom UITableViewCells from Xib files?

Here is my method for that: Loading Custom UITableViewCells from XIB Files… Yet Another Method

The idea is to create a SampleCell subclass of the UITableViewCell with a IBOutlet UIView *content property and a property for each custom subview you need to configure from the code. Then to create a SampleCell.xib file. In this nib file, change the file owner to SampleCell. Add a content UIView sized to fit your needs. Add and configure all the subviews (label, image views, buttons, etc) you want. Finally, link the content view and the subviews to the file owner.

switch() statement usage

Well, timing to the rescue again. It seems switch is generally faster than if statements. So that, and the fact that the code is shorter/neater with a switch statement leans in favor of switch:

# Simplified to only measure the overhead of switch vs if

test1 <- function(type) {
 switch(type,
        mean = 1,
        median = 2,
        trimmed = 3)
}

test2 <- function(type) {
 if (type == "mean") 1
 else if (type == "median") 2
 else if (type == "trimmed") 3
}

system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs

Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:

> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
           expr  min   lq median   uq      max
1 test1("mean")  709  771    864  951 16122411
2 test2("mean") 1007 1073   1147 1223  8012202

> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
              expr  min   lq median   uq      max
1 test1("trimmed")  733  792    843  944 60440833
2 test2("trimmed") 2022 2133   2203 2309 60814430

Final Update Here's showing how versatile switch is:

switch(type, case1=1, case2=, case3=2.5, 99)

This maps case2 and case3 to 2.5 and the (unnamed) default to 99. For more information, try ?switch

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

I'd recommend reading that PEP the error gives you. The problem is that your code is trying to use the ASCII encoding, but the pound symbol is not an ASCII character. Try using UTF-8 encoding. You can start by putting # -*- coding: utf-8 -*- at the top of your .py file. To get more advanced, you can also define encodings on a string by string basis in your code. However, if you are trying to put the pound sign literal in to your code, you'll need an encoding that supports it for the entire file.

SQL Insert Query Using C#

private void button1_Click(object sender, EventArgs e)
    {
        String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
        try
        {
            using (SqlCommand command = new SqlCommand(query, con))
            {

                command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
                command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
                command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
                command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);


                con.Open();
                int result = command.ExecuteNonQuery();

                // Check Error
                if (result < 0)
                    MessageBox.Show("Error");

                MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                con.Close();
                loader();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            con.Close();
        }
    }

When is the @JsonProperty property used and what is it used for?

Here's a good example. I use it to rename the variable because the JSON is coming from a .Net environment where properties start with an upper-case letter.

public class Parameter {
  @JsonProperty("Name")
  public String name;
  @JsonProperty("Value")
  public String value; 
}

This correctly parses to/from the JSON:

"Parameter":{
  "Name":"Parameter-Name",
  "Value":"Parameter-Value"
}

How to press back button in android programmatically?

you can simply use onBackPressed();

or if you are using fragment you can use getActivity().onBackPressed()

How to set top position using jquery

And with Prototype:

$('yourDivId').setStyle({top: '100px', left:'80px'});

How to open Console window in Eclipse?

I also deleted my eclipse console by mistake, however what worked best for me was to type "console" in the "Quick Access" box to the right of the menu and that brought it right back! I'm running version 4.2.1, not sure if this Quick Accessbox is available in other versions.

Plotting multiple time series on the same plot using ggplot()

This is old, just update new tidyverse workflow not mentioned above.

library(tidyverse)

jobsAFAM1 <- tibble(
    date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
    Percent.Change = runif(5, 0,1)
    ) %>% 
    mutate(serial='jobsAFAM1')
jobsAFAM2 <- tibble(
    date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
    Percent.Change = runif(5, 0,1)
    ) %>% 
    mutate(serial='jobsAFAM2')
jobsAFAM <- bind_rows(jobsAFAM1, jobsAFAM2)

ggplot(jobsAFAM, aes(x=date, y=Percent.Change, col=serial)) + geom_line()

@Chris Njuguna

tidyr::gather() is the one in tidyverse workflow to turn wide dataframe to long tidy layout, then ggplot could plot multiple serials.

gather

Detect Safari using jQuery

    // Safari uses pre-calculated pixels, so use this feature to detect Safari
    var canva = document.createElement('canvas');
    var ctx = canva.getContext("2d");
    var img = ctx.getImageData(0, 0, 1, 1);
    var pix = img.data;     // byte array, rgba
    var isSafari = (pix[3] != 0);   // alpha in Safari is not zero

HTML: can I display button text in multiple lines?

Yes it is, and you can also use it like this

<button>Click here to<br/> start playing</button>

if you want to make the break yourself.

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

Refreshing data in RecyclerView and keeping its scroll position

I have quite similar problem. And I came up with following solution.

Using notifyDataSetChanged is a bad idea. You should be more specific, then RecyclerView will save scroll state for you.

For example, if you only need to refresh, or in other words, you want each view to be rebinded, just do this:

adapter.notifyItemRangeChanged(0, adapter.getItemCount());

Decimal or numeric values in regular expression validation

I had the same problem, but I also wanted ".25" to be a valid decimal number. Here is my solution using JavaScript:

function isNumber(v) {
  // [0-9]* Zero or more digits between 0 and 9  (This allows .25 to be considered valid.)
  // ()? Matches 0 or 1 things in the parentheses.  (Allows for an optional decimal point)
  // Decimal point escaped with \.
  // If a decimal point does exist, it must be followed by 1 or more digits [0-9]
  // \d and [0-9] are equivalent 
  // ^ and $ anchor the endpoints so tthe whole string must match.
  return v.trim().length > 0 && v.trim().match(/^[0-9]*(\.[0-9]+)?$/);
}

Where my trim() method is

String.prototype.trim = function() {
  return this.replace(/(^\s*|\s*$)/g, "");
};

Matthew DesVoigne

How to use gitignore command in git

There is a file in your git root directory named .gitignore. It's a file, not a command. You just need to insert the names of the files that you want to ignore, and they will automatically be ignored. For example, if you wanted to ignore all emacs autosave files, which end in ~, then you could add this line:

*~

If you want to remove the unwanted files from your branch, you can use git add -A, which "removes files that are no longer in the working tree".

Note: What I called the "git root directory" is simply the directory in which you used git init for the first time. It is also where you can find the .git directory.

UILabel with text of two different colors

extension UILabel{

    func setSubTextColor(pSubString : String, pColor : UIColor){


        let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!);


        let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
        if range.location != NSNotFound {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
        }
        self.attributedText = attributedString

    }
}

Why extend the Android Application class?

Introduction:

enter image description here

  1. If we consider an apk file in our mobile, it is comprised of multiple useful blocks such as, Activitys, Services and others.
  2. These components do not communicate with each other regularly and not forget they have their own life cycle. which indicate that they may be active at one time and inactive the other moment.

Requirements:

  1. Sometimes we may require a scenario where we need to access a variable and its states across the entire Application regardless of the Activity the user is using,
  2. An example is that a user might need to access a variable that holds his personnel information (e.g. name) that has to be accessed across the Application,
  3. We can use SQLite but creating a Cursor and closing it again and again is not good on performance,
  4. We could use Intents to pass the data but it's clumsy and activity itself may not exist at a certain scenario depending on the memory-availability.

Uses of Application Class:

  1. Access to variables across the Application,
  2. You can use the Application to start certain things like analytics etc. since the application class is started before Activitys or Servicess are being run,
  3. There is an overridden method called onConfigurationChanged() that is triggered when the application configuration is changed (horizontal to vertical & vice-versa),
  4. There is also an event called onLowMemory() that is triggered when the Android device is low on memory.

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

Press Ctrl + Alt + S then choose Keymap and finally find the keyboard shortcut by type back word in search bar at the top right corner.

How to edit .csproj file

The CSPROJ file, saved in XML format, stores all the references for your project including your compilation options. There is also an SLN file, which stores information about projects that make up your solution.

If you are using Visual Studio and you have the need to view or edit your CSPROJ file, while in Visual Studio, you can do so by following these simple steps:

  1. Right-click on your project in solution explorer and select Unload Project
  2. Right-click on the project (tagged as unavailable in solution explorer) and click "Edit yourproj.csproj". This will open up your CSPROJ file for editing.
  3. After making the changes you want, save, and close the file. Right-click again on the node and choose Reload Project when done.

How do I clear my Jenkins/Hudson build history?

Deleting directly from file system is not safe. You can run the below script to delete all builds from all jobs ( recursively ).

def numberOfBuildsToKeep = 10
Jenkins.instance.getAllItems(AbstractItem.class).each {
  if( it.class.toString() != "class com.cloudbees.hudson.plugins.folder.Folder" && it.class.toString() != "class org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject") {
    println it.name
    builds = it.getBuilds()
    for(int i = numberOfBuildsToKeep; i < builds.size(); i++) {
        builds.get(i).delete()
      println "Deleted" + builds.get(i)
    }
  }
}

Convert unix time to readable date in pandas dataframe

If you try using:

df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))

and receive an error :

"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"

This means the DATE_FIELD is not specified in seconds.

In my case, it was milli seconds - EPOCH time.

The conversion worked using below:

df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms')) 

Two HTML tables side by side, centered on the page

The problem is that the DIV that should center your tables has no width defined. By default, DIVs are block elements and take up the entire width of their parent - in this case the entire document (propagating through the #outer DIV), so the automatic margin style has no effect.

For this technique to work, you simply have to set the width of the div that has margin:auto to anything but "auto" or "inherit" (either a fixed pixel value or a percentage).

How to strip all whitespace from string

If optimal performance is not a requirement and you just want something dead simple, you can define a basic function to test each character using the string class's built in "isspace" method:

def remove_space(input_string):
    no_white_space = ''
    for c in input_string:
        if not c.isspace():
            no_white_space += c
    return no_white_space

Building the no_white_space string this way will not have ideal performance, but the solution is easy to understand.

>>> remove_space('strip my spaces')
'stripmyspaces'

If you don't want to define a function, you can convert this into something vaguely similar with list comprehension. Borrowing from the top answer's join solution:

>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'

LIKE vs CONTAINS on SQL Server

The second (assuming you means CONTAINS, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.

The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.


The CONTAINS query should be:

SELECT * FROM table WHERE CONTAINS(Column, 'test');

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

jEdit:

With the keyboard: press Alt-\ (Opt-\ in Mac OS X) to toggle between rectangular and normal selection mode; then use Shift plus arrow keys to extend selection. You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.

With the mouse: Either use Alt-\ (Opt-\ in Mac OS X) as above to toggle rectangular selection mode, then drag as usual; or Ctrl-drag (Cmd-drag in Mac OS X). You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.

Actually, you can even make a non-rectangular selection the normal way and then hit Alt-\ (Opt-\ in Mac OS X) to convert it into a rectangular one.

R - Concatenate two dataframes?

You want "rbind".

b$b <- NA
new <- rbind(a, b)

rbind requires the data frames to have the same columns.

The first line adds column b to data frame b.

Results

> a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
> a
  a b c
1 0 3 6
2 1 4 7
3 2 5 8
> b <- data.frame(a=c(9,10,11), c=c(12,13,14))
> b
   a  c
1  9 12
2 10 13
3 11 14
> b$b <- NA
> b
   a  c  b
1  9 12 NA
2 10 13 NA
3 11 14 NA
> new <- rbind(a,b)
> new
   a  b  c
1  0  3  6
2  1  4  7
3  2  5  8
4  9 NA 12
5 10 NA 13
6 11 NA 14

How to chain scope queries with OR instead of AND?

the squeel gem provides an incredibly easy way to accomplish this (prior to this I used something like @coloradoblue's method):

names = ["Kroger", "Walmart", "Target", "Aldi"]
matching_stores = Grocery.where{name.like_any(names)}

Running ASP.Net on a Linux based server

Now a days .Net is run in multiple platforms,like linux ,Mac os etc. but mono is not fully platform independent ,Because to deploy .NET in another OS required third party software.so it is not like java platform independent.

Mono is running in different platform ,because of JIT is there in different os.

Mono is not fully success in moonlight(silver light in .NET) .Not only Research is going on.

Mono uses XSP2 server or apache . some of the big companies are using this project,Some of the robotic project are also running on mono.

For more details http://www.mono-project.com/Main_Page.

Check if a value is an object in JavaScript

underscore.js provides the following method to find out if something is really an object:

_.isObject = function(obj) {
  return obj === Object(obj);
};

UPDATE

Because of a previous bug in V8 and minor micro speed optimization, the method looks as follows since underscore.js 1.7.0 (August 2014):

_.isObject = function(obj) {
  var type = typeof obj;
  return type === 'function' || type === 'object' && !!obj;
};

Rename a column in MySQL

From MySQL 5.7 Reference Manual.

Syntax :

ALTER TABLE t1 CHANGE a b DATATYPE;

e.g. : for Customer TABLE having COLUMN customer_name, customer_street, customercity.

And we want to change customercity TO customer_city :

alter table customer change customercity customer_city VARCHAR(225);

Detect backspace and del on "input" event?

It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:

document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
    if (e.inputType == "deleteContentBackward") {
        // your code here
    }
});