Programs & Examples On #Ones complement

Change Screen Orientation programmatically using a Button

Yes, you can set the screen orientation programatically anytime you want using:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.

And this is how you can get the current screen orientation and set it adequatly depending on its current state:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
final int orientation = display.getOrientation(); 
 // OR: orientation = getRequestedOrientation(); // inside an Activity

// set the screen orientation on button click
Button btn = (Button) findViewById(R.id.yourbutton);
btn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {

              switch(orientation) {
                   case Configuration.ORIENTATION_PORTRAIT:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                       break;
                   case Configuration.ORIENTATION_LANDSCAPE:
                       setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                       break;                   
               }
          }
   });

Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/

EDIT

Also, you can get the screen orientation using the Configuration:

Activity.getResources().getConfiguration().orientation

Recommended add-ons/plugins for Microsoft Visual Studio

I use a lot the Fogbguz plug in but well you need to use Fogbugz first !!!

Oracle client and networking components were not found

1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to

 F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3\lib;F:\oracle\product\10.2.0\db_2\sysman\admin\scripts;

change your drive and folder depending on your requirement...

How to specify a port number in SQL Server connection string?

For JDBC the proper format is slightly different and as follows:

jdbc:microsoft:sqlserver://mycomputer.test.xxx.com:49843

Note the colon instead of the comma.

Create JPA EntityManager without persistence.xml configuration file

You can also get an EntityManager using PersistenceContext or Autowired annotation, but be aware that it will not be thread-safe.

@PersistenceContext
private EntityManager entityManager;

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I've ran into the same problem. The question here is that play-java-jpa artifact (javaJpa key in the build.sbt file) depends on a different version of the spec (version 2.0 -> "org.hibernate.javax.persistence" % "hibernate-jpa-2.0-api" % "1.0.1.Final").

When you added hibernate-entitymanager 4.3 this brought the newer spec (2.1) and a different factory provider for the entitymanager. Basically you ended up having both jars in the classpath as transitive dependencies.

Edit your build.sbt file like this and it will temporarily fix you problem until play releases a new version of the jpa plugin for the newer api dependency.

libraryDependencies ++= Seq(
javaJdbc,
javaJpa.exclude("org.hibernate.javax.persistence", "hibernate-jpa-2.0-api"),
"org.hibernate" % "hibernate-entitymanager" % "4.3.0.Final"
)

This is for play 2.2.x. In previous versions there were some differences in the build files.

In Jenkins, how to checkout a project into a specific directory (using GIT)

Furthermore, if in the same Jenkins project we need to checkout several private GitHub repositories into several separate dirs under a project root. How can we do it please?

The Jenkin's Multiple SCMs Plugin has solved the several repositories problem for me very nicely. I have just got working a project build that checks out four different git repos under a common folder. (I'm a bit reluctant to use git super-projects as suggested previously by Lukasz Rzanek, as git is complex enough without submodules.)

Adding a splash screen to Flutter apps

For Android, go to android > app > src > main > res > drawable > launcher_background.xml

Now uncomment this and replace @mipmap/launch_image, with your image location.

<item>
      <bitmap
          android:gravity="center"
          android:src="@mipmap/launch_image" />
</item>

You can change the colour of your screen here -

<item android:drawable="@android:color/white" />

PHP check file extension

  $original_str="this . is . to . find";
  echo "<br/> Position: ". $pos=strrpos($original_str, ".");
  $len=strlen($original_str);
  if($pos >= 0)
  {
    echo "<br/> Extension: ".   substr($original_str,$pos+1,$len-$pos) ;
   } 

What does the M stand for in C# Decimal literal notation?

From C# specifications:

var f = 0f; // float
var d = 0d; // double
var m = 0m; // decimal (money)
var u = 0u; // unsigned int
var l = 0l; // long
var ul = 0ul; // unsigned long

Note that you can use an uppercase or lowercase notation.

How to get key names from JSON using jq

Here's another way of getting a Bash array with the example JSON given by @anubhava in his answer:

arr=($(jq --raw-output 'keys_unsorted | @sh' file.json))

echo ${arr[0]}    # 'Archiver-Version'
echo ${arr[1]}    # 'Build-Id'
echo ${arr[2]}    # 'Build-Jdk'

jQuery rotate/transform

t = setTimeout(function() { rotate(++degree); },65);

and clearTimeout to stop

clearTimeout(t);

I use this with AJAX

success:function(){ clearTimeout(t); }

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

How to secure MongoDB with username and password

The best practice to connect to mongoDB as follow:

  1. After initial installation,

    use admin

  2. Then run the following script to create admin user

    db.createUser(
     {
         user: "YourUserName",
         pwd: "YourPassword",
         roles: [
                   { role: "userAdminAnyDatabase", db: "admin" },
                   { role: "readWriteAnyDatabase", db: "admin" },
                   { role: "dbAdminAnyDatabase", db: "admin" },
                   { role: "clusterAdmin", db: "admin" }
                ]
     })

the following script will create the admin user for the DB.

  1. log into the db.admin using

    mongo -u YourUserName -p YourPassword admin

  2. After login, you can create N number of the database with same admin credential or different by repeating the 1 to 3.

This allows you to create different user and password for the different collection you creating in the MongoDB

Check if String contains only letters

First import Pattern :

import java.util.regex.Pattern;

Then use this simple code:

String s = "smith23";
if (Pattern.matches("[a-zA-Z]+",s)) { 
  // Do something
  System.out.println("Yes, string contains letters only");
}else{
  System.out.println("Nope, Other characters detected");    
}

This will output:

Nope, Other characters detected

String.contains in Java

The obvious answer to this is "that's what the JLS says."

Thinking about why that is, consider that this behavior can be useful in certain cases. Let's say you want to check a string against a set of other strings, but the number of other strings can vary.

So you have something like this:

for(String s : myStrings) {
   check(aString.contains(s));
}

where some s's are empty strings.

If the empty string is interpreted as "no input," and if your purpose here is ensure that aString contains all the "inputs" in myStrings, then it is misleading for the empty string to return false. All strings contain it because it is nothing. To say they didn't contain it would imply that the empty string had some substance that was not captured in the string, which is false.

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

Best way to get hostname with php

What about gethostname()?

Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.

How to load assemblies in PowerShell?

You could use LoadWithPartialName. However, that is deprecated as they said.

You can indeed go along with Add-Type, and in addition to the other answers, if you don't want to specify the full path of the .dll file, you could just simply do:

Add-Type -AssemblyName "Microsoft.SqlServer.Management.SMO"

To me this returned an error, because I do not have SQL Server installed (I guess), however, with this same idea I was able to load the Windows Forms assembly:

Add-Type -AssemblyName "System.Windows.Forms"

You can find out the precise assembly name belonging to the particular class on the MSDN site:

Example of finding out assembly name belonging to a particular class

How do I find out which process is locking a file using .NET?

This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.

C#:

using System.Management; 
using System.IO;   

static class Module1 
{ 
static internal ArrayList myProcessArray = new ArrayList(); 
private static Process myProcess; 

public static void Main() 
{ 

    string strFile = "c:\\windows\\system32\\msi.dll"; 
    ArrayList a = getFileProcesses(strFile); 
    foreach (Process p in a) { 
        Debug.Print(p.ProcessName); 
    } 
} 


private static ArrayList getFileProcesses(string strFile) 
{ 
    myProcessArray.Clear(); 
    Process[] processes = Process.GetProcesses; 
    int i = 0; 
    for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) { 
        myProcess = processes(i); 
        if (!myProcess.HasExited) { 
            try { 
                ProcessModuleCollection modules = myProcess.Modules; 
                int j = 0; 
                for (j = 0; j <= modules.Count - 1; j++) { 
                    if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) { 
                        myProcessArray.Add(myProcess); 
                        break; // TODO: might not be correct. Was : Exit For 
                    } 
                } 
            } 
            catch (Exception exception) { 
            } 
            //MsgBox(("Error : " & exception.Message)) 
        } 
    } 
    return myProcessArray; 
} 
} 

VB.Net:

Imports System.Management
Imports System.IO

Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process

Sub Main()

    Dim strFile As String = "c:\windows\system32\msi.dll"
    Dim a As ArrayList = getFileProcesses(strFile)
    For Each p As Process In a
        Debug.Print(p.ProcessName)
    Next
End Sub


Private Function getFileProcesses(ByVal strFile As String) As ArrayList
    myProcessArray.Clear()
    Dim processes As Process() = Process.GetProcesses
    Dim i As Integer
    For i = 0 To processes.GetUpperBound(0) - 1
        myProcess = processes(i)
        If Not myProcess.HasExited Then
            Try
                Dim modules As ProcessModuleCollection = myProcess.Modules
                Dim j As Integer
                For j = 0 To modules.Count - 1
                    If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
                        myProcessArray.Add(myProcess)
                        Exit For
                    End If
                Next j
            Catch exception As Exception
                'MsgBox(("Error : " & exception.Message))
            End Try
        End If
    Next i
    Return myProcessArray
End Function
End Module

SQLAlchemy ORDER BY DESCENDING?

You can try: .order_by(ClientTotal.id.desc())

session = Session()
auth_client_name = 'client3' 
result_by_auth_client = session.query(ClientTotal).filter(ClientTotal.client ==
auth_client_name).order_by(ClientTotal.id.desc()).all()

for rbac in result_by_auth_client:
    print(rbac.id) 
session.close()

sqlalchemy filter multiple columns

You can simply call filter multiple times:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))

If input value is blank, assign a value of "empty" with Javascript

This can be done using HTML5's placeHolder or using JavaScript. Checkout this post.

When to use %r instead of %s in Python?

The %s specifier converts the object using str(), and %r converts it using repr().

For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

Here's an example, using a date:

>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'

Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

Why use deflate instead of gzip for text files served by Apache?

I think there's no big difference between deflate and gzip, because gzip basically is just a header wrapped around deflate (see RFCs 1951 and 1952).

Counter increment in Bash loop not working

It seems that you didn't update the counter is the script, use counter++

Java 8 NullPointerException in Collectors.toMap

NullPointerException is by far the most frequently encountered exception (at least in my case). To avoid this I go defensive and add bunch of null checks and I end up having bloated and ugly code. Java 8 introduces Optional to handle null references so you can define nullable and non-nullable values.

That said, I would wrap all the nullable references in Optional container. We should also not break backward compatibility as well. Here is the code.

class Answer {
    private int id;
    private Optional<Boolean> answer;

    Answer() {
    }

    Answer(int id, Boolean answer) {
        this.id = id;
        this.answer = Optional.ofNullable(answer);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /**
     * Gets the answer which can be a null value. Use {@link #getAnswerAsOptional()} instead.
     *
     * @return the answer which can be a null value
     */
    public Boolean getAnswer() {
        // What should be the default value? If we return null the callers will be at higher risk of having NPE
        return answer.orElse(null);
    }

    /**
     * Gets the optional answer.
     *
     * @return the answer which is contained in {@code Optional}.
     */
    public Optional<Boolean> getAnswerAsOptional() {
        return answer;
    }

    /**
     * Gets the answer or the supplied default value.
     *
     * @return the answer or the supplied default value.
     */
    public boolean getAnswerOrDefault(boolean defaultValue) {
        return answer.orElse(defaultValue);
    }

    public void setAnswer(Boolean answer) {
        this.answer = Optional.ofNullable(answer);
    }
}

public class Main {
    public static void main(String[] args) {
        List<Answer> answerList = new ArrayList<>();

        answerList.add(new Answer(1, true));
        answerList.add(new Answer(2, true));
        answerList.add(new Answer(3, null));

        // map with optional answers (i.e. with null)
        Map<Integer, Optional<Boolean>> answerMapWithOptionals = answerList.stream()
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswerAsOptional));

        // map in which null values are removed
        Map<Integer, Boolean> answerMapWithoutNulls = answerList.stream()
                .filter(a -> a.getAnswerAsOptional().isPresent())
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswer));

        // map in which null values are treated as false by default
        Map<Integer, Boolean> answerMapWithDefaults = answerList.stream()
                .collect(Collectors.toMap(a -> a.getId(), a -> a.getAnswerOrDefault(false)));

        System.out.println("With Optional: " + answerMapWithOptionals);
        System.out.println("Without Nulls: " + answerMapWithoutNulls);
        System.out.println("Wit Defaults: " + answerMapWithDefaults);
    }
}

Excel date to Unix timestamp

Here's my ultimate answer to this.

Also apparently javascript's new Date(year, month, day) constructor doesn't account for leap seconds too.

// Parses an Excel Date ("serial") into a
// corresponding javascript Date in UTC+0 timezone.
//
// Doesn't account for leap seconds.
// Therefore is not 100% correct.
// But will do, I guess, since we're
// not doing rocket science here.
//
// https://www.pcworld.com/article/3063622/software/mastering-excel-date-time-serial-numbers-networkdays-datevalue-and-more.html
// "If you need to calculate dates in your spreadsheets,
//  Excel uses its own unique system, which it calls Serial Numbers".
//
lib.parseExcelDate = function (excelSerialDate) {
  // "Excel serial date" is just
  // the count of days since `01/01/1900`
  // (seems that it may be even fractional).
  //
  // The count of days elapsed
  // since `01/01/1900` (Excel epoch)
  // till `01/01/1970` (Unix epoch).
  // Accounts for leap years
  // (19 of them, yielding 19 extra days).
  const daysBeforeUnixEpoch = 70 * 365 + 19;

  // An hour, approximately, because a minute
  // may be longer than 60 seconds, see "leap seconds".
  const hour = 60 * 60 * 1000;

  // "In the 1900 system, the serial number 1 represents January 1, 1900, 12:00:00 a.m.
  //  while the number 0 represents the fictitious date January 0, 1900".
  // These extra 12 hours are a hack to make things
  // a little bit less weird when rendering parsed dates.
  // E.g. if a date `Jan 1st, 2017` gets parsed as
  // `Jan 1st, 2017, 00:00 UTC` then when displayed in the US
  // it would show up as `Dec 31st, 2016, 19:00 UTC-05` (Austin, Texas).
  // That would be weird for a website user.
  // Therefore this extra 12-hour padding is added
  // to compensate for the most weird cases like this
  // (doesn't solve all of them, but most of them).
  // And if you ask what about -12/+12 border then
  // the answer is people there are already accustomed
  // to the weird time behaviour when their neighbours
  // may have completely different date than they do.
  //
  // `Math.round()` rounds all time fractions
  // smaller than a millisecond (e.g. nanoseconds)
  // but it's unlikely that an Excel serial date
  // is gonna contain even seconds.
  //
  return new Date(Math.round((excelSerialDate - daysBeforeUnixEpoch) * 24 * hour) + 12 * hour);
};

Generating UNIQUE Random Numbers within a range

You can try next code:

function unique_randoms($min, $max, $count) {

 $arr = array();
 while(count($arr) < $count){
      $tmp =mt_rand($min,$max);
      if(!in_array($tmp, $arr)){
         $arr[] = $tmp;
      }
 }
return $arr;
}

Python 3 ImportError: No module named 'ConfigParser'

I was having the same problem. Turns out, I needed to install python3 devel on my centos. First, you need to search for the package that is compatible with your system.

yum search python3 | grep devel

Then, install the package as:

yum install -y python3-devel.x86_64

Then, install mysqlclient from pip

pip install mysqlclient

Trigger validation of all fields in Angular Form submit

Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.

The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:

$('#formField1, #formField2').trigger('change');

File size exceeds configured limit (2560000), code insight features not available

For the 64-bit 2020 version

I tried in vain to find the current location of this file for version 2020. When navigating to Help > Edit Custom Properties a new (empty) file is created at appData/Roaming/JetBrains/IntelliJIdea2020.1/idea.properties. There is no /bin directory as some tutorials suggest. However, neither adding the block from the accepted answer to this file nor adding the same file to /bin resulted in an update to my configuration.

I finally discovered that a reference to the same property exists in appData/Roaming/JetBrains/IntelliJIdea2020.1/idea64.exe.vmoptions. It looks like this:

-Didea.max.intellisense.filesize=3470

I changed it to this, which should be adequate for my needs:

-Didea.max.intellisense.filesize=9999

This strikes me as a bug in this version where the behavior of the menu item doesn't reflect what's needed, but it may also be the case that my particular setup is somehow different than stock. I do have PyCharm and the JDK installed.

Show data on mouseover of circle

I assume that what you want is a tooltip. The easiest way to do this is to append an svg:title element to each circle, as the browser will take care of showing the tooltip and you don't need the mousehandler. The code would be something like

vis.selectAll("circle")
   .data(datafiltered).enter().append("svg:circle")
   ...
   .append("svg:title")
   .text(function(d) { return d.x; });

If you want fancier tooltips, you could use tipsy for example. See here for an example.

Global keyboard capture in C# application

If a global hotkey would suffice, then RegisterHotKey would do the trick

Find element's index in pandas Series

you can use Series.idxmax()

>>> import pandas as pd
>>> myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
>>> myseries.idxmax()
3
>>> 

how to add super privileges to mysql database?

You can add super privilege using phpmyadmin:

Go to PHPMYADMIN > privileges > Edit User > Under Administrator tab Click SUPER. > Go

If you want to do it through Console, do like this:

 mysql> GRANT SUPER ON *.* TO user@'localhost' IDENTIFIED BY 'password';

After executing above code, end it with:

mysql> FLUSH PRIVILEGES;

You should do in on *.* because SUPER is not the privilege that applies just to one database, it's global.

Multiple Updates in MySQL

Yes ..it is possible using INSERT ON DUPLICATE KEY UPDATE sql statement.. syntax: INSERT INTO table_name (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE a=VALUES(a),b=VALUES(b),c=VALUES(c)

SQL Server: Database stuck in "Restoring" state

There can also be problem deleting a stuck database if snapshot is enabled. For me this worked:

  1. First I followed Tipu Delacablu steps (read a few posts up)
  2. run command: drop database [your database], which will give you an error telling you the name of the snapshot database
  3. run command: drop database [snapshot database], and then run the command in step 2 again.

Get the length of a String

In Swift 4 : If the string does not contain unicode characters then use the following

let str : String = "abcd"
let count = str.count // output 4

If the string contains unicode chars then use the following :

let spain = "España"
let count1 = spain.count // output 6
let count2 = spain.utf8.count // output 7

AWS S3: how do I see how much disk space is using

I'm not sure when this was added to the AWSCLI given that the original question was 3 years ago, but the command line tool gives a nice summary by running:

aws s3 ls s3://mybucket --recursive --human-readable --summarize

Getting JSONObject from JSONArray

When using google gson library.

var getRowData =
[{
    "dayOfWeek": "Sun",
    "date": "11-Mar-2012",
    "los": "1",
    "specialEvent": "",
    "lrv": "0"
},
{
    "dayOfWeek": "Mon",
    "date": "",
    "los": "2",
    "specialEvent": "",
    "lrv": "0.16"
}];

    JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
     JsonArray  jsonArray = root.getAsJsonArray();
     JsonObject  jsonObject1 = jsonArray.get(0).getAsJsonObject();
     String dayOfWeek = jsonObject1.get("dayOfWeek").toString();

// when using jackson library

    JsonFactory f = new JsonFactory();
              ObjectMapper mapper = new ObjectMapper();
          JsonParser jp = f.createJsonParser(getRowData);
          // advance stream to START_ARRAY first:
          jp.nextToken();
          // and then each time, advance to opening START_OBJECT
         while (jp.nextToken() == JsonToken.START_OBJECT) {
            Map<String,Object> userData = mapper.readValue(jp, Map.class);
            userData.get("dayOfWeek");
            // process
           // after binding, stream points to closing END_OBJECT
        }

Get list of data-* attributes using javascript / jQuery

One way of finding all data attributes is using element.attributes. Using .attributes, you can loop through all of the element attributes, filtering out the items which include the string "data-".

let element = document.getElementById("element");

function getDataAttributes(element){
    let elementAttributes = {},
        i = 0;

    while(i < element.attributes.length){
        if(element.attributes[i].name.includes("data-")){
            elementAttributes[element.attributes[i].name] = element.attributes[i].value
        }
        i++;
    }

    return elementAttributes;

}

How to create a DateTime equal to 15 minutes ago?

This is simply what to do:

datetime.datetime.now() - datetime.timedelta(minutes = 15)

timedeltas are specifically designed to allow you to subtract or add deltas (differences) to datetimes.

NSNotificationCenter addObserver in Swift

Swift 5 & Xcode 10.2:

NotificationCenter.default.addObserver(
            self,
            selector: #selector(batteryLevelDidChangeNotification),
            name: UIDevice.batteryLevelDidChangeNotification,
            object: nil)

Git: How configure KDiff3 as merge tool and diff tool

Well, the problem is that Git can't find KDiff3 in the %PATH%.

In a typical Unix installation all executables reside in several well-known locations (/bin/, /usr/bin/, /usr/local/bin/, etc.), and one can invoke a program by simply typing its name in a shell processor (e.g. cmd.exe :) ).

In Microsoft Windows, programs are usually installed in dedicated paths so you can't simply type kdiff3 in a cmd session and get KDiff3 running.

The hard solution: you should tell Git where to find KDiff3 by specifying the full path to kdiff3.exe. Unfortunately, Git doesn't like spaces in the path specification in its config, so the last time I needed this, I ended up with those ancient "C:\Progra~1...\kdiff3.exe" as if it was late 1990s :)

The simple solution: Edit your computer settings and include the directory with kdiff3.exe in %PATH%. Then test if you can invoke it from cmd.exe by its name and then run Git.

Substring in VBA

Test for ':' first, then take test string up to ':' or end, depending on if it was found

Dim strResult As String

' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
    ' : found, so take up to :
    strResult = Left(strTest, intPos - 1)
Else
    ' : not found, so take whole string
    strResult = strTest
End If

Microsoft.ReportViewer.Common Version=12.0.0.0

Issue

Parser Error Message: Could not load file or assembly 'Microsoft.ReportViewer.WebForms / Winforms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Cause

Microsoft ReportViewer runtime and SQL CLR Types for SQL Server 2014 is required to run and is missing from the server hosting Internet Information Services (IIS) or your application.

Resolution

Install the following packages on the IIS server and then restart the system:

Download Microsoft ReportViewer runtime

Download Microsoft SQL CLR types for SQL Server 2014

Once restarted connect to Web service / Your app again and verify that the error has been resolved.

Or you cant follow this link to read more.

How do I upload a file with metadata using a REST web service?

I agree with Greg that a two phase approach is a reasonable solution, however I would do it the other way around. I would do:

POST http://server/data/media
body:
{
    "Name": "Test",
    "Latitude": 12.59817,
    "Longitude": 52.12873
}

To create the metadata entry and return a response like:

201 Created
Location: http://server/data/media/21323
{
    "Name": "Test",
    "Latitude": 12.59817,
    "Longitude": 52.12873,
    "ContentUrl": "http://server/data/media/21323/content"
}

The client can then use this ContentUrl and do a PUT with the file data.

The nice thing about this approach is when your server starts get weighed down with immense volumes of data, the url that you return can just point to some other server with more space/capacity. Or you could implement some kind of round robin approach if bandwidth is an issue.

Git Bash is extremely slow on Windows 7 x64

I've encountered the same problem running Git for Windows (msysgit) on Windows 7 x64 as a limited user account for quite some time.

From what I've read here and other places, the common theme seems to be the lack of administrative privileges and/or UAC. Since UAC is off on my system, the explanation that it is trying to write/delete something in the program files directory makes the most sense to me.

In any case, I've resolved my problem by installing the portable version of Git 1.8 with zipinstaller. Note that I had to unpack the .7z distribution file and repack it as a ZIP file in order for zipinstaller to work. I also had to manually add that directory to my system path.

The performance is fine now. Even though it is installed in the Program Files (x86) directory, which I don't have permissions for as a limited user, it doesn't seem to suffer from the same problem.

I ascribe this either to the fact that the portable version is a bit more conservative in where it writes/deletes files, which is probably the case, or to the upgrade from 1.7 to 1.8. I'm not going to try to pin down which one is the reason, suffice to say it works much better now, including Bash.

Android: No Activity found to handle Intent error? How it will resolve

in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)

<activity
        android:name=".MyBrowser"
        android:label="MyBrowser Activity" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="com.dsociety.activities.MyBrowser" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="http" />
        </intent-filter>
    </activity>

when i code the following, the same Exception is thrown at run time :

Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com"));    // should be http://www.google.com
startActivity(intent);

No Application Encryption Key Has Been Specified

  1. Copy .env.example to .env:

    cp -a .env.example .env

  2. Generate a key:

    php artisan key:generate

  3. Only then run:

    php artisan serve

APR based Apache Tomcat Native library was not found on the java.library.path?

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

How do we check if a pointer is NULL pointer?

First, to be 100% clear, there is no difference between C and C++ here. And second, the Stack Overflow question you cite doesn't talk about null pointers; it introduces invalid pointers; pointers which, at least as far as the standard is concerned, cause undefined behavior just by trying to compare them. There is no way to test in general whether a pointer is valid.

In the end, there are three widespread ways to check for a null pointer:

if ( p != NULL ) ...

if ( p != 0 ) ...

if ( p ) ...

All work, regardless of the representation of a null pointer on the machine. And all, in some way or another, are misleading; which one you choose is a question of choosing the least bad. Formally, the first two are indentical for the compiler; the constant NULL or 0 is converted to a null pointer of the type of p, and the results of the conversion are compared to p. Regardless of the representation of a null pointer.

The third is slightly different: p is implicitly converted to bool. But the implicit conversion is defined as the results of p != 0, so you end up with the same thing. (Which means that there's really no valid argument for using the third style—it obfuscates with an implicit conversion, without any offsetting benefit.)

Which one of the first two you prefer is largely a matter of style, perhaps partially dictated by your programming style elsewhere: depending on the idiom involved, one of the lies will be more bothersome than the other. If it were only a question of comparison, I think most people would favor NULL, but in something like f( NULL ), the overload which will be chosen is f( int ), and not an overload with a pointer. Similarly, if f is a function template, f( NULL ) will instantiate the template on int. (Of course, some compilers, like g++, will generate a warning if NULL is used in a non-pointer context; if you use g++, you really should use NULL.)

In C++11, of course, the preferred idiom is:

if ( p != nullptr ) ...

, which avoids most of the problems with the other solutions. (But it is not C-compatible:-).)

Android - Activity vs FragmentActivity?

ianhanniballake is right. You can get all the functionality of Activity from FragmentActivity. In fact, FragmentActivity has more functionality.

Using FragmentActivity you can easily build tab and swap format. For each tab you can use different Fragment (Fragments are reusable). So for any FragmentActivity you can reuse the same Fragment.

Still you can use Activity for single pages like list down something and edit element of the list in next page.

Also remember to use Activity if you are using android.app.Fragment; use FragmentActivity if you are using android.support.v4.app.Fragment. Never attach a android.support.v4.app.Fragment to an android.app.Activity, as this will cause an exception to be thrown.

Node.js getaddrinfo ENOTFOUND

If you need to use https, then use the https library

https = require('https');

// options
var options = {
    host: 'eternagame.wikia.com',
    path: '/wiki/EteRNA_Dictionary'
}

// get
https.get(options, callback);

Chrome: Uncaught SyntaxError: Unexpected end of input

There will definitely be an open bracket which caused the error.

I'd suggest that you open the page in Firefox, then open Firebug and check the console – it'll show the missing symbol.

Example screenshot:

Firebug highlighting the error

How to git ignore subfolders / subdirectories?

For ignoring subfolders but not main folder I could only get this to work in Visual Studio Code by placing a dummy readme.txt in the main folder. Only then /*/ checked in the main folder (and no subfolders).

Google Maps V3 marker with label

If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..

<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };


    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

JUNIT testing void methods

I want to make some unit test to get maximal code coverage

Code coverage should never be the goal of writing unit tests. You should write unit tests to prove that your code is correct, or help you design it better, or help someone else understand what the code is meant to do.

but I dont see how I can test my method checkIfValidElements, it returns nothing or change nothing.

Well you should probably give a few tests, which between them check that all 7 methods are called appropriately - both with an invalid argument and with a valid argument, checking the results of ErrorFile each time.

For example, suppose someone removed the call to:

method4(arg1, arg2);

... or accidentally changed the argument order:

method4(arg2, arg1);

How would you notice those problems? Go from that, and design tests to prove it.

How to give a pandas/matplotlib bar graph custom colors

I found the easiest way is to use the colormap parameter in .plot() with one of the preset color gradients:

df.plot(kind='bar', stacked=True, colormap='Paired')

enter image description here

You can find a large list of preset colormaps here.

colormaps

How do I check if a string is unicode or ascii?

Note that on Python 3, it's not really fair to say any of:

  • strs are UTFx for any x (eg. UTF8)

  • strs are Unicode

  • strs are ordered collections of Unicode characters

Python's str type is (normally) a sequence of Unicode code points, some of which map to characters.


Even on Python 3, it's not as simple to answer this question as you might imagine.

An obvious way to test for ASCII-compatible strings is by an attempted encode:

"Hello there!".encode("ascii")
#>>> b'Hello there!'

"Hello there... ?!".encode("ascii")
#>>> Traceback (most recent call last):
#>>>   File "", line 4, in <module>
#>>> UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 15: ordinal not in range(128)

The error distinguishes the cases.

In Python 3, there are even some strings that contain invalid Unicode code points:

"Hello there!".encode("utf8")
#>>> b'Hello there!'

"\udcc3".encode("utf8")
#>>> Traceback (most recent call last):
#>>>   File "", line 19, in <module>
#>>> UnicodeEncodeError: 'utf-8' codec can't encode character '\udcc3' in position 0: surrogates not allowed

The same method to distinguish them is used.

Could not resolve all dependencies for configuration ':classpath'

In my case deleting the .gradle folder worked for me.

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Update: Using DateTimeFormat, introduced in java 8:

The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.

Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.

The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.

Here is the example code:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Original answer - with old API SimpleDateFormat

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018

how do I print an unsigned char as hex in c++ using ostream?

Use:

cout << "a is " << hex << (int) a <<"; b is " << hex << (int) b << endl;

And if you want padding with leading zeros then:

#include <iomanip>
...
cout << "a is " << setw(2) << setfill('0') << hex << (int) a ; 

As we are using C-style casts, why not go the whole hog with terminal C++ badness and use a macro!

#define HEX( x )
   setw(2) << setfill('0') << hex << (int)( x )

you can then say

cout << "a is " << HEX( a );

Edit: Having said that, MartinStettner's solution is much nicer!

Get the value in an input text box

You can simply set the value in text box.

First, you get the value like

var getValue = $('#txt_name').val();

After getting a value set in input like

$('#txt_name').val(getValue);

How to let an ASMX file output JSON

Are you calling the web service from client script or on the server side?

You may find sending a content type header to the server will help, e.g.

'application/json; charset=utf-8'

On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

JavaScript Chart.js - Custom data formatting to display on tooltip

For chart.js 2.0+, this has changed (no more tooltipTemplate/multiTooltipTemplate). For those that just want to access the current, unformatted value and start tweaking it, the default tooltip is the same as:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return tooltipItem.yLabel;
            }
        }
    }
}

I.e., you can return modifications to tooltipItem.yLabel, which holds the y-axis value. In my case, I wanted to add a dollar sign, rounding, and thousands commas for a financial chart, so I used:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return "$" + Number(tooltipItem.yLabel).toFixed(0).replace(/./g, function(c, i, a) {
                    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
                });
            }
        }
    }
}

Multiprocessing vs Threading Python

Here are some pros/cons I came up with.

Multiprocessing

Pros

  • Separate memory space
  • Code is usually straightforward
  • Takes advantage of multiple CPUs & cores
  • Avoids GIL limitations for cPython
  • Eliminates most needs for synchronization primitives unless if you use shared memory (instead, it's more of a communication model for IPC)
  • Child processes are interruptible/killable
  • Python multiprocessing module includes useful abstractions with an interface much like threading.Thread
  • A must with cPython for CPU-bound processing

Cons

  • IPC a little more complicated with more overhead (communication model vs. shared memory/objects)
  • Larger memory footprint

Threading

Pros

  • Lightweight - low memory footprint
  • Shared memory - makes access to state from another context easier
  • Allows you to easily make responsive UIs
  • cPython C extension modules that properly release the GIL will run in parallel
  • Great option for I/O-bound applications

Cons

  • cPython - subject to the GIL
  • Not interruptible/killable
  • If not following a command queue/message pump model (using the Queue module), then manual use of synchronization primitives become a necessity (decisions are needed for the granularity of locking)
  • Code is usually harder to understand and to get right - the potential for race conditions increases dramatically

How to serve up images in Angular2?

Just put your images in the assets folder refer them in your html pages or ts files with that link.

How do I make an auto increment integer field in Django?

You can override Django save method official doc about it.

The modified version of your code:

class Order(models.Model):
    cart = models.ForeignKey(Cart)
    add_date = models.DateTimeField(auto_now_add=True)
    order_number = models.IntegerField(default=0)  # changed here
    enable = models.BooleanField(default=True)

    def save(self, *args, **kwargs):
        self.order_number = self.order_number + 1
        super().save(*args, **kwargs)  # Call the "real" save() method.

Another way is to use signals. More one:

  1. official Django docs about pre-save
  2. stackoverflow example about using pre-save signal

How do I start my app on startup?

screenshot

I would like to add one point in this question which I was facing for couple of days. I tried all the answers but those were not working for me. If you are using android version 5.1 please change these settings.

If you are using android version 5.1 then you have to dis-select (Restrict to launch) from app settings.

settings> app > your app > Restrict to launch (dis-select)

Using classes with the Arduino

I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:

class AMLed
{
    private:
          uint8_t _ledPin;
          long _turnOffTime;

    public:
          AMLed(uint8_t pin);
          void setOn();
          void setOff();
          // Turn the led on for a given amount of time (relies
          // on a call to check() in the main loop()).
          void setOnForTime(int millis);
          void check();
};

And here is the main source

AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
    pinMode(_ledPin, OUTPUT);
}

void AMLed::setOn()
{
    digitalWrite(_ledPin, HIGH);
}

void AMLed::setOff()
{
    digitalWrite(_ledPin, LOW);
}

void AMLed::setOnForTime(int p_millis)
{
    _turnOffTime = millis() + p_millis;
    setOn();
}

void AMLed::check()
{
    if (_turnOffTime != 0 && (millis() > _turnOffTime))
    {
        _turnOffTime = 0;
        setOff();
    }
}

It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html

To use, I simply do something like this in the .pde file:

#include "AM_Led.h"

#define TIME_LED    12   // The port for the LED

AMLed test(TIME_LED);

How do you set the title color for the new Toolbar?

With the Material Components Library you can use the app:titleTextColor attribute.

In the layout you can use something like:

<com.google.android.material.appbar.MaterialToolbar
    app:titleTextColor="@color/...."
    .../>

You can also use a custom style:

<com.google.android.material.appbar.MaterialToolbar
     style="@style/MyToolbarStyle"
    .../>

with (extending the Widget.MaterialComponents.Toolbar.Primary style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar.Primary">
       <item name="titleTextColor">@color/....</item>
  </style>

or (extending the Widget.MaterialComponents.Toolbar style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
       <item name="titleTextColor">@color/....</item>
  </style>

enter image description here

You can also override the color defined by the style using the android:theme attribute (using the Widget.MaterialComponents.Toolbar.Primary style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        />

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is also used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>

enter image description here

or (using the Widget.MaterialComponents.Toolbar style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar"
        android:theme="@style/MyThemeOverlay_Toolbar2"

with:

  <style name="MyThemeOverlay_Toolbar3" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>

What is the yield keyword used for in C#?

At first sight, yield return is a .NET sugar to return an IEnumerable.

Without yield, all the items of the collection are created at once:

class SomeData
{
    public SomeData() { }

    static public IEnumerable<SomeData> CreateSomeDatas()
    {
        return new List<SomeData> {
            new SomeData(), 
            new SomeData(), 
            new SomeData()
        };
    }
}

Same code using yield, it returns item by item:

class SomeData
{
    public SomeData() { }

    static public IEnumerable<SomeData> CreateSomeDatas()
    {
        yield return new SomeData();
        yield return new SomeData();
        yield return new SomeData();
    }
}

The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created.

The yield operator allows the creation of items as it is demanded. That's a good reason to use it.

Passing an array by reference

It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don't use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

E.g. int &myArray[100] // array of references

So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

E.g int (&myArray)[100] // reference of an array of 100 ints

ImageView rounded corners

I use Universal Image loader library to download and round the corners of image, and it worked for me.

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(thisContext)
            // You can pass your own memory cache implementation
           .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
           .build();

DisplayImageOptions options = new DisplayImageOptions.Builder()
            .displayer(new RoundedBitmapDisplayer(10)) //rounded corner bitmap
            .cacheInMemory(true)
            .cacheOnDisc(true)
            .build();

ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
imageLoader.displayImage(image_url,image_view, options );

find all the name using mysql query which start with the letter 'a'

Try this:

select * from artists where name like "A%" or name like "B%" or name like "C%"

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

Submit Button Image

You have to remove the borders and add a background image on the input.

.imgClass { 
    background-image: url(path to image) no-repeat;
    width: 186px;
    height: 53px;
    border: none;
}

It should be good now, normally.

ORA-01031: insufficient privileges when selecting view

To use a view, the user must have the appropriate privileges but only for the view itself, not its underlying objects. However, if access privileges for the underlying objects of the view are removed, then the user no longer has access. This behavior occurs because the security domain that is used when a user queries the view is that of the definer of the view. If the privileges on the underlying objects are revoked from the view's definer, then the view becomes invalid, and no one can use the view. Therefore, even if a user has been granted access to the view, the user may not be able to use the view if the definer's rights have been revoked from the view's underlying objects.

Oracle Documentation http://docs.oracle.com/cd/B28359_01/network.111/b28531/authorization.htm#DBSEG98017

How to format a number 0..9 to display with 2 digits (it's NOT a date)

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

How to sort an associative array by its values in Javascript?

Continued discussion & other solutions covered at How to sort an (associative) array by value? with the best solution (for my case) being by saml (quoted below).

Arrays can only have numeric indexes. You'd need to rewrite this as either an Object, or an Array of Objects.

var status = new Array();
status.push({name: 'BOB', val: 10});
status.push({name: 'TOM', val: 3});
status.push({name: 'ROB', val: 22});
status.push({name: 'JON', val: 7});

If you like the status.push method, you can sort it with:

status.sort(function(a,b) {
    return a.val - b.val;
});

Use images instead of radio buttons

  • Wrap radio and image in <label>
  • Hide radio button (Don't use display:none or visibility:hidden since such will impact accessibility)
  • Target the image next to the hidden radio using Adjacent sibling selector +

_x000D_
_x000D_
/* HIDE RADIO */
[type=radio] { 
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

/* IMAGE STYLES */
[type=radio] + img {
  cursor: pointer;
}

/* CHECKED STYLES */
[type=radio]:checked + img {
  outline: 2px solid #f00;
}
_x000D_
<label>
  <input type="radio" name="test" value="small" checked>
  <img src="http://placehold.it/40x60/0bf/fff&text=A">
</label>

<label>
  <input type="radio" name="test" value="big">
  <img src="http://placehold.it/40x60/b0f/fff&text=B">
</label>
_x000D_
_x000D_
_x000D_

Don't forget to add a class to your labels and in CSS use that class instead.


Custom styles and animations

Here's an advanced version using the <i> element and the :after pseudo:

CSS custom radio and checkbox

_x000D_
_x000D_
body{color:#444;font:100%/1.4 sans-serif;}


/* CUSTOM RADIO & CHECKBOXES
   http://stackoverflow.com/a/17541916/383904 */
.rad,
.ckb{
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}
.rad > input,
.ckb > input{ /* HIDE ORG RADIO & CHECKBOX */
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}
/* RADIO & CHECKBOX STYLES */
/* DEFAULT <i> STYLE */
.rad > i,
.ckb > i{ 
  display: inline-block;
  vertical-align: middle;
  width:  16px;
  height: 16px;
  border-radius: 50%;
  transition: 0.2s;
  box-shadow: inset 0 0 0 8px #fff;
  border: 1px solid gray;
  background: gray;
}
/* CHECKBOX OVERWRITE STYLES */
.ckb > i {
  width: 25px;
  border-radius: 3px;
}
.rad:hover > i{ /* HOVER <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: gray;
}
.rad > input:checked + i{ /* (RADIO CHECKED) <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: orange;
}
/* CHECKBOX */
.ckb > input + i:after{
  content: "";
  display: block;
  height: 12px;
  width:  12px;
  margin: 2px;
  border-radius: inherit;
  transition: inherit;
  background: gray;
}
.ckb > input:checked + i:after{ /* (RADIO CHECKED) <i> STYLE */
  margin-left: 11px;
  background:  orange;
}
_x000D_
<label class="rad">
  <input type="radio" name="rad1" value="a">
  <i></i> Radio 1
</label>
<label class="rad">
  <input type="radio" name="rad1" value="b" checked>
  <i></i> Radio 2
</label>

<br>

<label class="ckb">
  <input type="checkbox" name="ckb1" value="a" checked>
  <i></i> Checkbox 1
</label>
<label class="ckb">
  <input type="checkbox" name="ckb2" value="b">
  <i></i> Checkbox 2
</label>
_x000D_
_x000D_
_x000D_

unexpected T_VARIABLE, expecting T_FUNCTION

put public, protected or private before the $connection.

How to toggle font awesome icon on click?

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

How to write ternary operator condition in jQuery?

As others have correctly pointed out, the first part of the ternary needs to return true or false and in your question the return value is a jQuery object.

The problem that you may have in the comparison is that the web color will be converted to RGB so you have to text for that in the ternary condition.

So with the CSS:

#blackbox {
    background:pink;
    width:10px;
    height:10px;
}

The following jQuery will flip the colour:

var b = $('#blackbox');
b.css('background', (b.css('backgroundColor') === 'rgb(255, 192, 203)' ? 'black' : 'pink'));

Demo

SSL cert "err_cert_authority_invalid" on mobile chrome only

I guess you should install CA certificate form one if authority canter:

ssl_trusted_certificate ssl/SSL_CA_Bundle.pem;

CSS: Position loading indicator in the center of the screen

_x000D_
_x000D_
.loader{_x000D_
  position: fixed;_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  z-index: 9999;_x000D_
  background: url('//upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Phi_fenomeni.gif/50px-Phi_fenomeni.gif') _x000D_
              50% 50% no-repeat rgb(249,249,249);_x000D_
}
_x000D_
<div class="loader"></div>
_x000D_
_x000D_
_x000D_

Get HTML code from website in C#

I am using AngleSharp and have been very satisfied with it.

Here is a simple example how to fetch a page:

var config = Configuration.Default.WithDefaultLoader();
var document = await BrowsingContext.New(config).OpenAsync("https://www.google.com");

And now you have a web page in document variable. Then you can easily access it by LINQ or other methods. For example if you want to get a string value from a HTML table:

var someStringValue = document.All.Where(m =>
        m.LocalName == "td" &&
        m.HasAttribute("class") &&
        m.GetAttribute("class").Contains("pid-1-bid")
    ).ElementAt(0).TextContent.ToString();

To use CSS selectors please see AngleSharp examples.

Start index for iterating Python list

Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?

Use a normal for-loop with range(start, stop, step) (where start and step are optional arguments).

For example, looping through an array starting at index 1:

for i in range(1, len(arr)):
    print(arr[i])

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.

For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.

Can I have two JavaScript onclick events in one element?

The HTML

<a href="#" id="btn">click</a>

And the javascript

// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
    if (window.addEventListener) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, fpNotify);
        };
    }
}());

// find the element
var el = document.getElementById("btn");

// add the first listener
on(el, "click", function(){
    alert("foo");
});

// add the second listener
on(el, "click", function(){
    alert("bar");
});

This will alert both 'foo' and 'bar' when clicked.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Also, if your service is sending an object instead of an array add isArray:false to its declaration.

'query': {method: 'GET', isArray: false }

How to use BOOLEAN type in SELECT statement

With Oracle 12, you can use the WITH clause to declare your auxiliary functions. I'm assuming your get_something function returns varchar2:

with
  function get_something_(name varchar2, ignore_notfound number)
  return varchar2 
  is
  begin
    -- Actual function call here
    return get_something(name, not ignore_notfound = 0);
  end get_something_;

  -- Call auxiliary function instead of actual function
select get_something_('NAME', 1) from dual;

Of course, you could have also stored your auxiliary function somewhere in the schema as shown in this answer, but by using WITH, you don't have any external dependencies just to run this query. I've blogged about this technique more in detail here.

How can I list all collections in the MongoDB shell?

How do I list all collections for the current database that I'm using?

Three methods

  • show collections
  • show tables
  • db.getCollectionNames()

To list all databases:

show dbs

To enter or use a given database:

use databasename

To list all collections:

show collections

Output:

collection1
collection2
system.indexes

(or)

show tables

Output:

collection1
collection2
system.indexes

(or)

db.getCollectionNames()

Output:

[ "collection1", "collection2", "system.indexes" ]

To enter or use given collection

use collectionname

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

Console output in a Qt GUI app?

Oh you can Output a message when using QT += gui and CONFIG += console.

You need printf("foo bar") but cout << "foo bar" doesn't works

Git undo changes in some files

Yes;

git commit FILE

will commit just FILE. Then you can use

git reset --hard

to undo local changes in other files.

There may be other ways too that I don't know about...

edit: or, as NicDumZ said, git-checkout just the files you want to undo the changes on (the best solution depends on wether there are more files to commit or more files to undo :-)

Setting paper size in FPDF

/*$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait*/

Adding quotes to a string in VBScript

You have to use double double quotes to escape the double quotes (lol):

g = "abcd """ & a & """"

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I am trying to avoid using VBA. But if has to be, then it has to be:)

There is quite simple UDF for you:

Function myCountIf(rng As Range, criteria) As Long
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
    Next ws
End Function

and call it like this: =myCountIf(I:I,A13)


P.S. if you'd like to exclude some sheets, you can add If statement:

Function myCountIf(rng As Range, criteria) As Long
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.name <> "Sheet1" And ws.name <> "Sheet2" Then
            myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
        End If
    Next ws
End Function

UPD:

I have four "reference" sheets that I need to exclude from being scanned/searched. They are currently the last four in the workbook

Function myCountIf(rng As Range, criteria) As Long
    Dim i As Integer

    For i = 1 To ThisWorkbook.Worksheets.Count - 4
        myCountIf = myCountIf + WorksheetFunction.CountIf(ThisWorkbook.Worksheets(i).Range(rng.Address), criteria)
    Next i
End Function

Download a specific tag with Git

Working off of Peter Johnson's answer, I created a nice little alias for myself:

alias gcolt="git checkout $(git tag | sort -V | tail -1)"

aka 'git checkout latest tag'.

This relies on the GNU version of sort, which appropriately handles situations like the one lOranger pointed out:

v1.0.1
...
v1.0.9
v1.0.10

If you're on a mac, brew install coreutils and then call gsort instead.

What is the equivalent of "!=" in Excel VBA?

Just a note. If you want to compare a string with "" ,in your case, use

If LEN(str) > 0 Then

or even just

If LEN(str) Then

instead.

Show row number in row header of a DataGridView

Thanks @Gabriel-Perez and @Groo, great idea! In case others want it, here's a version in VB tested in Visual Studio 2012. In my case I wanted the numbers to appear top right aligned in the Row Header.

Private Sub MyDGV_RowPostPaint(sender As Object, _
    e As DataGridViewRowPostPaintEventArgs) Handles MyDataGridView.RowPostPaint

    ' Automatically maintains a Row Header Index Number 
    '   like the Excel row number, independent of sort order

    Dim grid As DataGridView = CType(sender, DataGridView)
    Dim rowIdx As String = (e.RowIndex + 1).ToString()
    Dim rowFont As New System.Drawing.Font("Tahoma", 8.0!, _
        System.Drawing.FontStyle.Bold, _
        System.Drawing.GraphicsUnit.Point, CType(0, Byte))

    Dim centerFormat = New StringFormat()
    centerFormat.Alignment = StringAlignment.Far
    centerFormat.LineAlignment = StringAlignment.Near

    Dim headerBounds As Rectangle = New Rectangle(_
        e.RowBounds.Left, e.RowBounds.Top, _
        grid.RowHeadersWidth, e.RowBounds.Height)
    e.Graphics.DrawString(rowIdx, rowFont, SystemBrushes.ControlText, _
        headerBounds, centerFormat)
End Sub

You can also get the default font, rowFont = grid.RowHeadersDefaultCellStyle.Font, but it might not look as good. The screenshot below is using the Tahoma font.

Example on windows 7

Create mysql table directly from CSV file using the CSV Storage engine?

This is not possible, you can however overwrite an existing table file. But be sure, that the line endings in your file are unix style (ending only with \n), not windows style (ending with \r\n), whether you are working under windows or not.

How do I get the number of elements in a list?

Besides len you can also use operator.length_hint (requires Python 3.4+). For a normal list both are equivalent, but length_hint makes it possible to get the length of a list-iterator, which could be useful in certain circumstances:

>>> from operator import length_hint
>>> l = ["apple", "orange", "banana"]
>>> len(l)
3
>>> length_hint(l)
3

>>> list_iterator = iter(l)
>>> len(list_iterator)
TypeError: object of type 'list_iterator' has no len()
>>> length_hint(list_iterator)
3

But length_hint is by definition only a "hint", so most of the time len is better.

I've seen several answers suggesting accessing __len__. This is all right when dealing with built-in classes like list, but it could lead to problems with custom classes, because len (and length_hint) implement some safety checks. For example, both do not allow negative lengths or lengths that exceed a certain value (the sys.maxsize value). So it's always safer to use the len function instead of the __len__ method!

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

Python, Pandas : write content of DataFrame into text File

You can just use np.savetxt and access the np attribute .values:

np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')

yields:

18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

or to_csv:

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')

Note for np.savetxt you'd have to pass a filehandle that has been created with append mode.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

In PostMan we have ->Pre-request Script. Paste the Below snippet.

const dateNow = new Date();
postman.setGlobalVariable("todayDate", dateNow.toLocaleDateString());

And now we are ready to use.

{
"firstName": "SANKAR",
"lastName": "B",
"email": "[email protected]",
"creationDate": "{{todayDate}}"
}

If you are using JPA Entity classes then use the below snippet

    @JsonFormat(pattern="MM/dd/yyyy")
    @Column(name = "creation_date")
    private Date creationDate;

enter image description here enter image description here

Declaring an unsigned int in Java

Perhaps this is what you meant?

long getUnsigned(int signed) {
    return signed >= 0 ? signed : 2 * (long) Integer.MAX_VALUE + 2 + signed;
}
  • getUnsigned(0) ? 0
  • getUnsigned(1) ? 1
  • getUnsigned(Integer.MAX_VALUE) ? 2147483647
  • getUnsigned(Integer.MIN_VALUE) ? 2147483648
  • getUnsigned(Integer.MIN_VALUE + 1) ? 2147483649

HSL to RGB color conversion

Here is the modified javascript function, it outputs Hue in set 0-360 degrees.

function rgbToHsl(r, g, b) {
      r /= 255, g /= 255, b /= 255;
      var max = Math.max(r, g, b), min = Math.min(r, g, b);
      var h, s, l = (max + min) / 2;

      if(max == min){
          h = s = 0; // achromatic
      } else {
          var d = max - min;
          s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
          switch(max){
              case r: h = (g - b) / d ; break;
              case g: h = 2 + ( (b - r) / d); break;
              case b: h = 4 + ( (r - g) / d); break;
          }
          h*=60;
          if (h < 0) h +=360;
      }
     return([h, s, l]);
  }  
alert(rgbToHsl(125,115,145));

How to list files using dos commands?

If you just want to get the file names and not directory names then use :

dir /b /a-d > file.txt

Why does Eclipse complain about @Override on interface methods?

Project specific settings may be enabled. Select your project Project > Properties > Java Compiler, uncheck the Enable project specific settings or change Jdk 1.6 and above not forgetting the corresponding JRE.
Incase it does not work, remove your project from eclipse, delete .settings folders, .project, .classpath files. clean and build the project, import it back into eclipse and then reset your Java compiler. Clean and build your projectand eclipse. It worked for me

How to ignore parent css style

There are a bunch of values that can be used to undo CSS rules: initial, unset & revert. More details from the CSS Working Group at W3C:

https://drafts.csswg.org/css-cascade/#defaulting-keywords

As this is 'draft' not all are fully supported, but unset and initial are in most major browsers, revert has less support.

Setting mime type for excel document

I am using EPPlus to generate .xlsx (OpenXML format based) excel file. For sending this excel file as attachment in email I use the following MIME type and it works fine with EPPlus generated file and opens properly in ms-outlook mail client preview.

string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.Net.Mime.ContentType contentType = null;
if (mimeType?.Length > 0)
{
    contentType = new System.Net.Mime.ContentType(mimeType);
}

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

Every class has a nil? method:

if a_variable.nil?
    # the variable has a nil value
end

And strings have the empty? method:

if a_string.empty?
    # the string is empty
}

Remember that a string does not equal nil when it is empty, so use the empty? method to check if a string is empty.

offsetTop vs. jQuery.offset().top

It is possible that the offset could be a non-integer, using em as the measurement unit, relative font-sizes in %.

I also theorise that the offset might not be a whole number when the zoom isn't 100% but that depends how the browser handles scaling.

How to establish ssh key pair when "Host key verification failed"

First you should remove existing key. SSH keys in most of Linux-based OS will be saved this file "/root/.ssh/known_hosts", so in order to remove the key related to host the following command will be used:

ssh-keygen -f "/root/.ssh/known_hosts" -R [Hostname]

Regards K1

Java Project: Failed to load ApplicationContext

I faced this issue, and that is when a Bean (@Bean) was not instantiated properly as it was not given the correct parameters in my test class.

Fix columns in horizontal scrolling

Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/

HTML

<h2>TableHeadFixer Fix Left Column</h2>

<div id="parent">
    <table id="fixTable" class="table">
        <thead>
            <tr>
                <th>Ano</th>
                <th>Jan</th>
                <th>Fev</th>
                <th>Mar</th>
                <th>Abr</th>
                <th>Maio</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
        </tbody>
    </table>
</div>

JS

    $(document).ready(function() {
        $("#fixTable").tableHeadFixer({"head" : false, "right" : 1}); 
    });

CSS

    #parent {
        height: 300px;
    }

    #fixTable {
        width: 1800px !important;
    }

https://jsfiddle.net/5gfuqqc4/

Python: pandas merge multiple dataframes

If you are filtering by common date this will return it:

dfs = [df1, df2, df3]
checker = dfs[-1]
check = set(checker.loc[:, 0])

for df in dfs[:-1]:
    check = check.intersection(set(df.loc[:, 0]))

print(checker[checker.loc[:, 0].isin(check)])

jQuery Ajax POST example with PHP

If you want to send data using jQuery Ajax then there is no need of form tag and submit button

Example:

<script>
    $(document).ready(function () {
        $("#btnSend").click(function () {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {bar: $("#bar").val()},
                success: function (result) {
                    alert('success');
                }
            });
        });
    });
</script>

<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />

Response::json() - Laravel 5.1

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.

if you are like me, simply add

   "use Response;"

above your class ...extends contoller. this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.

You can find creation/deletion of environments in the Anaconda documentation.

Hope this helped.

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

How to determine a Python variable's type?

Just do not do it. Asking for something's type is wrong in itself. Instead use polymorphism. Find or if necessary define by yourself the method that does what you want for any possible type of input and just call it without asking about anything. If you need to work with built-in types or types defined by a third-party library, you can always inherit from them and use your own derivatives instead. Or you can wrap them inside your own class. This is the object-oriented way to resolve such problems.

If you insist on checking exact type and placing some dirty ifs here and there, you can use __class__ property or type function to do it, but soon you will find yourself updating all these ifs with additional cases every two or three commits. Doing it the OO way prevents that and lets you only define a new class for a new type of input instead.

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

Here's the way to do it without using any external libraries:

// Define a class like this
function Person(name, gender){

   // Add object properties like this
   this.name = name;
   this.gender = gender;
}

// Add methods like this.  All Person objects will be able to invoke this
Person.prototype.speak = function(){
    alert("Howdy, my name is" + this.name);
};

// Instantiate new objects with 'new'
var person = new Person("Bob", "M");

// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"

Now the real answer is a whole lot more complex than that. For instance, there is no such thing as classes in JavaScript. JavaScript uses a prototype-based inheritance scheme.

In addition, there are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript. You'll want to check out at least Prototype and jQuery.

Deciding which of these is the "best" is a great way to start a holy war on Stack Overflow. If you're embarking on a larger JavaScript-heavy project, it's definitely worth learning a popular library and doing it their way. I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery.

As far as there being only "one way to do it", without any dependencies on external libraries, the way I wrote is pretty much it.

Missing artifact com.sun:tools:jar

If this problem still happens, it might be because of a JDK of version equal or greater than 11.

The tools.jar archive has been removed from the lib folder in those JDK's (see this answer to a similar question). In that case, try to use other versions of the libraries, that do not rely on the com.sun:tools library.

gitignore all files of extension in directory

UPDATE: Take a look at @Joey's answer: Git now supports the ** syntax in patterns. Both approaches should work fine.


The gitignore(5) man page states:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory, with patterns in the higher level files (up to the toplevel of the work tree) being overridden by those in lower level files down to the directory containing the file.

What this means is that the patterns in a .gitignore file in any given directory of your repo will affect that directory and all subdirectories.

The pattern you provided

/public/static/**/*.js

isn't quite right, firstly because (as you correctly noted) the ** syntax is not used by Git. Also, the leading / anchors that pattern to the start of the pathname. (So, /public/static/*.js will match /public/static/foo.js but not /public/static/foo/bar.js.) Removing the leading / won't work either, matching paths like public/static/foo.js and foo/public/static/bar.js. EDIT: Just removing the leading slash won't work either — because the pattern still contains a slash, it is treated by Git as a plain, non-recursive shell glob (thanks @Joey Hoer for pointing this out).

As @ptyx suggested, what you need to do is create the file <repo>/public/static/.gitignore and include just this pattern:

*.js

There is no leading /, so it will match at any part of the path, and that pattern will only ever be applied to files in the /public/static directory and its subdirectories.

How to create a Jar file in Netbeans

Please do right click on the project and go to properties. Then go to Build and Packaging. You can see the JAR file location that is produced by defualt setting of netbean in the dist directory.

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

Remove the first character of a string

python 2.x

s = ":dfa:sif:e"
print s[1:]

python 3.x

s = ":dfa:sif:e"
print(s[1:])

both prints

dfa:sif:e

jQuery UI dialog box not positioned center screen

Just solved the same problem, the issue was that i did not imported some js files, like widget.js :)

ReactJS lifecycle method inside a function Component

Solution One: You can use new react HOOKS API. Currently in React v16.8.0

Hooks let you use more of React’s features without classes. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. Hooks solves all the problems addressed with Recompose.

A Note from the Author of recompose (acdlite, Oct 25 2018):

Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today, we announced a proposal for Hooks. Hooks solves all the problems I attempted to address with Recompose three years ago, and more on top of that. I will be discontinuing active maintenance of this package (excluding perhaps bugfixes or patches for compatibility with future React releases), and recommending that people use Hooks instead. Your existing code with Recompose will still work, just don't expect any new features.

Solution Two:

If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a function component.

Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).

// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

function RenderlessComponent() {
  return null; 
}

export default lifecycle({

  componentDidMount() {
    const { checkIfAuthed } = this.props;
    // Do they have an active session? ("Remember me")
    checkIfAuthed();
  },

  componentWillReceiveProps(nextProps) {
    const {
      loadUser,
    } = this.props;

    // Various 'indicators'..
    const becameAuthed = (!(this.props.auth) && nextProps.auth);
    const isCurrentUser = (this.props.currentUser !== null);

    if (becameAuthed) {
      loadUser(nextProps.auth.uid);
    }

    const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
    if (shouldSetCurrentUser) {
      const currentUser = nextProps.users[nextProps.auth.uid];
      if (currentUser) {
        this.props.setCurrentUser({
          'id': nextProps.auth.uid,
          ...currentUser,
        });
      }
    }
  }
})(RenderlessComponent);

In CSS how do you change font size of h1 and h2

h1 {
  font-weight: bold;
  color: #fff;
  font-size: 32px;
}

h2 {
  font-weight: bold;
  color: #fff;
  font-size: 24px;
}

Note that after color you can use a word (e.g. white), a hex code (e.g. #fff) or RGB (e.g. rgb(255,255,255)) or RGBA (e.g. rgba(255,255,255,0.3)).

Launch custom android application from android browser

example.php:

<?php
if(!isset($_GET['app_link'])){  ?>   
    <iframe src="example.php?app_link=YourApp://blabla" style="display:none;" scrolling="no" frameborder="0"></iframe>
    <iframe src="example.php?full_link=http://play.google.com/xyz" style="display:none;" scrolling="no" frameborder="0"></iframe>
    <?php 
}
else { ?>
    <script type="text/javascript">
    self.window.location        = '<?php echo $_GET['app_link'];?>';
    window.parent.location.href = '<?php echo $_GET['full_link'];?>';
    </script>
<?php 
}

How to count number of records per day?

This one is like the answer above which uses the MySql DATE_FORMAT() function. I also selected just one specific week in Jan.

SELECT 
    DatePart(day, DateAdded) AS date, 
    COUNT(entryhash) AS count 
FROM Responses 
    where DateAdded > '2020-01-25' and DateAdded < '2020-02-01' 
GROUP BY 
    DatePart(day, DateAdded )

Check date with todays date

Does this help?

Calendar c = Calendar.getInstance();

// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

// and get that as a Date
Date today = c.getTime();

// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();

// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;

// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

// and get that as a Date
Date dateSpecified = c.getTime();

// test your condition
if (dateSpecified.before(today)) {
  System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
  System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}

Is it possible to opt-out of dark mode on iOS 13?

Yes you can skip by adding the following code in viewDidLoad:

if #available(iOS 13.0, *) {
        // Always adopt a light interface style.
        overrideUserInterfaceStyle = .light
    }

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

How to determine MIME type of file in android?

None of the answers here are perfect. Here is an answer combining the best elements of all the top answers:

public final class FileUtil {

    // By default, Android doesn't provide support for JSON
    public static final String MIME_TYPE_JSON = "application/json";

    @Nullable
    public static String getMimeType(@NonNull Context context, @NonNull Uri uri) {

        String mimeType = null;
        if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            ContentResolver cr = context.getContentResolver();
            mimeType = cr.getType(uri);
        } else {
            String fileExtension = getExtension(uri.toString());

            if(fileExtension == null){
                return null;
            }

            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                    fileExtension.toLowerCase());

            if(mimeType == null){
                // Handle the misc file extensions
                return handleMiscFileExtensions(fileExtension);
            }
        }
        return mimeType;
    }

    @Nullable
    private static String getExtension(@Nullable String fileName){

        if(fileName == null || TextUtils.isEmpty(fileName)){
            return null;
        }

        char[] arrayOfFilename = fileName.toCharArray();
        for(int i = arrayOfFilename.length-1; i > 0; i--){
            if(arrayOfFilename[i] == '.'){
                return fileName.substring(i+1, fileName.length());
            }
        }
        return null;
    }

    @Nullable
    private static String handleMiscFileExtensions(@NonNull String extension){

        if(extension.equals("json")){
            return MIME_TYPE_JSON;
        }
        else{
            return null;
        }
    }
}

Why Choose Struct Over Class?

I wouldn't say that structs offer less functionality.

Sure, self is immutable except in a mutating function, but that's about it.

Inheritance works fine as long as you stick to the good old idea that every class should be either abstract or final.

Implement abstract classes as protocols and final classes as structs.

The nice thing about structs is that you can make your fields mutable without creating shared mutable state because copy on write takes care of that :)

That's why the properties / fields in the following example are all mutable, which I would not do in Java or C# or swift classes.

Example inheritance structure with a bit of dirty and straightforward usage at the bottom in the function named "example":

protocol EventVisitor
{
    func visit(event: TimeEvent)
    func visit(event: StatusEvent)
}

protocol Event
{
    var ts: Int64 { get set }

    func accept(visitor: EventVisitor)
}

struct TimeEvent : Event
{
    var ts: Int64
    var time: Int64

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }
}

protocol StatusEventVisitor
{
    func visit(event: StatusLostStatusEvent)
    func visit(event: StatusChangedStatusEvent)
}

protocol StatusEvent : Event
{
    var deviceId: Int64 { get set }

    func accept(visitor: StatusEventVisitor)
}

struct StatusLostStatusEvent : StatusEvent
{
    var ts: Int64
    var deviceId: Int64
    var reason: String

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }

    func accept(visitor: StatusEventVisitor)
    {
        visitor.visit(self)
    }
}

struct StatusChangedStatusEvent : StatusEvent
{
    var ts: Int64
    var deviceId: Int64
    var newStatus: UInt32
    var oldStatus: UInt32

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }

    func accept(visitor: StatusEventVisitor)
    {
        visitor.visit(self)
    }
}

func readEvent(fd: Int) -> Event
{
    return TimeEvent(ts: 123, time: 56789)
}

func example()
{
    class Visitor : EventVisitor
    {
        var status: UInt32 = 3;

        func visit(event: TimeEvent)
        {
            print("A time event: \(event)")
        }

        func visit(event: StatusEvent)
        {
            print("A status event: \(event)")

            if let change = event as? StatusChangedStatusEvent
            {
                status = change.newStatus
            }
        }
    }

    let visitor = Visitor()

    readEvent(1).accept(visitor)

    print("status: \(visitor.status)")
}

How to avoid the "divide by zero" error in SQL?

Here is a situation where you can divide by zero. The business rule is that to calculate inventory turns, you take cost of goods sold for a period, annualize it. After you have the annualized number, you divide by the average inventory for the period.

I'm looking at calculating the number of inventory turns that occur in a three month period. I have calculated that I have Cost of Goods sold during the three month period of $1,000. The annual rate of sales is $4,000 ($1,000/3)*12. The beginning inventory is 0. The ending inventory is 0. My average inventory is now 0. I have sales of $4000 per year, and no inventory. This yields an infinite number of turns. This means that all my inventory is being converted and purchased by customers.

This is a business rule of how to calculate inventory turns.

SQL Server principal "dbo" does not exist,

USE [<dbname>]
GO
sp_changedbowner '<user>' -- you can use 'sa' as a quick fix in databases with SQL authentication

KB913423 - You cannot run a statement or a module that includes the EXECUTE AS clause after you restore a database in SQL Server 2005

Copying from one text file to another using Python

f=open('list1.txt')  
f1=open('output.txt','a')
for x in f.readlines():
    f1.write(x)
f.close()
f1.close()

this will work 100% try this once

How to place div in top right hand corner of page

<style type="text/css">
 .topcorner{
  position:absolute;
  top:10;
  right:15;
  }
</style>

You ca also use this in CSS external file.

Cannot execute script: Insufficient memory to continue the execution of the program

Sometimes, due to the heavy size of the script and data, we encounter this type of error. Server needs sufficient memory to execute and give the result. We can simply increase the memory size, per query.

You just need to go to the sql server properties > Memory tab (left side)> Now set the maximum memory limit you want to add.

Also, there is an option at the top, "Results to text", which consume less memory as compare to option "Results to grid", we can also go for Result to Text for less memory execution.

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

How to specify multiple conditions in an if statement in javascript

Wrap them in an extra pair of parens and you're good to go.

if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
    PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

The Python 3 range() object doesn't produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration.

The object also implements the object.__contains__ hook, and calculates if your number is part of its range. Calculating is a (near) constant time operation *. There is never a need to scan through all possible integers in the range.

From the range() object documentation:

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

So at a minimum, your range() object would do:

class my_range:
    def __init__(self, start, stop=None, step=1, /):
        if stop is None:
            start, stop = 0, start
        self.start, self.stop, self.step = start, stop, step
        if step < 0:
            lo, hi, step = stop, start, -step
        else:
            lo, hi = start, stop
        self.length = 0 if lo > hi else ((hi - lo - 1) // step) + 1

    def __iter__(self):
        current = self.start
        if self.step < 0:
            while current > self.stop:
                yield current
                current += self.step
        else:
            while current < self.stop:
                yield current
                current += self.step

    def __len__(self):
        return self.length

    def __getitem__(self, i):
        if i < 0:
            i += self.length
        if 0 <= i < self.length:
            return self.start + i * self.step
        raise IndexError('my_range object index out of range')

    def __contains__(self, num):
        if self.step < 0:
            if not (self.stop < num <= self.start):
                return False
        else:
            if not (self.start <= num < self.stop):
                return False
        return (num - self.start) % self.step == 0

This is still missing several things that a real range() supports (such as the .index() or .count() methods, hashing, equality testing, or slicing), but should give you an idea.

I also simplified the __contains__ implementation to only focus on integer tests; if you give a real range() object a non-integer value (including subclasses of int), a slow scan is initiated to see if there is a match, just as if you use a containment test against a list of all the contained values. This was done to continue to support other numeric types that just happen to support equality testing with integers but are not expected to support integer arithmetic as well. See the original Python issue that implemented the containment test.


* Near constant time because Python integers are unbounded and so math operations also grow in time as N grows, making this a O(log N) operation. Since it’s all executed in optimised C code and Python stores integer values in 30-bit chunks, you’d run out of memory before you saw any performance impact due to the size of the integers involved here.

jQuery - select all text from a textarea

To stop the user from getting annoyed when the whole text gets selected every time they try to move the caret using their mouse, you should do this using the focus event, not the click event. The following will do the job and works around a problem in Chrome that prevents the simplest version (i.e. just calling the textarea's select() method in a focus event handler) from working.

jsFiddle: http://jsfiddle.net/NM62A/

Code:

<textarea id="foo">Some text</textarea>

<script type="text/javascript">
    var textBox = document.getElementById("foo");
    textBox.onfocus = function() {
        textBox.select();

        // Work around Chrome's little problem
        textBox.onmouseup = function() {
            // Prevent further mouseup intervention
            textBox.onmouseup = null;
            return false;
        };
    };
</script>

jQuery version:

$("#foo").focus(function() {
    var $this = $(this);
    $this.select();

    // Work around Chrome's little problem
    $this.mouseup(function() {
        // Prevent further mouseup intervention
        $this.unbind("mouseup");
        return false;
    });
});

Chrome: console.log, console.debug are not working

In my case was webpack having the UglifyPlugin running with drop_console: true set

docker command not found even though installed with apt-get

IMPORTANT - on ubuntu package docker is something entirely different ( avoid it ) :

issue following to view what if any packages you have mentioning docker

dpkg -l|grep docker

if only match is following then you do NOT have docker installed below is an unrelated package

docker - System tray for KDE3/GNOME2 docklet applications

if you see something similar to following then you have docker installed

 dpkg -l|grep docker

ii  docker-ce                                  5:19.03.13~3-0~ubuntu-focal         amd64        Docker: the open-source application container engine
ii  docker-ce-cli                              5:19.03.13~3-0~ubuntu-focal         amd64        Docker CLI: the open-source application container engine

NOTE - ubuntu package docker.io is not getting updates ( obsolete do NOT use )


Instead do this : install the latest version of docker on linux by executing the following:

  sudo curl -sSL https://get.docker.com/ | sh
# sudo curl -sSL https://test.docker.com | sh  # get dev pipeline version
  

here is a typical output ( ubuntu 16.04 )

apparmor is enabled in the kernel and apparmor utils were already installed
+ sudo -E sh -c apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
Executing: /tmp/tmp.rAAGu0P85R/gpg.1.sh --keyserver
hkp://ha.pool.sks-keyservers.net:80
--recv-keys
58118E89F3A912897C070ADBF76221572C52609D
gpg: requesting key 2C52609D from hkp server ha.pool.sks-keyservers.net
gpg: key 2C52609D: "Docker Release Tool (releasedocker) <[email protected]>" 1 new signature
gpg: Total number processed: 1
gpg:         new signatures: 1
+ break
+ sudo -E sh -c apt-key adv -k 58118E89F3A912897C070ADBF76221572C52609D >/dev/null
+ sudo -E sh -c mkdir -p /etc/apt/sources.list.d
+ dpkg --print-architecture
+ sudo -E sh -c echo deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main > /etc/apt/sources.list.d/docker.list
+ sudo -E sh -c sleep 3; apt-get update; apt-get install -y -q docker-engine
Hit:1 http://repo.steampowered.com/steam precise InRelease
Hit:2 http://download.virtualbox.org/virtualbox/debian xenial InRelease                                                           
Ign:3 http://dl.google.com/linux/chrome/deb stable InRelease                                                                      
Hit:4 http://dl.google.com/linux/chrome/deb stable Release                                                                        
Hit:5 http://archive.canonical.com/ubuntu xenial InRelease                                                                        
Hit:6 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial InRelease                                                     
Hit:7 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-updates InRelease                                             
Hit:8 http://ppa.launchpad.net/me-davidsansome/clementine/ubuntu xenial InRelease                                                 
Ign:9 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 InRelease                                                         
Hit:10 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-backports InRelease                                          
Hit:11 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 Release                                                          
Hit:12 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-security InRelease                                           
Hit:14 http://ppa.launchpad.net/numix/ppa/ubuntu xenial InRelease                                                                 
Ign:15 http://linux.dropbox.com/ubuntu wily InRelease                                                                             
Ign:16 http://repo.vivaldi.com/stable/deb stable InRelease                                                                        
Hit:17 http://repo.vivaldi.com/stable/deb stable Release                                                                          
Get:18 http://linux.dropbox.com/ubuntu wily Release [6,596 B]            
Get:19 https://apt.dockerproject.org/repo ubuntu-xenial InRelease [20.6 kB]    
Ign:20 http://packages.amplify.nginx.com/ubuntu xenial InRelease                      
Hit:22 http://packages.amplify.nginx.com/ubuntu xenial Release
Hit:23 https://deb.opera.com/opera-beta stable InRelease
Hit:26 https://deb.opera.com/opera-developer stable InRelease
Get:28 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 Packages [1,719 B]
Hit:29 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Fetched 28.9 kB in 1s (17.2 kB/s)
Reading package lists... Done
W: http://repo.mongodb.org/apt/debian/dists/wheezy/mongodb-org/3.2/Release.gpg: Signature by key 42F3E95A2C4F08279C4960ADD68FA50FEA312927 uses weak digest algorithm (SHA1)
Reading package lists...
Building dependency tree...
Reading state information...
The following additional packages will be installed:
  aufs-tools cgroupfs-mount
The following NEW packages will be installed:
  aufs-tools cgroupfs-mount docker-engine
0 upgraded, 3 newly installed, 0 to remove and 17 not upgraded.
Need to get 14.6 MB of archives.
After this operation, 73.7 MB of additional disk space will be used.
Get:1 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 aufs-tools amd64 1:3.2+20130722-1.1ubuntu1 [92.9 kB]
Get:2 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 cgroupfs-mount all 1.2 [4,970 B]
Get:3 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 docker-engine amd64 1.11.2-0~xenial [14.5 MB]
Fetched 14.6 MB in 7s (2,047 kB/s)
Selecting previously unselected package aufs-tools.
(Reading database ... 427978 files and directories currently installed.)
Preparing to unpack .../aufs-tools_1%3a3.2+20130722-1.1ubuntu1_amd64.deb ...
Unpacking aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Selecting previously unselected package cgroupfs-mount.
Preparing to unpack .../cgroupfs-mount_1.2_all.deb ...
Unpacking cgroupfs-mount (1.2) ...
Selecting previously unselected package docker-engine.
Preparing to unpack .../docker-engine_1.11.2-0~xenial_amd64.deb ...
Unpacking docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for systemd (229-4ubuntu6) ...
Setting up aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Setting up cgroupfs-mount (1.2) ...
Setting up docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu6) ...
Processing triggers for ureadahead (0.100.0-19) ...
+ sudo -E sh -c docker version
Client:
 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

Server:
 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  sudo usermod -aG docker stens

Remember that you will have to log out and back in for this to take effect!

Here is the underlying detailed install instructions which as you can see comes bundled into above technique ... Above one liner gives you same as :

https://docs.docker.com/engine/installation/linux/ubuntulinux/

Once installed you can see what docker packages were installed by issuing

dpkg -l|grep docker
ii  docker-ce                                  5:19.03.13~3-0~ubuntu-focal         amd64        Docker: the open-source application container engine
ii  docker-ce-cli                              5:19.03.13~3-0~ubuntu-focal         amd64        Docker CLI: the open-source application container engine

now Docker updates will get installed going forward when you issue

sudo apt-get update
sudo apt-get upgrade

take a look at

 ls -latr /etc/apt/sources.list.d/*docker*
-rw-r--r-- 1 root root 202 Jun 23 10:01 /etc/apt/sources.list.d/docker.list.save
-rw-r--r-- 1 root root  71 Jul  4 11:32 /etc/apt/sources.list.d/docker.list


cat /etc/apt/sources.list.d/docker.list

deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main

or more generally

cd /etc/apt
grep -r docker *
sources.list.d/docker.list:deb [arch=amd64] https://download.docker.com/linux/ubuntu focal test

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

A 'for' loop to iterate over an enum in Java

If you don't care about the order this should work:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff
}

How do I properly set the permgen size?

Don't put the environment configuration in catalina.bat/catalina.sh. Instead you should create a new file in CATALINA_BASE\bin\setenv.bat to keep your customizations separate of tomcat installation.

Progress Bar with HTML and CSS

Same as @RoToRa's answer, with a some slight adjustments (correct colors and dimensions):

_x000D_
_x000D_
body {_x000D_
  background-color: #636363;_x000D_
  padding: 1em;_x000D_
}_x000D_
_x000D_
#progressbar {_x000D_
  background-color: #20201F;_x000D_
  border-radius: 20px; /* (heightOfInnerDiv / 2) + padding */_x000D_
  padding: 4px;_x000D_
}_x000D_
_x000D_
#progressbar>div {_x000D_
  background-color: #F7901E;_x000D_
  width: 48%;_x000D_
  /* Adjust with JavaScript */_x000D_
  height: 16px;_x000D_
  border-radius: 10px;_x000D_
}
_x000D_
<div id="progressbar">_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's the fiddle: jsFiddle

And here's what it looks like: jsFiddle-screenshot

How to construct a std::string from a std::vector<char>?

Just for completeness, another way is std::string(&v[0]) (although you need to ensure your string is null-terminated and std::string(v.data()) is generally to be preferred.

The difference is that you can use the former technique to pass the vector to functions that want to modify the buffer, which you cannot do with .data().

Adding a default value in dropdownlist after binding with database

You can add it programmatically or in the markup, but if you add it programmatically, rather than Add the item, you should Insert it as position zero so that it is the first item:

ddlColor.DataSource = from p in db.ProductTypes
                      where p.ProductID == pID
                      orderby p.Color
                      select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");

The default item is expected to be the first item in the list. If you just Add it, it will be on the bottom and will not be selected by default.

Saving and loading objects and using pickle

Always open in binary mode, in this case

file = open("Fruits.obj",'rb')

Import Excel Data into PostgreSQL 9.3

You can handle loading the excel file content by writing Java code using Apache POI library (https://poi.apache.org/). The library is developed for working with MS office application data including Excel.

I have recently created the application based on the technology that will help you to load Excel files to the Postgres database. The application is available under http://www.abespalov.com/. The application is tested only for Windows, but should work for Linux as well.

The application automatically creates necessary tables with the same columns as in the Excel files and populate the tables with content. You can export several files in parallel. You can skip the step to convert the files into the CSV format. The application handles the xls and xlsx formats.

Overall application stages are :

  1. Load the excel file content. Here is the code depending on file extension:

{

fileExtension = FilenameUtils.getExtension(inputSheetFile.getName());
    if (fileExtension.equalsIgnoreCase("xlsx")) {
        workbook = createWorkbook(openOPCPackage(inputSheetFile));
    } else {
        workbook =     
        createWorkbook(openNPOIFSFileSystemPackage(inputSheetFile));
    }

sheet = workbook.getSheetAt(0);

}

  1. Establish Postgres JDBC connection
  2. Create a Postgres table
  3. Iterate over the sheet and inset rows into the table. Here is a piece of Java code :

{

Iterator<Row> rowIterator = InitInputFilesImpl.sheet.rowIterator();

//skip a header
if (rowIterator.hasNext()) {
    rowIterator.next();
}
while (rowIterator.hasNext()) {
    Row row = (Row) rowIterator.next();
    // inserting rows
}  

}

Here you can find all Java code for the application created for exporting excel to Postgres (https://github.com/palych-piter/Excel2DB).

How to implement DrawerArrowToggle from Android appcompat v7 21 library

If you are using the Support Library provided DrawerLayout as suggested in the Creating a navigation drawer training, you can use the newly added android.support.v7.app.ActionBarDrawerToggle (note: different from the now deprecated android.support.v4.app.ActionBarDrawerToggle):

shows a Hamburger icon when drawer is closed and an arrow when drawer is open. It animates between these two states as the drawer opens.

While the training hasn't been updated to take the deprecation/new class into account, you should be able to use it almost exactly the same code - the only difference in implementing it is the constructor.

react-router scroll to top on every transition

I wrote a Higher-Order Component called withScrollToTop. This HOC takes in two flags:

  • onComponentWillMount - Whether to scroll to top upon navigation (componentWillMount)
  • onComponentDidUpdate - Whether to scroll to top upon update (componentDidUpdate). This flag is necessary in cases where the component is not unmounted but a navigation event occurs, for example, from /users/1 to /users/2.

// @flow
import type { Location } from 'react-router-dom';
import type { ComponentType } from 'react';

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

type Props = {
  location: Location,
};

type Options = {
  onComponentWillMount?: boolean,
  onComponentDidUpdate?: boolean,
};

const defaultOptions: Options = {
  onComponentWillMount: true,
  onComponentDidUpdate: true,
};

function scrollToTop() {
  window.scrollTo(0, 0);
}

const withScrollToTop = (WrappedComponent: ComponentType, options: Options = defaultOptions) => {
  return class withScrollToTopComponent extends Component<Props> {
    props: Props;

    componentWillMount() {
      if (options.onComponentWillMount) {
        scrollToTop();
      }
    }

    componentDidUpdate(prevProps: Props) {
      if (options.onComponentDidUpdate &&
        this.props.location.pathname !== prevProps.location.pathname) {
        scrollToTop();
      }
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
};

export default (WrappedComponent: ComponentType, options?: Options) => {
  return withRouter(withScrollToTop(WrappedComponent, options));
};

To use it:

import withScrollToTop from './withScrollToTop';

function MyComponent() { ... }

export default withScrollToTop(MyComponent);

How can I find last row that contains data in a specific column?

Simple and quick:

Dim lastRow as long
Range("A1").select
lastRow = Cells.Find("*",SearchOrder:=xlByRows,SearchDirection:=xlPrevious).Row

Example use:

cells(lastRow,1)="Ultima Linha, Last Row. Youpi!!!!"

'or 

Range("A" & lastRow).Value = "FIM, THE END"

exception in thread 'main' java.lang.NoClassDefFoundError:

You can find information about required libraries inside pom.xml, it is much easier to use tools like Apache Maven to build java applications.

    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.20</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-text</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-math3</artifactId>
        <version>3.6.1</version>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>24.0-jre</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.25</version>
    </dependency>
    <dependency>
        <groupId>com.google.inject</groupId>
        <artifactId>guice</artifactId>
        <version>4.2.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.inject.extensions</groupId>
        <artifactId>guice-assistedinject</artifactId>
        <version>4.2.0</version>
    </dependency>

Why is lock(this) {...} bad?

You can establish a rule that says that a class can have code that locks on 'this' or any object that the code in the class instantiates. So it's only a problem if the pattern is not followed.

If you want to protect yourself from code that won't follow this pattern, then the accepted answer is correct. But if the pattern is followed, it's not a problem.

The advantage of lock(this) is efficiency. What if you have a simple "value object" that holds a single value. It's just a wrapper, and it gets instantiated millions of times. By requiring the creation of a private sync object just for locking, you've basically doubled the size of the object and doubled the number of allocations. When performance matters, this is an advantage.

When you don't care about number of allocations or memory footprint, avoiding lock(this) is preferable for the reasons indicated in other answers.

How to convert a String into an array of Strings containing one character each

Use toCharArray() method. It splits the string into an array of characters:

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#toCharArray%28%29

String str = "aabbab";
char[] chs = str.toCharArray();

How to send multiple data fields via Ajax?

Try with quotes:

data: {"status": status, "name": name}

It must work fine.

HTML embed autoplay="false", but still plays automatically

Just set using JS as follows:

<script>
    var vid = document.getElementById("myVideo");
    vid.autoplay = false;
    vid.load();
</script>

Set true to turn on autoplay. Set false to turn off autoplay.

http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_autoplay

How to kill/stop a long SQL query immediately?

If you cancel and see that run

 sp_who2 'active'

(Activity Monitor won't be available on old sql server 2000 FYI )

Spot the SPID you wish to kill e.g. 81

Kill 81

Run the sp_who2 'active' again and you will probably notice it is sleeping ... rolling back

To get the STATUS run again the KILL

Kill 81 

Then you will get a message like this

 SPID 81: transaction rollback in progress. Estimated rollback completion: 63%. Estimated time remaining: 992 seconds.

Read MS Exchange email in C#

It's a mess. MAPI or CDO via a .NET interop DLL is officially unsupported by Microsoft--it will appear to work fine, but there are problems with memory leaks due to their differing memory models. You could use CDOEX, but that only works on the Exchange server itself, not remotely; useless. You could interop with Outlook, but now you've just made a dependency on Outlook; overkill. Finally, you could use Exchange 2003's WebDAV support, but WebDAV is complicated, .NET has poor built-in support for it, and (to add insult to injury) Exchange 2007 nearly completely drops WebDAV support.

What's a guy to do? I ended up using AfterLogic's IMAP component to communicate with my Exchange 2003 server via IMAP, and this ended up working very well. (I normally seek out free or open-source libraries, but I found all of the .NET ones wanting--especially when it comes to some of the quirks of 2003's IMAP implementation--and this one was cheap enough and worked on the first try. I know there are others out there.)

If your organization is on Exchange 2007, however, you're in luck. Exchange 2007 comes with a SOAP-based Web service interface that finally provides a unified, language-independent way of interacting with the Exchange server. If you can make 2007+ a requirement, this is definitely the way to go. (Sadly for me, my company has a "but 2003 isn't broken" policy.)

If you need to bridge both Exchange 2003 and 2007, IMAP or POP3 is definitely the way to go.

Can not find module “@angular-devkit/build-angular”

npm install --save-dev @angular-devkit/build-angular

It's Install @angular-devkit/build-angular as dev dependency. This package is newly introduced in Angular 6.0

MySQL LIKE IN()?

This would be correct:

SELECT * FROM table WHERE field regexp concat_ws("|",(
"111",
"222",
"333"
));

Test if a property is available on a dynamic variable

Following on from the answer by @karask, you could wrap the function as a helper like so:

public static bool HasProperty(ExpandoObject expandoObj,
                               string name)
{
    return ((IDictionary<string, object>)expandoObj).ContainsKey(name);
}

How can I conditionally require form inputs with AngularJS?

if you want put a input required if other is written:

   <input type='text'
   name='name'
   ng-model='person.name'/>

   <input type='text'
   ng-model='person.lastname'             
   ng-required='person.name' />  

Regards.

Find a private field with Reflection?

typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)

Characters allowed in GET parameter

All of the rules concerning the encoding of URIs (which contains URNs and URLs) are specified in the RFC1738 and the RFC3986, here's a TL;DR of these long and boring documents:

Percent-encoding, also known as URL encoding, is a mechanism for encoding information in a URI under certain circumstances. The characters allowed in a URI are either reserved or unreserved. Reserved characters are those characters that sometimes have special meaning, but they are not the only characters that needs encoding.

There are 66 unreserved characters that doesn't need any encoding: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~

There are 18 reserved characters which needs to be encoded: !*'();:@&=+$,/?#[], and all the other characters must be encoded.

To percent-encode a character, simply concatenate "%" and its ASCII value in hexadecimal. The php functions "urlencode" and "rawurlencode" do this job for you.

Read from a gzip file in python

python: read lines from compressed text files

Using gzip.GzipFile:

import gzip

with gzip.open('input.gz','r') as fin:        
    for line in fin:        
        print('got line', line)

error::make_unique is not a member of ‘std’

If you are stuck with c++11, you can get make_unique from abseil-cpp, an open source collection of C++ libraries drawn from Google’s internal codebase.

ArrayAdapter in android to create simple listview

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

I am also new to Android , so i might be wrong. But as per my understanding while using this for listview creation 2nd argument is the layout of list items. A layout consists of many views (image view,text view etc). With 3rd argument you are specifying in which view or textview you want the text to be displayed.

View tabular file such as CSV from command line

If you're a vimmer, use the CSV plugin, which is juuust beautiful.

What is the significance of load factor in HashMap?

If the buckets get too full, then we have to look through

a very long linked list.

And that's kind of defeating the point.

So here's an example where I have four buckets.

I have elephant and badger in my HashSet so far.

This is a pretty good situation, right?

Each element has zero or one elements.

Now we put two more elements into our HashSet.

     buckets      elements
      -------      -------
        0          elephant
        1          otter
         2          badger
         3           cat

This isn't too bad either.

Every bucket only has one element . So if I wanna know, does this contain panda?

I can very quickly look at bucket number 1 and it's not

there and

I known it's not in our collection.

If I wanna know if it contains cat, I look at bucket

number 3,

I find cat, I very quickly know if it's in our

collection.

What if I add koala, well that's not so bad.

             buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala 
         2          badger
         3           cat

Maybe now instead of in bucket number 1 only looking at

one element,

I need to look at two.

But at least I don't have to look at elephant, badger and

cat.

If I'm again looking for panda, it can only be in bucket

number 1 and

I don't have to look at anything other then otter and

koala.

But now I put alligator in bucket number 1 and you can

see maybe where this is going.

That if bucket number 1 keeps getting bigger and bigger and

bigger, then I'm basically having to look through all of

those elements to find

something that should be in bucket number 1.

            buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala ->alligator
         2          badger
         3           cat

If I start adding strings to other buckets,

right, the problem just gets bigger and bigger in every

single bucket.

How do we stop our buckets from getting too full?

The solution here is that

          "the HashSet can automatically

        resize the number of buckets."

There's the HashSet realizes that the buckets are getting

too full.

It's losing this advantage of this all of one lookup for

elements.

And it'll just create more buckets(generally twice as before) and

then place the elements into the correct bucket.

So here's our basic HashSet implementation with separate

chaining. Now I'm going to create a "self-resizing HashSet".

This HashSet is going to realize that the buckets are

getting too full and

it needs more buckets.

loadFactor is another field in our HashSet class.

loadFactor represents the average number of elements per

bucket,

above which we want to resize.

loadFactor is a balance between space and time.

If the buckets get too full then we'll resize.

That takes time, of course, but

it may save us time down the road if the buckets are a

little more empty.

Let's see an example.

Here's a HashSet, we've added four elements so far.

Elephant, dog, cat and fish.

          buckets      elements
      -------      -------
        0          
        1          elephant
         2          cat ->dog
         3           fish
          4         
           5

At this point, I've decided that the loadFactor, the

threshold,

the average number of elements per bucket that I'm okay

with, is 0.75.

The number of buckets is buckets.length, which is 6, and

at this point our HashSet has four elements, so the

current size is 4.

We'll resize our HashSet, that is we'll add more buckets,

when the average number of elements per bucket exceeds

the loadFactor.

That is when current size divided by buckets.length is

greater than loadFactor.

At this point, the average number of elements per bucket

is 4 divided by 6.

4 elements, 6 buckets, that's 0.67.

That's less than the threshold I set of 0.75 so we're

okay.

We don't need to resize.

But now let's say we add woodchuck.

                  buckets      elements
      -------      -------
        0          
        1          elephant
         2        woodchuck-> cat ->dog
         3           fish
          4         
           5

Woodchuck would end up in bucket number 3.

At this point, the currentSize is 5.

And now the average number of elements per bucket

is the currentSize divided by buckets.length.

That's 5 elements divided by 6 buckets is 0.83.

And this exceeds the loadFactor which was 0.75.

In order to address this problem, in order to make the

buckets perhaps a little

more empty so that operations like determining whether a

bucket contains

an element will be a little less complex, I wanna resize

my HashSet.

Resizing the HashSet takes two steps.

First I'll double the number of buckets, I had 6 buckets,

now I'm going to have 12 buckets.

Note here that the loadFactor which I set to 0.75 stays the same.

But the number of buckets changed is 12,

the number of elements stayed the same, is 5.

5 divided by 12 is around 0.42, that's well under our

loadFactor,

so we're okay now.

But we're not done because some of these elements are in

the wrong bucket now.

For instance, elephant.

Elephant was in bucket number 2 because the number of

characters in elephant

was 8.

We have 6 buckets, 8 minus 6 is 2.

That's why it ended up in number 2.

But now that we have 12 buckets, 8 mod 12 is 8, so

elephant does not belong in bucket number 2 anymore.

Elephant belongs in bucket number 8.

What about woodchuck?

Woodchuck was the one that started this whole problem.

Woodchuck ended up in bucket number 3.

Because 9 mod 6 is 3.

But now we do 9 mod 12.

9 mod 12 is 9, woodchuck goes to bucket number 9.

And you see the advantage of all this.

Now bucket number 3 only has two elements whereas before it had 3.

So here's our code,

where we had our HashSet with separate chaining that

didn't do any resizing.

Now, here's a new implementation where we use resizing.

Most of this code is the same,

we're still going to determine whether it contains the

value already.

If it doesn't, then we'll figure it out which bucket it

should go into and

then add it to that bucket, add it to that LinkedList.

But now we increment the currentSize field.

currentSize was the field that kept track of the number

of elements in our HashSet.

We're going to increment it and then we're going to look

at the average load,

the average number of elements per bucket.

We'll do that division down here.

We have to do a little bit of casting here to make sure

that we get a double.

And then, we'll compare that average load to the field

that I've set as

0.75 when I created this HashSet, for instance, which was

the loadFactor.

If the average load is greater than the loadFactor,

that means there's too many elements per bucket on

average, and I need to reinsert.

So here's our implementation of the method to reinsert

all the elements.

First, I'll create a local variable called oldBuckets.

Which is referring to the buckets as they currently stand

before I start resizing everything.

Note I'm not creating a new array of linked lists just yet.

I'm just renaming buckets as oldBuckets.

Now remember buckets was a field in our class, I'm going

to now create a new array

of linked lists but this will have twice as many elements

as it did the first time.

Now I need to actually do the reinserting,

I'm going to iterate through all of the old buckets.

Each element in oldBuckets is a LinkedList of strings

that is a bucket.

I'll go through that bucket and get each element in that

bucket.

And now I'm gonna reinsert it into the newBuckets.

I will get its hashCode.

I will figure out which index it is.

And now I get the new bucket, the new LinkedList of

strings and

I'll add it to that new bucket.

So to recap, HashSets as we've seen are arrays of Linked

Lists, or buckets.

A self resizing HashSet can realize using some ratio or

How to rotate x-axis tick labels in Pandas barplot

The follows might be helpful:

# Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, None

plt.xticks(
    rotation=45,
    horizontalalignment='right',
    fontweight='light',
    fontsize='medium',
)

Here is the function xticks[reference] with example and API

def xticks(ticks=None, labels=None, **kwargs):
    """
    Get or set the current tick locations and labels of the x-axis.

    Call signatures::

        locs, labels = xticks()            # Get locations and labels
        xticks(ticks, [labels], **kwargs)  # Set locations and labels

    Parameters
    ----------
    ticks : array_like
        A list of positions at which ticks should be placed. You can pass an
        empty list to disable xticks.

    labels : array_like, optional
        A list of explicit labels to place at the given *locs*.

    **kwargs
        :class:`.Text` properties can be used to control the appearance of
        the labels.

    Returns
    -------
    locs
        An array of label locations.
    labels
        A list of `.Text` objects.

    Notes
    -----
    Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
    equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
    the current axes.
    Calling this function with arguments is the pyplot equivalent of calling
    `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.

    Examples
    --------
    Get the current locations and labels:

        >>> locs, labels = xticks()

    Set label locations:

        >>> xticks(np.arange(0, 1, step=0.2))

    Set text labels:

        >>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))

    Set text labels and properties:

        >>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)

    Disable xticks:

        >>> xticks([])
    """

How do I call an Angular 2 pipe with multiple arguments?

In your component's template you can use multiple arguments by separating them with colons:

{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}

From your code it will look like this:

new MyPipe().transform(myData, arg1, arg2, arg3)

And in your transform function inside your pipe you can use the arguments like this:

export class MyPipe implements PipeTransform { 
    // specify every argument individually   
    transform(value: any, arg1: any, arg2: any, arg3: any): any { }
    // or use a rest parameter
    transform(value: any, ...args: any[]): any { }
}

Beta 16 and before (2016-04-26)

Pipes take an array that contains all arguments, so you need to call them like this:

new MyPipe().transform(myData, [arg1, arg2, arg3...])

And your transform function will look like this:

export class MyPipe implements PipeTransform {    
    transform(value:any, args:any[]):any {
        var arg1 = args[0];
        var arg2 = args[1];
        ...
    }
}

Cannot resolve symbol 'AppCompatActivity'

Cannot resolve symbol AppCompatActivity Issue.

Do the Simple Step to resolve the problem.

i) Exit the Android studio.

ii) Go to your project directory.

iii) Find the .idea folder in your project directory.

iv) Delete .idea folder.

v) Restart your android studio.

vi) The Issue Will be resolved.

How to Get enum item name from its value

No, you have no way to get the "name" from the value in C++ because all the symbols are discarded during compilation.

You may need this way X Macros

Scrolling to an Anchor using Transition/CSS3

You can find the answer to your question on the following page:

https://stackoverflow.com/a/17633941/2359161

Here is the JSFiddle that was given:

http://jsfiddle.net/YYPKM/3/

Note the scrolling section at the end of the CSS, specifically:

_x000D_
_x000D_
/*_x000D_
 *Styling_x000D_
 */_x000D_
_x000D_
html,body {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    position: relative; _x000D_
}_x000D_
body {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: #fff; _x000D_
position: fixed; _x000D_
left: 0; top: 0; _x000D_
width:100%;_x000D_
height: 3.5rem;_x000D_
z-index: 10; _x000D_
}_x000D_
_x000D_
nav {_x000D_
width: 100%;_x000D_
padding-top: 0.5rem;_x000D_
}_x000D_
_x000D_
nav ul {_x000D_
list-style: none;_x000D_
width: inherit; _x000D_
margin: 0; _x000D_
}_x000D_
_x000D_
_x000D_
ul li:nth-child( 3n + 1), #main .panel:nth-child( 3n + 1) {_x000D_
background: rgb( 0, 180, 255 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 2), #main .panel:nth-child( 3n + 2) {_x000D_
background: rgb( 255, 65, 180 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 3), #main .panel:nth-child( 3n + 3) {_x000D_
background: rgb( 0, 255, 180 );_x000D_
}_x000D_
_x000D_
ul li {_x000D_
display: inline-block; _x000D_
margin: 0 8px;_x000D_
margin: 0 0.5rem;_x000D_
padding: 5px 8px;_x000D_
padding: 0.3rem 0.5rem;_x000D_
border-radius: 2px; _x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
color: #fff;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
width: 100%;_x000D_
height: 500px;_x000D_
z-index:0; _x000D_
-webkit-transform: translateZ( 0 );_x000D_
transform: translateZ( 0 );_x000D_
-webkit-transition: -webkit-transform 0.6s ease-in-out;_x000D_
transition: transform 0.6s ease-in-out;_x000D_
-webkit-backface-visibility: hidden;_x000D_
backface-visibility: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.panel h1 {_x000D_
font-family: sans-serif;_x000D_
font-size: 64px;_x000D_
font-size: 4rem;_x000D_
color: #fff;_x000D_
position:relative;_x000D_
line-height: 200px;_x000D_
top: 33%;_x000D_
text-align: center;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
/*_x000D_
 *Scrolling_x000D_
 */_x000D_
_x000D_
a[ id= "servicios" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( 0px);_x000D_
transform: translateY( 0px );_x000D_
}_x000D_
_x000D_
a[ id= "galeria" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -500px );_x000D_
transform: translateY( -500px );_x000D_
}_x000D_
a[ id= "contacto" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -1000px );_x000D_
transform: translateY( -1000px );_x000D_
}
_x000D_
<a id="servicios"></a>_x000D_
<a id="galeria"></a>_x000D_
<a id="contacto"></a>_x000D_
<header class="nav">_x000D_
<nav>_x000D_
    <ul>_x000D_
        <li><a href="#servicios"> Servicios </a> </li>_x000D_
        <li><a href="#galeria"> Galeria </a> </li>_x000D_
        <li><a href="#contacto">Contacta  nos </a> </li>_x000D_
    </ul>_x000D_
</nav>_x000D_
</header>_x000D_
_x000D_
<section id="main">_x000D_
<article class="panel" id="servicios">_x000D_
    <h1> Nuestros Servicios</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="galeria">_x000D_
    <h1> Mustra de nuestro trabajos</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="contacto">_x000D_
    <h1> Pongamonos en contacto</h1>_x000D_
</article>_x000D_
</section>
_x000D_
_x000D_
_x000D_

heroku - how to see all the logs

To see the detailed log you need to put two lines in the production.rb file:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::DEBUG

and then by running

heroku logs -t

you can see the detailed logs.

How can I hide the Android keyboard using JavaScript?

Giving soft keyboard some time to close works for me.

$('#ButtonCancel').click(function () {
    document.body.focus();

    setTimeout(function () {
        //close the dialog, switch to another screen, etc.
    }, 300);
});

API vs. Webservice

API(Application Programming Interface), the full form itself suggests that its an Interface which allows you to program for your application with the help or support of some other Application's Interface which exposes some sort of functionality which is useful to your application.

E.g showing updated currency exchange rates on your website would need some third party Interface to program against unless you plan to have your own database with currency rates and regular updates to the same. This set of functionality is when already available with some one else and when they want to share it with others they have to have an endpoint to communicate with the others who are interested in such interactions so they deploy it on web by the means of web-services. This end point is nothing but interface of their application which you can program against hence API.

Bootstrap modal z-index

I found this question as I had a similar problem. While data-backdrop does "solve" the issue; I found another problem in my markup.

I had the button which launched this modal and the modal dialog itself was in the footer. The problem is that the footer was defined as navbar_fixed_bottom, and that contained position:fixed.

After I moved the dialog outside of the fixed section, everything worked as expected.