Programs & Examples On #Address bar

Address bar, "location bar" or "Omnibox" refers to the bar in web browsers which is used to navigate between pages using URLs.

Open new popup window without address bars in firefox & IE

Firefox 3.0 and higher have disabled setting location by default. resizable and status are also disabled by default. You can verify this by typing `about:config' in your address bar and filtering by "dom". The items of interest are:

  • dom.disable_window_open_feature.location
  • dom.disable_window_open_feature.resizable
  • dom.disable_window_open_feature.status

You can get further information at the Mozilla Developer site. What this basically means, though, is that you won't be able to do what you want to do.

One thing you might want to do (though it won't solve your problem), is put quotes around your window feature parameters, like so:

window.open('/pageaddress.html','winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');

How to hide a mobile browser's address bar?

In chrome lastest. Add following css it auto hide address bar (URL bar) when scroll!

html { height: 100vh; }
body { height: 100%; }

And this is why: https://developers.google.com/web/updates/2016/12/url-bar-resizing

Hope to helpful!

Declaring and initializing a string array in VB.NET

Array initializer support for type inference were changed in Visual Basic 10 vs Visual Basic 9.

In previous version of VB it was required to put empty parens to signify an array. Also, it would define the array as object array unless otherwise was stated:

' Integer array
Dim i as Integer() = {1, 2, 3, 4} 

' Object array
Dim o() = {1, 2, 3} 

Check more info:

Visual Basic 2010 Breaking Changes

Collection and Array Initializers in Visual Basic 2010

How to get a user's client IP address in ASP.NET?

use in ashx file

public string getIP(HttpContext c)
{
    string ips = c.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (!string.IsNullOrEmpty(ips))
    {
        return ips.Split(',')[0];
    }
    return c.Request.ServerVariables["REMOTE_ADDR"];
}

Is there a decent wait function in C++?

There is a C++11 way of doing it. It is quite simple, and I believe it is portable. Of course, as Lightness Races in Orbit pointed out, you should not do this in order to be able to see an Hello World in your terminal, but there exist some good reason to use a wait function. Without further ado,

#include <chrono> // std::chrono::microseconds
#include <thread> // std::this_thread::sleep_for
std::this_thread::sleep_for(std::chrono::microseconds{});

More details are available here. See also sleep_until.

How do I open a second window from the first window in WPF?

private void button1_Click(object sender, RoutedEventArgs e)
{
    window2 win2 = new window2();
    win2.Show();
}

Haversine Formula in Python (Bearing and Distance between two GPS points)

Here are two functions to calculate distance and bearing, which are based on the code in previous messages and https://gist.github.com/jeromer/2005586 (added tuple type for geographical points in lat, lon format for both functions for clarity). I tested both functions and they seem to work right.

#coding:UTF-8
from math import radians, cos, sin, asin, sqrt, atan2, degrees

def haversine(pointA, pointB):

    if (type(pointA) != tuple) or (type(pointB) != tuple):
        raise TypeError("Only tuples are supported as arguments")

    lat1 = pointA[0]
    lon1 = pointA[1]

    lat2 = pointB[0]
    lon2 = pointB[1]

    # convert decimal degrees to radians 
    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2]) 

    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles
    return c * r


def initial_bearing(pointA, pointB):

    if (type(pointA) != tuple) or (type(pointB) != tuple):
        raise TypeError("Only tuples are supported as arguments")

    lat1 = radians(pointA[0])
    lat2 = radians(pointB[0])

    diffLong = radians(pointB[1] - pointA[1])

    x = sin(diffLong) * cos(lat2)
    y = cos(lat1) * sin(lat2) - (sin(lat1)
            * cos(lat2) * cos(diffLong))

    initial_bearing = atan2(x, y)

    # Now we have the initial bearing but math.atan2 return values
    # from -180° to + 180° which is not what we want for a compass bearing
    # The solution is to normalize the initial bearing as shown below
    initial_bearing = degrees(initial_bearing)
    compass_bearing = (initial_bearing + 360) % 360

    return compass_bearing

pA = (46.2038,6.1530)
pB = (46.449, 30.690)

print haversine(pA, pB)

print initial_bearing(pA, pB)

What is the correct way of reading from a TCP socket in C/C++?

This is an article that I always refer to when working with sockets..

THE WORLD OF SELECT()

It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.

Change font size of UISegmentedControl

In swift 5,

let font = UIFont.systemFont(ofSize: 16)
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)

How to check certificate name and alias in keystore files?

You can run the following command to list the content of your keystore file (and alias name):

keytool -v -list -keystore .keystore

If you are looking for a specific alias, you can also specify it in the command:

keytool -list -keystore .keystore -alias foo

If the alias is not found, it will display an exception:

keytool error: java.lang.Exception: Alias does not exist

DataTables: Cannot read property 'length' of undefined

If you are using ajax as a function remember it expects JSON data to be returned to it, with the parameters set.

$('#example').dataTable({
    "ajax" : function (data, callback, settings) {
        callback({
            data: [...],
            recordsTotal: 40,
            recordsFiltered: 40}
            ));
    }
})

visual c++: #include files from other projects in the same solution

Since both projects are under the same solution, there's a simpler way for the include files and linker as described in https://docs.microsoft.com/en-us/cpp/build/adding-references-in-visual-cpp-projects?view=vs-2019 :

  1. The include can be written in a relative path (E.g. #include "../libProject/libHeader.h").
  2. For the linker, right click on "References", Click on Add Reference, and choose the other project.

How to create a function in SQL Server

You can use stuff in place of replace for avoiding the bug that Hamlet Hakobyan has mentioned

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250)) 
RETURNS VARCHAR(250) 
AS BEGIN
   DECLARE @Work VARCHAR(250)
   SET @Work = @Input

   --SET @Work = REPLACE(@Work, 'www.', '')
   SET @Work = Stuff(@Work,1,4, '')
   SET @Work = REPLACE(@Work, '.com', '')

   RETURN @work 
END

bad operand types for binary operator "&" java

Because & has a lesser priority than ==.

Your code is equivalent to a[0] & (1 == 0), and unless a[0] is a boolean this won't compile...

You need to:

(a[0] & 1) == 0

etc etc.

(yes, Java does hava a boolean & operator -- a non shortcut logical and)

Difference between Static and final?

Static and final have some big differences:

Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:

public class Test{    
   public final int first = 10;
   public static int second = 20;

   public Test(){
     second = second + 1
     first = first + 1;
   }
}

The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

My own solution on Linux (under ~/.config/smartgit/19.1) is to comment or remove line listx from preferences.yml file and reopen program.

Deleting the all folders will make you reconfigure everything (useless).

What is a plain English explanation of "Big O" notation?

"What is a plain English explanation of Big O? With as little formal definition as possible and simple mathematics."

Such a beautifully simple and short question seems at least to deserve an equally short answer, like a student might receive during tutoring.

Big O notation simply tells how much time* an algorithm can run within, in terms of only the amount of input data**.

( *in a wonderful, unit-free sense of time!)
(**which is what matters, because people will always want more, whether they live today or tomorrow)

Well, what's so wonderful about Big O notation if that's what it does?

  • Practically speaking, Big O analysis is so useful and important because Big O puts the focus squarely on the algorithm's own complexity and completely ignores anything that is merely a proportionality constant—like a JavaScript engine, the speed of a CPU, your Internet connection, and all those things which become quickly become as laughably outdated as a Model T. Big O focuses on performance only in the way that matters equally as much to people living in the present or in the future.

  • Big O notation also shines a spotlight directly on the most important principle of computer programming/engineering, the fact which inspires all good programmers to keep thinking and dreaming: the only way to achieve results beyond the slow forward march of technology is to invent a better algorithm.

How do you create a remote Git branch?

First, you must create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Teammates can reach your branch, by doing:

git fetch
git checkout origin/your_branch

You can continue working in the branch and pushing whenever you want without passing arguments to git push (argumentless git push will push the master to remote master, your_branch local to remote your_branch, etc...)

git push

Teammates can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch

Or tracking the branch to avoid the arguments to git push

git checkout --track -b your_branch origin/your_branch
... work ...
git commit
... work ...
git commit
git push

Slack clean all messages (~8K) in a channel

I wrote a simple node script for deleting messages from public/private channels and chats. You can modify and use it.

https://gist.github.com/firatkucuk/ee898bc919021da621689f5e47e7abac

First, modify your token in the scripts configuration section then run the script:

node ./delete-slack-messages CHANNEL_ID

Get an OAuth token:

  1. Go to https://api.slack.com/apps
  2. Click 'Create New App', and name your (temporary) app.
  3. In the side nav, go to 'Oauth & Permissions'
  4. On that page, find the 'Scopes' section. Click 'Add an OAuth Scope' and add 'channels:history' and 'chat:write'. (see scopes)
  5. At the top of the page, Click 'Install App to Workspace'. Confirm, and on page reload, copy the OAuth Access Token.

Find the channel ID

Also, the channel ID can be seen in the browser URL when you open slack in the browser. e.g.

https://mycompany.slack.com/messages/MY_CHANNEL_ID/

or

https://app.slack.com/client/WORKSPACE_ID/MY_CHANNEL_ID

How to determine the Boost version on a system?

As to me, you can first(find version.hpp the version variable is in it, if you know where it is(in ubuntu it usually in /usr/include/boost/version.hpp by default install)):

 locate `boost/version.hpp`

Second show it's version by:

 grep BOOST_LIB_VERSION /usr/include/boost/version.hpp

or

  grep BOOST_VERSION /usr/include/boost/version.hpp.

As to me, I have two version boost installed in my system. Output as below:

xy@xy:~$ locate boost/version.hpp |grep boost

/home/xy/boost_install/boost_1_61_0/boost/version.hpp
/home/xy/boost_install/lib/include/boost/version.hpp
/usr/include/boost/version.hpp

xy@xy:~$ grep BOOST_VERSION /usr/include/boost/version.hpp
#ifndef BOOST_VERSION_HPP
#define BOOST_VERSION_HPP
//  BOOST_VERSION % 100 is the patch level
//  BOOST_VERSION / 100 % 1000 is the minor version
//  BOOST_VERSION / 100000 is the major version
#define BOOST_VERSION 105800
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION

# or this way more readable
xy@xy:~$ grep BOOST_LIB_VERSION /usr/include/boost/version.hpp
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_58"

Show local installed version:

xy@xy:~$ grep BOOST_LIB_VERSION /home/xy/boost_install/lib/include/boost/version.hpp
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_61"

java.lang.NoClassDefFoundError in junit

These steps worked for me when the error showed that the Filter class was missing (as reported in this false-diplicated question: JUnit: NoClassDefFoundError: org/junit/runner/manipulation/Filter ):

  1. Make sure to have JUnit 4 referenced only once in your project (I also removed the Maven nature, but I am not sure if this step has any influence in solving the problem).
  2. Right click the file containing unit tests, select Properties, and under the Run/Debug settings, remove any entries from the Launch Configurations for that file. Hit Apply and close.
  3. Right click the project containing unit tests, select Properties, and under the Run/Debug settings, remove any entries involving JUnit from the Launch Configurations. Hit Apply and close.
  4. Clean the project, and run the test.

Thanks to these answers for giving me the hint for this solution: https://stackoverflow.com/a/34067333/5538923 and https://stackoverflow.com/a/39987979/5538923).

Execution failed app:processDebugResources Android Studio

Banged my head around this for 2 days.

TL;DR - Got this error since My app name contained '-'.

Turn out android does not allowed that. After running gradlew build --stacktrace inside android directory - got an error that implies that.

How to launch Windows Scheduler by command-line?

You can make a new shortcut to:

control schedtasks

Name it something easy like "tsks.lnk" and then save it in c:\windows\system32.

You can now press Windows Key + R, then type "tsks" and press Enter and voila. No mouse necessary at that point.
Or in Windows Vista/7/2008, just press Windows Key, then type "tsks" and press Enter.

Reportviewer tool missing in visual studio 2017 RC

Download Microsoft Rdlc Report Designer for Visual Studio from this link. https://marketplace.visualstudio.com/items?itemName=ProBITools.MicrosoftRdlcReportDesignerforVisualStudio-18001

Microsoft explain the steps in details:

https://docs.microsoft.com/en-us/sql/reporting-services/application-integration/integrating-reporting-services-using-reportviewer-controls-get-started?view=sql-server-2017

The following steps summarizes the above article.

Adding the Report Viewer control to a new web project:

  1. Create a new ASP.NET Empty Web Site or open an existing ASP.NET project.

  2. Install the Report Viewer control NuGet package via the NuGet package manager console. From Visual Studio -> Tools -> NuGet Package Manager -> Package Manager Console

    Install-Package Microsoft.ReportingServices.ReportViewerControl.WebForms
    
  3. Add a new .aspx page to the project and register the Report Viewer control assembly for use within the page.

    <%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
    
  4. Add a ScriptManagerControl to the page.

  5. Add the Report Viewer control to the page. The snippet below can be updated to reference a report hosted on a remote report server.

     <rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote">
     <ServerReport ReportPath="" ReportServerUrl="" /></rsweb:ReportViewer>
    

The final page should look like the following.

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

<%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>

<!DOCTYPE html>

<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager runat="server"></asp:ScriptManager>        
       <rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote">
           <ServerReport ReportServerUrl="https://AContosoDepartment/ReportServer" ReportPath="/LatestSales" />
    </rsweb:ReportViewer>
    </form>
</body>

How to ftp with a batch file?

Each line of a batch file will get executed; but only after the previous line has completed. In your case, as soon as it hits the ftp line the ftp program will start and take over user input. When it is closed then the remaining lines will execute. Meaning the username/password are never sent to the FTP program and instead will be fed to the command prompt itself once the ftp program is closed.

Instead you need to pass everything you need on the ftp command line. Something like:

@echo off
echo user MyUserName> ftpcmd.dat
echo MyPassword>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo put %1>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat SERVERNAME.COM
del ftpcmd.dat

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

How to check iOS version?

Basically the same idea as this one https://stackoverflow.com/a/19903595/1937908 but more robust:

#ifndef func_i_system_version_field
#define func_i_system_version_field

inline static int i_system_version_field(unsigned int fieldIndex) {
  NSString* const versionString = UIDevice.currentDevice.systemVersion;
  NSArray<NSString*>* const versionFields = [versionString componentsSeparatedByString:@"."];
  if (fieldIndex < versionFields.count) {
    NSString* const field = versionFields[fieldIndex];
    return field.intValue;
  }
  NSLog(@"[WARNING] i_system_version(%iu): field index not present in version string '%@'.", fieldIndex, versionString);
  return -1; // error indicator
}

#endif

Simply place the above code in a header file.

Usage:

int major = i_system_version_field(0);
int minor = i_system_version_field(1);
int patch = i_system_version_field(2);

How to build a Horizontal ListView with RecyclerView?

Recycler View in Horizontal Dynamic.

Recycler View Implementation

RecyclerView musicList = findViewById(R.id.MusicList);

// RecyclerView musiclist = findViewById(R.id.MusicList1);
// RecyclerView musicLIST = findViewById(R.id.MusicList2);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
musicList.setLayoutManager(layoutManager);

String[] names = {"RAP", "CH SHB", "Faheem", "Anum", "Shoaib", "Laiba", "Zoki", "Komal", "Sultan","Mansoob Gull"};
musicList.setAdapter(new ProgrammingAdapter(names));'

Adapter class for recycler view, in which there is is a view holder for holding view of that recycler

public class ProgrammingAdapter 
     extendsRecyclerView.Adapter<ProgrammingAdapter.programmingViewHolder> {

private String[] data;

public ProgrammingAdapter(String[] data)
{
    this.data = data;
}

@Override
public programmingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.list_item_layout, parent, false);

    return new programmingViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull programmingViewHolder holder, int position) {
    String title = data[position];
    holder.textV.setText(title);
}

@Override
public int getItemCount() {
    return data.length;
}

public class programmingViewHolder extends RecyclerView.ViewHolder{
    ImageView img;
    TextView textV;
    public programmingViewHolder(View itemView) {
        super(itemView);
        img =  itemView.findViewById(R.id.img);
        textV =  itemView.findViewById(R.id.textt);
    }
}

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

I had to add a user environment variable, HOME, with C:\Users\<your user name> by going to System, Advanced System Settings, in the System Properties window, the Advanced tab, Environment Variables...

Then in my C:\Users\<your user name> I created the file .bashrc, e.g., touch .bashrc and added the desired aliases.

Where to put Gradle configuration (i.e. credentials) that should not be committed?

You could also supply variables on the command line with -PmavenUser=user -PmavenPassword=password.

This might be useful you can't use a gradle.properties file for some reason. E.g. on a build server we're using Gradle with the -g option so that each build plan has it's own GRADLE_HOME.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Convert Array to Object

If you're using jquery:

$.extend({}, ['a', 'b', 'c']);

How can I retrieve the remote git address of a repo?

The long boring solution, which is not involved with CLI, you can manually navigate to:

your local repo folder ? .git folder (hidden) ? config file

then choose your text editor to open it and look for url located under the [remote "origin"] section.

Mean filter for smoothing images in Matlab

h = fspecial('average', n);
filter2(h, img);

See doc fspecial: h = fspecial('average', n) returns an averaging filter. n is a 1-by-2 vector specifying the number of rows and columns in h.

Tensorflow installation error: not a supported wheel on this platform

I was trying to install from source, and got that error. (Why would a wheel built on this machine not be compatible with it-?)

For me, the tag --ignore-installed made all the difference.

pip install --ignore-installed /tmp/tensorflow_pkg/tensorflow-1.8.0-cp36-cp36m-linux_x86_64.whl

worked, while

pip install /tmp/tensorflow_pkg/tensorflow-1.8.0-cp36-cp36m-linux_x86_64.whl 

threw the abovementioned error.

Context: Conda environment; might have been a problem specific to this

Euclidean distance of two vectors

If you want to use less code, you can also use the norm in the stats package (the 'F' stands for Forbenius, which is the Euclidean norm):

norm(matrix(x1-x2), 'F')

While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:

set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)

Then testing for time yields the following:

> system.time(a<-sqrt(sum((x1-x2)^2)))
user  system elapsed 
1.02    0.12    1.18 
> system.time(b<-norm(matrix(x1-x2), 'F'))
user  system elapsed 
0.97    0.33    1.31 

Can I add an image to an ASP.NET button?

I actually prefer to use the html button form element and make it runat=server. The button element can hold other elements inside it. You can even add formatting inside it with span's or strong's. Here is an example:

<button id="BtnSave" runat="server"><img src="Images/save.png" />Save</button>

Simple if else onclick then do?

I did it that way and I like it better, but it can be optimized, right?

// Obtengo los botones y la caja de contenido
var home = document.getElementById("home");
var about = document.getElementById("about");
var service = document.getElementById("service");
var contact = document.getElementById("contact");
var content = document.querySelector("section");

function botonPress(e){
  console.log(e.getAttribute("id"));
  var screen = e.getAttribute("id");
  switch(screen){
    case "home":
      // cambiar fondo
      content.style.backgroundColor = 'black';
      break;
    case "about":
      // cambiar fondo
      content.style.backgroundColor = 'blue';
      break;
    case "service":
      // cambiar fondo
      content.style.backgroundColor = 'green';
      break;
    case "contact":
      // cambiar fondo
      content.style.backgroundColor = 'red';
      break;
  }
}

Ruby on Rails generates model field:type - what are the options for field:type?

Remember to not capitalize your text when writing this command. For example:

Do write:

rails g model product title:string description:text image_url:string price:decimal

Do not write:

rails g Model product title:string description:text image_url:string price:decimal

At least it was a problem to me.

Check if an object exists

You can use:

try:
   # get your models
except ObjectDoesNotExist:
   # do something

Google Drive as FTP Server

What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.

The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.

I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.

This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter

Check if string contains only digits

String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false

pow (x,y) in Java

Additionally for what was said, if you want integer powers of two, then 1 << x (or 1L << x) is a faster way to calculate 2x than Math.pow(2,x) or a multiplication loop, and is guaranteed to give you an int (or long) result.

It only uses the lowest 5 (or 6) bits of x (i.e. x & 31 (or x & 63)), though, shifting between 0 and 31 (or 63) bits.

Can I open a dropdownlist using jQuery

This should cover it:

 var event;
 event = document.createEvent('MouseEvents');
 event.initMouseEvent('mousedown', true, true, window);
 countries.dispatchEvent(event); //we use countries as it's referred to by ID - but this could be any JS element var

This could be bound for example to a keypress event, so when the element has focus the user can type and it will expand automatically...

--Context--

  modal.find("select").not("[readonly]").on("keypress", function(e) {

     if (e.keyCode == 13) {
         e.preventDefault();
         return false;
     }
     var event;
     event = document.createEvent('MouseEvents');
     event.initMouseEvent('mousedown', true, true, window);
     this.dispatchEvent(event);
 });

Code for download video from Youtube on Java, Android

Ref : Youtube Video Download (Android/Java)

private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();

initTypeMap(); call first

class Meta {
    public String num;
    public String type;
    public String ext;

    Meta(String num, String ext, String type) {
        this.num = num;
        this.ext = ext;
        this.type = type;
    }
}

class Video {
    public String ext = "";
    public String type = "";
    public String url = "";

    Video(String ext, String type, String url) {
        this.ext = ext;
        this.type = type;
        this.url = url;
    }
}

public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
        throws IOException {
    if (ytUrl == null) {
        return null;
    }

    // Remove any query params in query string after the watch?v=<vid> in
    // e.g.
    // http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
    int andIdx = ytUrl.indexOf('&');
    if (andIdx >= 0) {
        ytUrl = ytUrl.substring(0, andIdx);
    }

    // Get the HTML response
    /* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
   /* HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            userAgent);
    HttpGet request = new HttpGet(ytUrl);
    HttpResponse response = client.execute(request);*/
    String html = "";
    HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    InputStream in = c.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        str.append(line.replace("\\u0026", "&"));
    }
    in.close();
    html = str.toString();

    // Parse the HTML response and extract the streaming URIs
    if (html.contains("verify-age-thumb")) {
        Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
        return null;
    }

    if (html.contains("das_captcha")) {
        Log.e("Downloader", "Captcha found, please try with different IP address.");
        return null;
    }

    Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
    // Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
    Matcher m = p.matcher(html);
    List<String> matches = new ArrayList<String>();
    while (m.find()) {
        matches.add(m.group());
    }

    if (matches.size() != 1) {
        Log.e("Downloader", "Found zero or too many stream maps.");
        return null;
    }

    String urls[] = matches.get(0).split(",");
    HashMap<String, String> foundArray = new HashMap<String, String>();
    for (String ppUrl : urls) {
        String url = URLDecoder.decode(ppUrl, "UTF-8");
        Log.e("URL","URL : "+url);

        Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
        Matcher m1 = p1.matcher(url);
        String itag = null;
        if (m1.find()) {
            itag = m1.group(1);
        }

        Pattern p2 = Pattern.compile("signature=(.*?)[&]");
        Matcher m2 = p2.matcher(url);
        String sig = null;
        if (m2.find()) {
            sig = m2.group(1);
        } else {
            Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
            Matcher m23 = p23.matcher(url);
            if (m23.find()) {
                sig = m23.group(1);
            }
        }

        Pattern p3 = Pattern.compile("url=(.*?)[&]");
        Matcher m3 = p3.matcher(ppUrl);
        String um = null;
        if (m3.find()) {
            um = m3.group(1);
        }

        if (itag != null && sig != null && um != null) {
            Log.e("foundArray","Adding Value");
            foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
                    + "signature=" + sig);
        }
    }
    Log.e("foundArray","Size : "+foundArray.size());
    if (foundArray.size() == 0) {
        Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
        return null;
    }


    ArrayList<Video> videos = new ArrayList<Video>();

    for (String format : typeMap.keySet()) {
        Meta meta = typeMap.get(format);

        if (foundArray.containsKey(format)) {
            Video newVideo = new Video(meta.ext, meta.type,
                    foundArray.get(format));
            videos.add(newVideo);
            Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
                    + ", type:" + newVideo.type + ", url:" + newVideo.url);
        }
    }

    return videos;
}

private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(webViewActivity.this, "",
                "Connecting to YouTube...", true);
    }

    @Override
    protected ArrayList<Video> doInBackground(String... params) {
        ArrayList<Video> fVideos = new ArrayList<>();
        String url = params[0];
        try {
            ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
            /*                Log.e("Downloader","Size of Video : "+videos.size());*/
            if (videos != null && !videos.isEmpty()) {
                for (Video video : videos)
                {
                    Log.e("Downloader", "ext : " + video.ext);
                    if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
                        ext = video.ext.toLowerCase();
                        fVideos.add(new Video(video.ext,video.type,video.url));
                    }
                }


                return fVideos;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
        }
        Log.e("Downloader", "Couldn't get stream URI for " + url);
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<Video> streamingUrl) {
        super.onPostExecute(streamingUrl);
        progressDialog.dismiss();
        if (streamingUrl != null) {
            if (!streamingUrl.isEmpty()) {
                //Log.e("Steaming Url", "Value : " + streamingUrl);

                for (int i = 0; i < streamingUrl.size(); i++) {
                    Video fX = streamingUrl.get(i);
                    Log.e("Founded Video", "URL : " + fX.url);
                    Log.e("Founded Video", "TYPE : " + fX.type);
                    Log.e("Founded Video", "EXT : " + fX.ext);
                }
                //new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
            }
        }
    }
}
public void initTypeMap()
{
    typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
    typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
    typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
    typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
    typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
    typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
    typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
    typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
    typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
    typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
    typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
    typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
    typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
    typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}

Edit 2:

Some time This Code Not worked proper

Same-origin policy

https://en.wikipedia.org/wiki/Same-origin_policy

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1]. 

Ref : https://superuser.com/questions/773719/how-do-all-of-these-save-video-from-youtube-services-work/773998#773998

url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts              // DASH: contains video or audio stream

Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this

url  // direct HTTP link to a video
itag // code specifying the quality
s    // signature, security measure to counter downloading

Each URL will be encoded so you will need to decode them. Now the tricky part.

YouTube has at least 3 security levels for their videos

unsecured // as expected, you can download these with just the unencoded URL
s         // see below
RTMPE     // uses "rtmpe://" protocol, no known method for these

The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.

The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as

AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this

function mo(a) {
  a = a.split("");
  a = lo.rw(a, 1);
  a = lo.rw(a, 32);
  a = lo.IC(a, 1);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 44);
  return a.join("")
}

This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as

http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js

this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header

Access-Control-Allow-Origin: http://www.youtube.com

and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests

Access-Control-Allow-Origin: *

So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.

What is %0|%0 and how does it work?

What it is:

%0|%0 is a fork bomb. It will spawn another process using a pipe | which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).

How this works:

%0 refers to the command used to run the current program. For example, script.bat

A pipe | symbol will make the output or result of the first command sequence as the input for the second command sequence. In the case of a fork bomb, there is no output, so it will simply run the second command sequence without any input.

Expanding the example, %0|%0 could mean script.bat|script.bat. This runs itself again, but also creating another process to run the same program again (with no input).

How to programmatically clear application data

Following up to @edovino's answer, the way of clearing all of an application's preferences programmatically would be

private void clearPreferences() {
    try {
        // clearing app data
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("pm clear YOUR_APP_PACKAGE_GOES HERE");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Warning: the application will force close.

What is a Subclass

Think of a class as a description of the members of a set of things. All of the members of that set have common characteristics (methods and properties).

A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass.

You declare that one class is subclass of another via the "extends" keyword in Java.

public class B extends A
{
...
}

B is a subclass of A. Instances of class B will automatically exhibit many of the same properties as instances of class A.

This is the main concept of inheritance in Object-Oriented programming.

Using Bootstrap Modal window as PartialView

Complete and clear example project http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals It displays create, edit and delete entity operation modals with bootstrap and also includes code to handle result returned from those entity operations (c#, JSON, javascript)

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

If the numbers are evenly distributed we can use Counting sort. We should keep the number of times that each number is repeated in an array. Available space is: 1 MB - 3 KB = 1045504 B or 8364032 bits Number of bits per number= 8364032/1000000 = 8 Therefore, we can store the number of times each number is repeated to the maximum of 2^8-1=255. Using this approach we have an extra 364032 bits unused that can be used to handle cases where a number is repeated more than 255 times. For example we can say a number 255 indicates a repetition greater than or equal to 255. In this case we should store a sequence of numbers+repetitions. We can handle 7745 special cases as shown bellow:

364032/ (bits need to represent each number + bits needed to represent 1 million)= 364032 / (27+20)=7745

Using NotNull Annotation in method argument

SO @NotNull just is a tag...If you want to validate it, then you must use something like hibernate validator jsr 303

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
 Set<ConstraintViolation<List<Searching>> violations = validator.validate(searchingList);

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Make the value an integer again:

for i in range(int(c / 10)):

or use the // floor division operator:

for i in range(c // 10):

How to escape apostrophe (') in MySql?

Standard SQL uses doubled-up quotes; MySQL has to accept that to be reasonably compliant.

'He said, "Don''t!"'

Using module 'subprocess' with timeout

surprised nobody mentioned using timeout

timeout 5 ping -c 3 somehost

This won't for work for every use case obviously, but if your dealing with a simple script, this is hard to beat.

Also available as gtimeout in coreutils via homebrew for mac users.

How to get a Static property with Reflection

Just wanted to clarify this for myself, while using the new reflection API based on TypeInfo - where BindingFlags is not available reliably (depending on target framework).

In the 'new' reflection, to get the static properties for a type (not including base class(es)) you have to do something like:

IEnumerable<PropertyInfo> props = 
  type.GetTypeInfo().DeclaredProperties.Where(p => 
    (p.GetMethod != null && p.GetMethod.IsStatic) ||
    (p.SetMethod != null && p.SetMethod.IsStatic));

Caters for both read-only or write-only properties (despite write-only being a terrible idea).

The DeclaredProperties member, too doesn't distinguish between properties with public/private accessors - so to filter around visibility, you then need to do it based on the accessor you need to use. E.g - assuming the above call has returned, you could do:

var publicStaticReadable = props.Where(p => p.GetMethod != null && p.GetMethod.IsPublic);

There are some shortcut methods available - but ultimately we're all going to be writing a lot more extension methods around the TypeInfo query methods/properties in the future. Also, the new API forces us to think about exactly what we think of as a 'private' or 'public' property from now on - because we must filter ourselves based on individual accessors.

How to negate a method reference predicate

If you're using Spring Boot (2.0.0+) you can use:

import org.springframework.util.StringUtils;

...
.filter(StringUtils::hasLength)
...

Which does: return (str != null && !str.isEmpty());

So it will have the required negation effect for isEmpty

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

Check your internet connection is stable or not. May be this will work with you

window.onload vs <body onload=""/>

window.onload can work without body. Create page with only the script tags and open it in a browser. The page doesn't contain any body, but it still works..

<script>
  function testSp()
  {
    alert("hit");
  }
  window.onload=testSp;
</script>

In C#, what's the difference between \n and \r\n?

Basically comes down to Windows standard: \r\n and Unix based systems using: \n

http://en.wikipedia.org/wiki/Newline

'invalid value encountered in double_scalars' warning, possibly numpy

It looks like a floating-point calculation error. Check the numpy.seterr function to get more information about where it happens.

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

Pass Model To Controller using Jquery/Ajax

Looks like your IndexPartial action method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPost action method and use jQuery post to post data to that. GET has limitation on the query string value.

[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
   //May be you want to pass the posted model to the parial view?
   return PartialView("_IndexPartial");
}

Your script should be

var url = "@Url.Action("IndexPartial","YourControllerName")";

var model = { Name :"Shyju", Location:"Detroit"};

$.post(url, model, function(res){
   //res contains the markup returned by the partial view
   //You probably want to set that to some Div.
   $("#SomeDivToShowTheResult").html(res);
});

Assuming Name and Location are properties of your DashboardViewModel class and SomeDivToShowTheResult is the id of a div in your page where you want to load the content coming from the partialview.

Sending complex objects?

You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","Stackoverflow"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});

For the above js model to be transformed to your method parameter, Your View Model should be like this.

public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}

And in your action method, specify [FromBody]

[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}

Easiest way to develop simple GUI in Python

I would recommend wxpython. It's very easy to use and the documentation is pretty good.

Match two strings in one line with grep

I often run into the same problem as yours, and I just wrote a piece of script:

function m() { # m means 'multi pattern grep'

    function _usage() {
    echo "usage: COMMAND [-inH] -p<pattern1> -p<pattern2> <filename>"
    echo "-i : ignore case"
    echo "-n : show line number"
    echo "-H : show filename"
    echo "-h : show header"
    echo "-p : specify pattern"
    }

    declare -a patterns
    # it is important to declare OPTIND as local
    local ignorecase_flag  filename linum header_flag colon result OPTIND

    while getopts "iHhnp:" opt; do
    case $opt in
        i)
        ignorecase_flag=true ;;
        H)
        filename="FILENAME," ;;
        n)
        linum="NR," ;;
        p)
        patterns+=( "$OPTARG" ) ;;
        h)
        header_flag=true ;;
        \?)
        _usage
        return ;;
    esac
    done

    if [[ -n $filename || -n $linum ]]; then
    colon="\":\","
    fi

    shift $(( $OPTIND - 1 ))

    if [[ $ignorecase_flag == true ]]; then
    for s in "${patterns[@]}"; do
            result+=" && s~/${s,,}/"
    done
    result=${result# && }
    result="{s=tolower(\$0)} $result"
    else
    for s in "${patterns[@]}"; do
            result="$result && /$s/"
    done
    result=${result# && }
    fi

    result+=" { print "$filename$linum$colon"\$0 }"

    if [[ ! -t 0 ]]; then       # pipe case
    cat - | awk "${result}"
    else
    for f in "$@"; do
        [[ $header_flag == true ]] && echo "########## $f ##########"
        awk "${result}" $f
    done
    fi
}

Usage:

echo "a b c" | m -p A 
echo "a b c" | m -i -p A # a b c

You can put it in .bashrc if you like.

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Function or sub to add new row and data to table

I needed this same solution, but if you use the native ListObject.Add() method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:

Sub AddDataRow(tableName As String, values() As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        For col = 1 To lastRow.Columns.Count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
    Next col
End Sub

To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design tab of the ribbon, in Excel 2013 at least: enter image description here

Example code for a table with three columns:

Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x

$(this).serialize() -- How to add a value?

Add the item first and then serialize:

$.ajax({
    type: 'POST',
    url: this.action,
    data: $.extend($(this), {'NonFormValue': NonFormValue}).serialize()
});

How can I clear the terminal in Visual Studio Code?

You can change from settings menu (at least from version 1.30.2 and above)...

On Mac, just hit Code > Preferences > Settings.

Then just search for "clear" and check Clear Previous Output.

Settings - Clear Previous Output

How to create cross-domain request?

For me it was another problem. This might be trivial for some, but it took me a while to figure out. So this answer might be helpfull to some.

I had my API_BASE_URL set to localhost:58577. The coin dropped after reading the error message for the millionth time. The problem is in the part where it says that it only supports HTTP and some other protocols. I had to change the API_BASE_URL so that it includes the protocol. So changing API_BASE_URL to http://localhost:58577 it worked perfectly.

Angular 4 - get input value

If you dont want to use two way data binding. You can do this.

In HTML

<form (ngSubmit)="onSubmit($event)">
   <input name="player" value="Name">
</form>

In component

onSubmit(event: any) {
   return event.target.player.value;
}

Android: Is it possible to display video thumbnails?

Try this it's working for me

RequestOptions requestOptions = new RequestOptions();
 Glide.with(getContext())
      .load("video_url")
      .apply(requestOptions)
      .thumbnail(Glide.with(getContext()).load("video_url"))
      .into("yourimageview");

SELECT query with CASE condition and SUM()

To get each sum in a separate column:

Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
       SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash') 
and CDate<=SYSDATETIME() 
and CStatus='Active';

align images side by side in html

Here is how I would do it, (however I would use an external style sheet for this project and all others. just makes things easier to work with. Also this example is with html5.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
  .container {
      display:inline-block;
  }
</style>
</head>
<body>

  <div class="container">
    <figure>
    <img src="http://placehold.it/350x150" height="200" width="200">
    <figcaption>This is image 1</figcaption>
    </figure>

    <figure>
    <img class="middle-img" src="http://placehold.it/350x150"/ height="200" width="200">
    <figcaption>This is image 2</figcaption>
    </figure>

    <figure>
    <img src="http://placehold.it/350x150" height="200" width="200">
    <figcaption>This is image 3</figcaption>
    </figure>

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

Where are $_SESSION variables stored?

How does it work? How does it know it's me?

Most sessions set a user-key(called the sessionid) on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key and runs to the server to get your variables.

If you mistakenly clear the cache, then your user-key will also be cleared. You won't be able to get your variables from the server any more since you don't know your id.

FTP/SFTP access to an Amazon S3 Bucket

As other posters have pointed out, there are some limitations with the AWS Transfer for SFTP service. You need to closely align requirements. For example, there are no quotas, whitelists/blacklists, file type limits, and non key based access requires external services. There is also a certain overhead relating to user management and IAM, which can get to be a pain at scale.

We have been running an SFTP S3 Proxy Gateway for about 5 years now for our customers. The core solution is wrapped in a collection of Docker services and deployed in whatever context is needed, even on-premise or local development servers. The use case for us is a little different as our solution is focused data processing and pipelines vs a file share. In a Salesforce example, a customer will use SFTP as the transport method sending email, purchase...data to an SFTP/S3 enpoint. This is mapped an object key on S3. Upon arrival, the data is picked up, processed, routed and loaded to a warehouse. We also have fairly significant auditing requirements for each transfer, something the Cloudwatch logs for AWS do not directly provide.

As other have mentioned, rolling your own is an option too. Using AWS Lightsail you can setup a cluster, say 4, of $10 2GB instances using either Route 53 or an ELB.

In general, it is great to see AWS offer this service and I expect it to mature over time. However, depending on your use case, alternative solutions may be a better fit.

.prop('checked',false) or .removeAttr('checked')?

use checked : true, false property of the checkbox.

jQuery:

if($('input[type=checkbox]').is(':checked')) {
    $(this).prop('checked',true);
} else {
    $(this).prop('checked',false);
}

Android Google Maps API V2 Zoom to Current Location

private void setUpMapIfNeeded(){
    if (mMap == null){
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();//invoke of map fragment by id from main xml file

     if (mMap != null) {
         mMap.setMyLocationEnabled(true);//Makes the users current location visible by displaying a blue dot.

         LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
         String provider=lm.getBestProvider(new Criteria(), true);

         if(provider==null){
             onProviderDisabled(provider);
              }
         Location loc=lm.getLastKnownLocation(provider);


         if (loc!=null){
             onLocationChanged(loc);
      }
         }
     }
}

    // Initialize map options. For example:
    // mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

@Override
public void onLocationChanged(Location location) {

   LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 14.6));//Animates camera and zooms to preferred state on the user's current location.
}

    // TODO Auto-generated method stub

trim left characters in sql server?

use "LEFT"

 select left('Hello World', 5)

or use "SUBSTRING"

 select substring('Hello World', 1, 5)

How to install PHP mbstring on CentOS 6.2

If none of the above help you out, and you have the option, try obtaining one of the rpm files eg:

wget http://rpms.famillecollet.com/enterprise/6/remi/x86_64/php-mbstring-5.4.45-2.el6.remi.x86_64.rpm

then using rpm, install it ignoring the depenecies like so:

rpm -i --nodeps php-mbstring-5.4.45-2.el6.remi.x86_64.rpm

Hope that helps out.

Symfony2 Setting a default choice field selection

You can define the default value from the 'data' attribute. This is part of the Abstract "field" type (http://symfony.com/doc/2.0/reference/forms/types/field.html)

$form = $this->createFormBuilder()
            ->add('status', 'choice', array(
                'choices' => array(
                    0 => 'Published',
                    1 => 'Draft'
                ),
                'data' => 1
            ))
            ->getForm();

In this example, 'Draft' would be set as the default selected value.

Why doesn't Mockito mock static methods?

Mockito [3.4.0] can mock static methods!

  1. Replace mockito-core dependency with mockito-inline:3.4.0.

  2. Class with static method:

    class Buddy {
      static String name() {
        return "John";
      }
    }
    
  3. Use new method Mockito.mockStatic():

    @Test
    void lookMomICanMockStaticMethods() {
      assertThat(Buddy.name()).isEqualTo("John");
    
      try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
        theMock.when(Buddy::name).thenReturn("Rafael");
        assertThat(Buddy.name()).isEqualTo("Rafael");
      }
    
      assertThat(Buddy.name()).isEqualTo("John");
    }
    

    Mockito replaces the static method within the try block only.

Getting URL parameter in java and extract a specific text from that URL

If you're on Android, you can do this:

Uri uri = Uri.parse(url);
String v = uri.getQueryParameter("v");

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

how to delete the content of text file without deleting itself

One of the best companion for java is Apache Projects and please do refer to it. For file related operation you can refer to the Commons IO project.

The Below one line code will help us to make the file empty.

FileUtils.write(new File("/your/file/path"), "")

Injecting $scope into an angular service function()

Instead of trying to modify the $scope within the service, you can implement a $watch within your controller to watch a property on your service for changes and then update a property on the $scope. Here is an example you might try in a controller:

angular.module('cfd')
    .controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) {

        $scope.students = null;

        (function () {
            $scope.$watch(function () {
                return StudentService.students;
            }, function (newVal, oldVal) {
                if ( newValue !== oldValue ) {
                    $scope.students = newVal;
                }
            });
        }());
    }]);

One thing to note is that within your service, in order for the students property to be visible, it needs to be on the Service object or this like so:

this.students = $http.get(path).then(function (resp) {
  return resp.data;
});

Convert Year/Month/Day to Day of Year in Python

I want to present performance of different approaches, on Python 3.4, Linux x64. Excerpt from line profiler:

      Line #      Hits         Time  Per Hit   % Time  Line Contents
      ==============================================================
         (...)
         823      1508        11334      7.5     41.6          yday = int(period_end.strftime('%j'))
         824      1508         2492      1.7      9.1          yday = period_end.toordinal() - date(period_end.year, 1, 1).toordinal() + 1
         825      1508         1852      1.2      6.8          yday = (period_end - date(period_end.year, 1, 1)).days + 1
         826      1508         5078      3.4     18.6          yday = period_end.timetuple().tm_yday
         (...)

So most efficient is

yday = (period_end - date(period_end.year, 1, 1)).days

How to slice a Pandas Data Frame by position?

I can see at least three options:

1.

df[:10]

2. Using head

df.head(10)

For negative values of n, this function returns all rows except the last n rows, equivalent to df[:-n] [Source].

3. Using iloc

df.iloc[:10]

How to change ProgressBar's progress indicator color in Android

There are 3 ways to solve this question:

  1. How to adjust the progressbar color declaratively
  2. How to adjust the progressbar color programmatically, but choose the color from various predetermined colors declared before compile-time
  3. How to adjust the progressbar color programmatically, and also create the color programatically.

In particular there is a lot of confusion around #2 and #3, as seen in comments to amfcosta's answer. That answer will yield unpredictable color results anytime you'd like to set the progressbar to anything except primary colors, as it only modifies the background color, and the actual progress bar "clip" area will still be a yellow overlay with reduced opacity. For example, using that method to set the background to dark purple will result in a progress bar "clip" color of some crazy pinkish color resulting from dark purple and yellow mixing via reduced alpha.

So anyhow, #1 is answered perfectly by Ryan and Štarke answers most of #3, but for those looking for a complete solution to #2 and #3:


How to adjust the progressbar color programmatically, but choose the color from a predetermined color declared in XML

res/drawable/my_progressbar.xml:

Create this file but change the colors in my_progress and my_secondsProgress:

(NOTE: This is just a copy of the actual XML file defining the default android SDK ProgressBar, but I've changed the IDs and Colors. The original is named progress_horizontal)

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

<item android:id="@+id/my_progress_background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
            android:startColor="#ff9d9e9d"
            android:centerColor="#ff5a5d5a"
            android:centerY="0.75"
            android:endColor="#ff747674"
            android:angle="270"
            />
    </shape>
</item>

<item android:id="@+id/my_secondaryProgress">
    <clip>
        <shape>
            <corners android:radius="5dip" />
            <gradient
                android:startColor="#80ff171d"
                android:centerColor="#80ff1315"
                android:centerY="0.75"
                android:endColor="#a0ff0208"
                android:angle="270"
                />
        </shape>
    </clip>
</item>

<item android:id="@+id/my_progress">
    <clip>
        <shape>
            <corners android:radius="5dip" />
            <gradient
                android:startColor="#7d2afdff"
                android:centerColor="#ff2afdff"
                android:centerY="0.75"
                android:endColor="#ff22b9ba"
                android:angle="270"
                />
        </shape>
    </clip>
</item>

In your Java:

final Drawable drawable;
int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < 16) {
        drawable =  ctx.getResources().getDrawable(R.drawable.my_progressbar);
    } else {
        drawable = ContextCompat.getDrawable(ctx, R.drawable.my_progressbar);
    }
progressBar.setProgressDrawable(drawable)

How to adjust the progressbar color programmatically, and also create the color programatically

EDIT: I found the time to solve this properly. My former answer left this a bit ambiguous.

A ProgressBar is composed as 3 Drawables in a LayerDrawable.

  1. Layer 1 is the background
  2. Layer 2 is the secondary progress color
  3. Layer 3 is the main progress bar color

In the example below I'll change the color of the main progress bar to cyan.

//Create new ClipDrawable to replace the old one
float pxCornerRadius = viewUtils.convertDpToPixel(5);
final float[] roundedCorners = new float[] { pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius };
ShapeDrawable shpDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null, null));
shpDrawable.getPaint().setColor(Color.CYAN);
final ClipDrawable newProgressClip = new ClipDrawable(shpDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);

//Replace the existing ClipDrawable with this new one
final LayerDrawable layers = (LayerDrawable) progressBar.getProgressDrawable();
layers.setDrawableByLayerId(R.id.my_progress, newProgressClip);

That example set it to a solid color. You may set it to a gradient color by replacing

shpDrawable.getPaint().setColor(Color.CYAN);

with

Shader shader = new LinearGradient(0, 0, 0, progressBar.getHeight(), Color.WHITE, Color.BLACK, Shader.TileMode.CLAMP);
shpDrawable.getPaint().setShader(shader);

Cheers.

-Lance

Entity Framework 5 Updating a Record

public interface IRepository
{
    void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class;
}

public class Repository : DbContext, IRepository
{
    public void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class
    {
        Set<T>().Attach(obj);
        propertiesToUpdate.ToList().ForEach(p => Entry(obj).Property(p).IsModified = true);
        SaveChanges();
    }
}

Regex for checking if a string is strictly alphanumeric

See the documentation of Pattern.

Assuming US-ASCII alphabet (a-z, A-Z), you could use \p{Alnum}.

A regex to check that a line contains only such characters is "^[\\p{Alnum}]*$".

That also matches empty string. To exclude empty string: "^[\\p{Alnum}]+$".

PHPExcel Make first row bold

$objPHPExcel->getActiveSheet()->getStyle('1:1')->getFont()->setBold(true);

That way you get the complete first row

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

The issue in my case was a typo in the PATH variable. Since vsvars32.bat uses the "reg" tool to query the registry, it was failing because the tool was not found (just typing reg on a command prompt was failing for me).

How to run php files on my computer

php have a easy way to run a light server:
first cd into php file directory, then

php -S 127.0.0.1:8000

then you can run php

.htaccess not working on localhost with XAMPP

For windows user, make sure to closely look at this section.

RewriteRule ^properties$ /property_available.php/$1 [NC,QSA]

As said in Apache documentation :

The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly.

So ^properties$ means Apache will only look for URL that has exact match with properties. You might want to try this code.

RewriteRule properties /property_available.php/$1 [NC,QSA]

So Apache will see the URL that has properties and rewrite it to /property_available.php/

Protractor : How to wait for page complete after click a button?

Use this I think it's better

   *isAngularSite(false);*
    browser.get(crmUrl);


    login.username.sendKeys(username);
    login.password.sendKeys(password);
    login.submit.click();

    *isAngularSite(true);*

For you to use this setting of isAngularSite should put this in your protractor.conf.js here:

        global.isAngularSite = function(flag) {
        browser.ignoreSynchronization = !flag;
        };

How do I get IntelliJ to recognize common Python modules?

Another possible fix (solved my problem)

You might have configured the environment properly but for some reason it broke along the way. In this case go to:

file > project settings > modules

Deploy the list of SDKs and look for a red line with [invalid] at the end. If you find one, you have to recreate a python sdk.

It is likely that your previously working SDK is there too, but not red. Delete it.

Now you can click on the new button and add your favorite python virtualenv. And it should work now.

Swift - How to detect orientation changes

All previous contributes are fine, but a little note:

a) if orientation is set in plist, only portrait or example, You will be not notified via viewWillTransition

b) if we anyway need to know if user has rotated device, (for example a game or similar..) we can only use:

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

tested on Xcode8, iOS11

How can I echo HTML in PHP?

You could use the alternative syntax alternative syntax for control structures and break out of PHP:

<?php if ($something): ?>
    <some /> <tags /> <etc />
    <?=$shortButControversialWayOfPrintingAVariable ?>
    <?php /* A comment not visible in the HTML, but it is a bit of a pain to write */ ?>
<?php else: ?>
    <!-- else -->
<?php endif; ?>

ApiNotActivatedMapError for simple html page using google-places-api

To enable Api do this

  1. Go to API Manager
  2. Click on Overview
  3. Search for Google Maps JavaScript API(Under Google Maps APIs). Click on that
  4. You will find Enable button there. Click to enable API.

OR You can try this url: Maps JavaScript API

Hope this will solve the problem of enabling API.

Hide text using css

repalce content with the CSS

 h1{  font-size: 0px;}
 h1:after {
    content: "new content";
    font-size: 15px;
  }

How to calculate number of days between two dates

Try:

//Difference in days

var diff =  Math.floor(( start - end ) / 86400000);
alert(diff);

How to pause / sleep thread or process in Android?

I know this is an old thread, but in the Android documentation I found a solution that worked very well for me...

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }

    public void onFinish() {
        mTextField.setText("done!");
    }
}.start();

https://developer.android.com/reference/android/os/CountDownTimer.html

Hope this helps someone...

How to make an inline element appear on new line, or block element not occupy the whole line?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.feature_wrapper span {
    float: left;
    clear: left;
    display:inline
}

EDIT: now browsers have better support you can make use of the do inline-block.

.feature_wrapper span {
    display:inline-block;
    *display:inline; *zoom:1;
}

Depending on the text-align this will appear as through its inline while also acting like a block element.

How can I do an asc and desc sort using underscore.js?

The Array prototype's reverse method modifies the array and returns a reference to it, which means you can do this:

var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();

Also, the underscore documentation reads:

In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

which means you can also use .reverse() while chaining:

var sortedDescAndFiltered = _.chain(collection)
    .sortBy('propertyName')
    .reverse()
    .filter(_.property('isGood'))
    .value();

How to read all rows from huge table?

The short version is, call stmt.setFetchSize(50); and conn.setAutoCommit(false); to avoid reading the entire ResultSet into memory.

Here's what the docs say:

Getting results based on a cursor

By default the driver collects all the results for the query at once. This can be inconvenient for large data sets so the JDBC driver provides a means of basing a ResultSet on a database cursor and only fetching a small number of rows.

A small number of rows are cached on the client side of the connection and when exhausted the next block of rows is retrieved by repositioning the cursor.

Note:

  • Cursor based ResultSets cannot be used in all situations. There a number of restrictions which will make the driver silently fall back to fetching the whole ResultSet at once.

  • The connection to the server must be using the V3 protocol. This is the default for (and is only supported by) server versions 7.4 and later.-

  • The Connection must not be in autocommit mode. The backend closes cursors at the end of transactions, so in autocommit mode the backend will have closed the cursor before anything can be fetched from it.-

  • The Statement must be created with a ResultSet type of ResultSet.TYPE_FORWARD_ONLY. This is the default, so no code will need to be rewritten to take advantage of this, but it also means that you cannot scroll backwards or otherwise jump around in the ResultSet.-

  • The query given must be a single statement, not multiple statements strung together with semicolons.

Example 5.2. Setting fetch size to turn cursors on and off.

Changing code to cursor mode is as simple as setting the fetch size of the Statement to the appropriate size. Setting the fetch size back to 0 will cause all rows to be cached (the default behaviour).

// make sure autocommit is off
conn.setAutoCommit(false);
Statement st = conn.createStatement();

// Turn use of the cursor on.
st.setFetchSize(50);
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
   System.out.print("a row was returned.");
}
rs.close();

// Turn the cursor off.
st.setFetchSize(0);
rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
   System.out.print("many rows were returned.");
}
rs.close();

// Close the statement.
st.close();

Python function pointer

It's much nicer to be able to just store the function itself, since they're first-class objects in python.

import mypackage

myfunc = mypackage.mymodule.myfunction
myfunc(parameter1, parameter2)

But, if you have to import the package dynamically, then you can achieve this through:

mypackage = __import__('mypackage')
mymodule = getattr(mypackage, 'mymodule')
myfunction = getattr(mymodule, 'myfunction')

myfunction(parameter1, parameter2)

Bear in mind however, that all of that work applies to whatever scope you're currently in. If you don't persist them somehow, you can't count on them staying around if you leave the local scope.

PHP array delete by value (not key)

The accepted answer converts the array to associative array, so, if you would like to keep it as a non-associative array with the accepted answer, you may have to use array_values too.

if(($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
    $arr = array_values($messages);
}

The reference is here

Regular expression for exact match of a string

(?<![\w\d])abc(?![\w\d])

this makes sure that your match is not preceded by some character, number, or underscore and is not followed immediately by character or number, or underscore

so it will match "abc" in "abc", "abc.", "abc ", but not "4abc", nor "abcde"

Count number of occurences for each unique value

This works for me. Take your vector v

length(summary(as.factor(v),maxsum=50000))

Comment: set maxsum to be large enough to capture the number of unique values

or with the magrittr package

v %>% as.factor %>% summary(maxsum=50000) %>% length

jQuery: Scroll down page a set increment (in pixels) on click?

You might be after something that the scrollTo plugin from Ariel Flesler does really well.

http://demos.flesler.com/jquery/scrollTo/

Node.js get file extension

Update

Since the original answer, extname() has been added to the path module, see Snowfish answer

Original answer:

I'm using this function to get a file extension, because I didn't find a way to do it in an easier way (but I think there is) :

function getExtension(filename) {
    var ext = path.extname(filename||'').split('.');
    return ext[ext.length - 1];
}

you must require 'path' to use it.

another method which does not use the path module :

function getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i);
}

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

Brace yourself, here there's another coming :-)

Today I had to explain to my girlfriend the difference between the expressive power of WS-Security as opposed to HTTPS. She's a computer scientist, so even if she doesn't know all the XML mumbo jumbo she understands (maybe better than me) what encryption or signature means. However I wanted a strong image, which could make her really understand what things are useful for, rather than how they are implemented (that came a bit later, she didn't escape it :-)).

So it goes like this. Suppose you are naked, and you have to drive your motorcycle to a certain destination. In the (A) case you go through a transparent tunnel: your only hope of not being arrested for obscene behaviour is that nobody is looking. That is not exactly the most secure strategy you can come out with... (notice the sweat drop from the guy forehead :-)). That is equivalent to a POST in clear, and when I say "equivalent" I mean it. In the (B) case, you are in a better situation. The tunnel is opaque, so as long as you travel into it your public record is safe. However, this is still not the best situation. You still have to leave home and reach the tunnel entrance, and once outside the tunnel probably you'll have to get off and walk somewhere... and that goes for HTTPS. True, your message is safe while it crosses the biggest chasm: but once you delivered it on the other side you don't really know how many stages it will have to go through before reaching the real point where the data will be processed. And of course all those stages could use something different than HTTP: a classical MSMQ which buffers requests which can't be served right away, for example. What happens if somebody lurks your data while they are in that preprocessing limbo? Hm. (read this "hm" as the one uttered by Morpheus at the end of the sentence "do you think it's air you are breathing?"). The complete solution (c) in this metaphor is painfully trivial: get some darn clothes on yourself, and especially the helmet while on the motorcycle!!! So you can safely go around without having to rely on opaqueness of the environments. The metaphor is hopefully clear: the clothes come with you regardless of the mean or the surrounding infrastructure, as the messsage level security does. Furthermore, you can decide to cover one part but reveal another (and you can do that on personal basis: airport security can get your jacket and shoes off, while your doctor may have a higher access level), but remember that short sleeves shirts are bad practice even if you are proud of your biceps :-) (better a polo, or a t-shirt).

I'm happy to say that she got the point! I have to say that the clothes metaphor is very powerful: I was tempted to use it for introducing the concept of policy (disco clubs won't let you in sport shoes; you can't go to withdraw money in a bank in your underwear, while this is perfectly acceptable look while balancing yourself on a surf; and so on) but I thought that for one afternoon it was enough ;-)

Architecture - WS, Wild Ideas

Courtesy : http://blogs.msdn.com/b/vbertocci/archive/2005/04/25/end-to-end-security-or-why-you-shouldn-t-drive-your-motorcycle-naked.aspx

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

The error for me was:

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:percent:26.0.2] AndroidManifest.xml:25:13-35
    is also present at [com.android.support:support-v4:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:23:9-25:38 to override.

The solution for me was in my project Gradle file I needed to bump my com.google.gms:google-services version.

I was using version 3.1.1:

classpath 'com.google.gms:google-services:3.1.1

And the error resolved after I bumped it to version 3.2.1:

classpath 'com.google.gms:google-services:3.2.1

I had just upgraded all my libraries to the latest including v27.1.1 of all the support libraries and v15.0.0 of all the Firebase libraries when I saw the error.

IPython/Jupyter Problems saving notebook as PDF

What I found was that the nbconvert/utils/pandoc.py had a code bug that resulted in the error for my machine. The code checks if pandoc is in your environmental variables path. For my machine the answer is no. However pandoc.exe is!

Solution was to add '.exe' to the code on line 69

if __version is None:
    if not which('pandoc.exe'):
        raise PandocMissing()

The same goes for 'xelatex' is not installed. Add to the file nbconvert/exporters/pdf.py on line 94

    cmd = which(command_list[0]+'.exe')

Remove insignificant trailing zeros from a number?

If you use toFixed(n) where n > 0, a more simple and stable (no more float operations) solution can be:

(+n).toFixed(2).replace(/(\.0+|0+)$/, '')


// 0 => 0
// 0.1234 => 0.12
// 0.1001 => 0.1

// 1 => 1
// 1.1234 => 1.12
// 1.1001 => 1.1

// 100 => 100
// 100.1234 => 100.12
// 100.1001 => 100.1

PS: if you use toFixed(0), then no replace is needed.

Comparing strings in C# with OR in an if statement

Try:

    if (textBox1.Text == "" || textBox2.Text == "")
    {
        // do something..
    }

Instead of:

    if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
    {
        // do something..
    }

Because string.Empty is different than - "".

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

How do I 'git diff' on a certain directory?

To use Beyond Compare as the difftool for directory diff, remember enable follow symbolic links like so:

In a Folder Compare ViewRules (Referee Icon):

Enter image description here

And then, enable follow symbolic links and update session defaults:

Enter image description here


OR,

set up the alias like so:

git config --global alias.diffdir "difftool --dir-diff --tool=bc3 --no-prompt --no-symlinks"

Note that in either case, any edits made to the side (left or right) that refers to the current working tree are preserved.

Remove element of a regular array

The nature of arrays is that their length is immutable. You can't add or delete any of the array items.

You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.

So it is probably better to use a List instead of an array.

document.getElementById("test").style.display="hidden" not working

you can use something like this....div container

<script type="text/javascript">
function hide(){
document.getElementById("test").innerHTML.style.display="none";
}
</script>
<div id="test">
<form method="post" >

<table width="60%" border="0" cellspacing="2" cellpadding="2"  >
  <tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold" align="center">
    <td>Ample Id</td>
    <td>Find</td>
  </tr>

  <tr align="center" bgcolor="#E8F8FF" style="color:#006" >
    <td><input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>" /></td>
   <td><input type="image" src="../images/btnFind.png" id="find" name="find" onclick="javascript:hide();"/></td>
   </tr>

</table>

</form>
</div>

Does Index of Array Exist

You can use LINQ to achieve that too:

var exists = array.ElementAtOrDefault(index) != null;

How do I restart my C# WinForm Application?

You could enclose your code inside a function and when restart is needed you can just call the function.

How to pass parameter to click event in Jquery

You don't need to pass the parameter, you can get it using .attr() method

$(function(){
    $('elements-to-match').click(function(){
        alert("The id is "+ $(this).attr("id") );
    });
});

Bootstrap 3: How do you align column content to bottom of row

You can use display: table-cell and vertical-align: bottom, on the 2 columns that you want to be aligned bottom, like so:

.bottom-column
{
    float: none;
    display: table-cell;
    vertical-align: bottom;
}

Working example here.

Also, this might be a possible duplicate question.

JavaScript require() on client side

I have found that in general it is recommended to preprocess scripts at compile time and bundle them in one (or very few) packages with the require being rewritten to some "lightweight shim" also at compile time.

I've Googled out following "new" tools that should be able to do it

And the already mentioned browserify should also fit quite well - http://esa-matti.suuronen.org/blog/2013/04/15/asynchronous-module-loading-with-browserify/

What are the module systems all about?

Basic HTTP authentication with Node and Express 4

I changed in express 4.0 the basic authentication with http-auth, the code is:

var auth = require('http-auth');

var basic = auth.basic({
        realm: "Web."
    }, function (username, password, callback) { // Custom authentication method.
        callback(username === "userName" && password === "password");
    }
);

app.get('/the_url', auth.connect(basic), routes.theRoute);

Uncaught TypeError: Cannot read property 'appendChild' of null

Had the same problem when Load external without cache using Javascript

Load external <script> without cache using Javascript

Had a good solution for cache problem here:

https://www.c-sharpcorner.com/article/how-to-force-the-browser-to-reload-cached-js-css-files-to-reflect-latest-chan/

But this happend: Uncaught TypeError: Cannot read property 'appendChild' of null.

Here is good explanation: https://stackoverflow.com/a/58824439/14491024

As it said your script tag is in the head, the JavaScript is loaded before your HTML.

Error

In Visual Studio by C# this problem is solved like this by adding Guid:

Guid

Here is how it looks in the View page source:

OK

Browser detection

I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.

Or use these libs to determine the browser type if you really must.

Also see Browser & version in prototype library?

How do I diff the same file between two different commits on the same branch?

Just another way to use Git's awesomeness...

git difftool HEAD HEAD@{N} /PATH/FILE.ext

Converting Integer to Long

A parser from int variables to the long type is included in the Integer class. Here is an example:

int n=10;
long n_long=Integer.toUnsignedLong(n);

You can easily use this in-built function to create a method that parses from int to long:

    public static long toLong(int i){
    long l;
    if (i<0){
        l=-Integer.toUnsignedLong(Math.abs(i));
    }
    else{
        l=Integer.toUnsignedLong(i);
    }
    return l;
}

How to programmatically set the Image source

Try this:

BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));

How to position the div popup dialog to the center of browser screen?

I think you need to make the .holder position:relative; and .popup position:absolute;

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

Try to disable SELinux by this command /usr/sbin/setenforce 0. In my case it solved the problem.

How to include js and CSS in JSP with spring MVC

Put your css/js files in folder src/main/webapp/resources. Don't put them in WEB-INF or src/main/resources.

Then add this line to spring-dispatcher-servlet.xml

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

Include css/js files in jsp pages

<link href="<c:url value="/resources/style.css" />" rel="stylesheet">

Don't forget to declare taglib in your jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Angular 2: Get Values of Multiple Checked Checkboxes

Here's a simple way using ngModel (final Angular 2)

<!-- my.component.html -->

<div class="form-group">
    <label for="options">Options:</label>
    <div *ngFor="let option of options">
        <label>
            <input type="checkbox"
                   name="options"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"/>
            {{option.name}}
        </label>
    </div>
</div>

// my.component.ts

@Component({ moduleId:module.id, templateUrl:'my.component.html'})

export class MyComponent {
  options = [
    {name:'OptionA', value:'1', checked:true},
    {name:'OptionB', value:'2', checked:false},
    {name:'OptionC', value:'3', checked:true}
  ]

  get selectedOptions() { // right now: ['1','3']
    return this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value)
  }
}

MAVEN_HOME, MVN_HOME or M2_HOME

I have solved same issue with following:

export M2_HOME=/usr/share/maven

Where does System.Diagnostics.Debug.Write output appear?

The solution for my case is:

  1. Right click the output window;
  2. Check the 'Program Output'

while EOF in JAVA?

nextLine() will throw an exception when there's no line and it will never return null,you can try the Scanner Class instead : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

How to run mvim (MacVim) from Terminal?

There should be a script named mvim in the root of the .bz2 file. Copy this somewhere into your $PATH ( /usr/local/bin would be good ) and you should be sorted.

SQL Server IF EXISTS THEN 1 ELSE 2

If you want to do it this way then this is the syntax you're after;

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
   SELECT 1 
END
ELSE
BEGIN
    SELECT 2
END

You don't strictly need the BEGIN..END statements but it's probably best to get into that habit from the beginning.

Constant pointer vs Pointer to constant

Please refer the following link for better understanding about the difference between Const pointer and Pointer on a constant value.

constant pointer vs pointer on a constant value

How to set a value to a file input in HTML?

Actually we can do it. we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form. Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed. So,

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
       FormToMultipartPostData postData = 
            new FormToMultipartPostData(webBrowser1, form);
        postData.SetFile("fileField", @"C:\windows\win.ini");
        postData.Submit();
    }

Refer the below link for downloading and complete reference.

https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

How to grant all privileges to root user in MySQL 8.0

I had the same problem on CentOS and this worked for me (version: 8.0.11):

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'

What is the difference between readonly="true" & readonly="readonly"?

This is a property setting rather than a valued attribute

These property settings are values per see and don't need any assignments to them. When they are present, an element has this boolean property set to true, when they're absent they're false.

<input type="text" readonly />

It's actually browsers that are liberal toward value assignment to them. If you assign any value to them it will simply get ignored. Browsers will only see the presence of a particular property and ignore the value you're trying to assign to them.

This is of course good, because some frameworks don't have the ability to add such properties without providing their value along with them. Asp.net MVC Html helpers are one of them. jQuery used to be the same until version 1.6 where they added the concept of properties.

There are of course some implications that are related to XHTML as well, because attributes in XML need values in order to be well formed. But that's a different story. Hence browsers have to ignore value assignments.

Anyway. Never mind the value you're assigning to them as long as the name is correctly spelled so it will be detected by browsers. But for readability and maintainability it's better to assign meaningful values to them like:

readonly="true" <-- arguably best human readable
readonly="readonly"

as opposed to

readonly="johndoe"
readonly="01/01/2000"

that may confuse future developers maintaining your code and may interfere with future specification that may define more strict rules to such property settings.

How can I use std::maps with user-defined types as key?

Keys must be comparable, but you haven't defined a suitable operator< for your custom class.

Google Maps JS API v3 - Simple Multiple Marker Example

Add a marker in your program is very easy. You just may add this code:

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  title: 'Hello World!'
});

The following fields are particularly important and commonly set when you construct a marker:

  • position (required) specifies a LatLng identifying the initial location of the marker. One way of retrieving a LatLng is by using the Geocoding service.
  • map (optional) specifies the Map on which to place the marker. If you do not specify a map on construction of the marker, the marker is created but is not attached to (or displayed on) the map. You may add the marker later by calling the marker's setMap() method.

Note, in the example, the title field set the marker's title who will appear as a tooltip.

You may consult the Google api documenation here.


This is a complete example to set one marker in a map. Be care full, you have to replace YOUR_API_KEY by your google API key:

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
   <meta charset="utf-8">
   <title>Simple markers</title>
<style>
  /* Always set the map height explicitly to define the size of the div
   * element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</style>
</head>
<body>
 <div id="map"></div>
<script>

  function initMap() {
    var myLatLng = {lat: -25.363, lng: 131.044};

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: myLatLng
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: 'Hello World!'
    });
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>


Now, if you want to plot markers of an array in a map, you should do like this:

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function initMap() {
  var myLatLng = {lat: -33.90, lng: 151.16};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: myLatLng
    });

  var count;

  for (count = 0; count < locations.length; count++) {  
    new google.maps.Marker({
      position: new google.maps.LatLng(locations[count][1], locations[count][2]),
      map: map,
      title: locations[count][0]
      });
   }
}

This example give me the following result:

enter image description here


You can, also, add an infoWindow in your pin. You just need this code:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[count][1], locations[count][2]),
    map: map
    });

marker.info = new google.maps.InfoWindow({
    content: 'Hello World!'
    });

You can have the Google's documentation about infoWindows here.


Now, we can open the infoWindow when the marker is "clik" like this:

var marker = new google.maps.Marker({
     position: new google.maps.LatLng(locations[count][1], locations[count][2]),
     map: map
     });

marker.info = new google.maps.InfoWindow({
     content: locations [count][0]
     });


google.maps.event.addListener(marker, 'click', function() {  
    // this = marker
    var marker_map = this.getMap();
    this.info.open(marker_map, this);
    // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
            });

Note, you can have some documentation about Listener here in google developer.


And, finally, we can plot an infoWindow in a marker if the user click on it. This is my complete code:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Info windows</title>
    <style>
    /* Always set the map height explicitly to define the size of the div
    * element that contains the map. */
    #map {
        height: 100%;
    }
    /* Optional: Makes the sample page fill the window. */
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>

    var locations = [
        ['Bondi Beach', -33.890542, 151.274856, 4],
        ['Coogee Beach', -33.923036, 151.259052, 5],
        ['Cronulla Beach', -34.028249, 151.157507, 3],
        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];


    // When the user clicks the marker, an info window opens.

    function initMap() {
        var myLatLng = {lat: -33.90, lng: 151.16};

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: myLatLng
            });

        var count=0;


        for (count = 0; count < locations.length; count++) {  

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[count][1], locations[count][2]),
                map: map
                });

            marker.info = new google.maps.InfoWindow({
                content: locations [count][0]
                });


            google.maps.event.addListener(marker, 'click', function() {  
                // this = marker
                var marker_map = this.getMap();
                this.info.open(marker_map, this);
                // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
                });
        }
    }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
</body>
</html>

Normally, you should have this result:

Your result

In javascript, how do you search an array for a substring match

I think this may help you. I had a similar issue. If your array looks like this:

var array = ["page1","1973","Jimmy"]; 

You can do a simple "for" loop to return the instance in the array when you get a match.

var c; 
for (i = 0; i < array.length; i++) {
if (array[i].indexOf("page") > -1){ 
c = i;}
} 

We create an empty variable, c to host our answer. We then loop through the array to find where the array object (e.g. "page1") matches our indexOf("page"). In this case, it's 0 (the first result)

Happy to expand if you need further support.

Search a text file and print related lines in Python?

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

With apologies to senderle who I blatantly copied.

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

Good PHP ORM Library?

Look into Doctrine.

Doctrine 1.2 implements Active Record. Doctrine 2+ is a DataMapper ORM.

Also, check out Xyster. It's based on the Data Mapper pattern.

Also, take a look at DataMapper vs. Active Record.

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();

CRON job to run on the last day of the month

What about this one, after Wikipedia?

55 23 L * * /full/path/to/command

Your content must have a ListView whose id attribute is 'android.R.id.list'

Inherit Activity Class instead of ListActivity you can resolve this problem.

public class ExampleActivity extends Activity  {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.mainlist);
    }
}

Fixing Sublime Text 2 line endings?

to chnage line endings from LF to CRLF:

open Sublime and follow the steps:-

1 press Ctrl+shift+p then install package name line unify endings

then again press Ctrl+shift+p

2 in the blank input box type "Line unify ending "

3 Hit enter twice

Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF

How to grant permission to users for a directory using command line in Windows?

  1. navigate to top level directory you want to set permissions to with explorer
  2. type cmd in the address bar of your explorer window
  3. enter icacls . /grant John:(OI)(CI)F /T where John is the username
  4. profit

Just adding this because it seemed supremely easy this way and others may profit - all credit goes to Calin Darie.

Split string to equal length substrings in Java

Here's a one-liner version which uses Java 8 IntStream to determine the indexes of the slice beginnings:

String x = "Thequickbrownfoxjumps";

String[] result = IntStream
                    .iterate(0, i -> i + 4)
                    .limit((int) Math.ceil(x.length() / 4.0))
                    .mapToObj(i ->
                        x.substring(i, Math.min(i + 4, x.length())
                    )
                    .toArray(String[]::new);

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

SQL SELECT everything after a certain character

For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:

   CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END

REST HTTP status codes for failed validation or invalid duplicate

For input validation failure: 400 Bad Request + your optional description. This is suggested in the book "RESTful Web Services". For double submit: 409 Conflict


Update June 2014

The relevant specification used to be RFC2616, which gave the use of 400 (Bad Request) rather narrowly as

The request could not be understood by the server due to malformed syntax

So it might have been argued that it was inappropriate for semantic errors. But not any more; since June 2014 the relevant standard RFC 7231, which supersedes the previous RFC2616, gives the use of 400 (Bad Request) more broadly as

the server cannot or will not process the request due to something that is perceived to be a client error

How to programmatically get iOS status bar height

Swift 3 or Swift 4:

UIApplication.shared.statusBarFrame.height

comma separated string of selected values in mysql

Use group_concat() function of mysql.

SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;

It'll give you concatenated string like :

5,6,9,10,12,14,15,17,18,779 

CSS - How to Style a Selected Radio Buttons Label?

_x000D_
_x000D_
.radio-toolbar input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.radio-toolbar label {_x000D_
  display: inline-block;_x000D_
  background-color: #ddd;_x000D_
  padding: 4px 11px;_x000D_
  font-family: Arial;_x000D_
  font-size: 16px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.radio-toolbar input[type="radio"]:checked+label {_x000D_
  background-color: #bbb;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <input type="radio" id="radio1" name="radios" value="all" checked>_x000D_
  <label for="radio1">All</label>_x000D_
_x000D_
  <input type="radio" id="radio2" name="radios" value="false">_x000D_
  <label for="radio2">Open</label>_x000D_
_x000D_
  <input type="radio" id="radio3" name="radios" value="true">_x000D_
  <label for="radio3">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

First of all, you probably want to add the name attribute on the radio buttons. Otherwise, they are not part of the same group, and multiple radio buttons can be checked.

Also, since I placed the labels as siblings (of the radio buttons), I had to use the id and for attributes to associate them together.

Short rot13 function - Python

Here's a maketrans/translate solution

import string
rot13 = string.maketrans( 
    "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", 
    "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World!", rot13)
# 'Uryyb Jbeyq!'

Pass entire form as data in jQuery Ajax function

There's a function that does exactly this:

http://api.jquery.com/serialize/

var data = $('form').serialize();
$.post('url', data);

How to convert LINQ query result to List?

What you can do is select everything into a new instance of Course, and afterwards convert them to a List.

var qry = from a in obj.tbCourses
                     select new Course() {
                         Course.Property = a.Property
                         ...
                     };

qry.toList<Course>();

ssh_exchange_identification: Connection closed by remote host under Git bash

Got the same error too when connecting to GitHub with ssh as I move from one workplace to another. according to my situation, it seems that dns servers of different networks may get various ip address of github and the known_hosts file not identify it when changes happened. So change dns or switch back original network may work.

How do I round a double to two decimal places in Java?

where num is the double number

  • Integer 2 denotes the number of decimal places that we want to print.
  • Here we are taking 2 decimal palces

    System.out.printf("%.2f",num);

What does "&" at the end of a linux command mean?

The & makes the command run in the background.

From man bash:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

How can I display just a portion of an image in HTML/CSS?

As mentioned in the question, there is the clip css property, although it does require that the element being clipped is position: absolute; (which is a shame):

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
}_x000D_
#clip {_x000D_
  position: absolute;_x000D_
  clip: rect(0, 100px, 200px, 0);_x000D_
  /* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="clip" src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo, for experimentation.

To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path, which has replaced the now-deprecated clip property.

The clip-path property allows a range of options (more-so than the original clip), of:

  • inset — rectangular/cuboid shapes, defined with four values as 'distance-from' (top right bottom left).
  • circlecircle(diameter at x-coordinate y-coordinate).
  • ellipseellipse(x-axis-length y-axis-length at x-coordinate y-coordinate).
  • polygon — defined by a series of x/y coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point: polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...]).
  • url — this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat.

_x000D_
_x000D_
div.container {_x000D_
  display: inline-block;_x000D_
}_x000D_
#rectangular {_x000D_
  -webkit-clip-path: inset(30px 10px 30px 10px);_x000D_
  clip-path: inset(30px 10px 30px 10px);_x000D_
}_x000D_
#circle {_x000D_
  -webkit-clip-path: circle(75px at 50% 50%);_x000D_
  clip-path: circle(75px at 50% 50%)_x000D_
}_x000D_
#ellipse {_x000D_
  -webkit-clip-path: ellipse(75px 50px at 50% 50%);_x000D_
  clip-path: ellipse(75px 50px at 50% 50%);_x000D_
}_x000D_
#polygon {_x000D_
  -webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
  clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
}
_x000D_
<div class="container">_x000D_
  <img id="control" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="rectangular" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="circle" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="ellipse" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="polygon" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo, for experimentation.

References:

How to fill Dataset with multiple tables?

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

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

        try
        {
            connection.Open();

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

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

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

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

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

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

ASP.Net MVC - Read File from HttpPostedFileBase without save

An alternative is to use StreamReader.

public void FunctionName(HttpPostedFileBase file)
{
    string result = new StreamReader(file.InputStream).ReadToEnd();
}

How do I do a case-insensitive string comparison?

I saw this solution here using regex.

import re
if re.search('mandy', 'Mandy Pande', re.IGNORECASE):
# is True

It works well with accents

In [42]: if re.search("ê","ê", re.IGNORECASE):
....:        print(1)
....:
1

However, it doesn't work with unicode characters case-insensitive. Thank you @Rhymoid for pointing out that as my understanding was that it needs the exact symbol, for the case to be true. The output is as follows:

In [36]: "ß".lower()
Out[36]: 'ß'
In [37]: "ß".upper()
Out[37]: 'SS'
In [38]: "ß".upper().lower()
Out[38]: 'ss'
In [39]: if re.search("ß","ßß", re.IGNORECASE):
....:        print(1)
....:
1
In [40]: if re.search("SS","ßß", re.IGNORECASE):
....:        print(1)
....:
In [41]: if re.search("ß","SS", re.IGNORECASE):
....:        print(1)
....:

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

Removing page title and date when printing web page (with CSS?)

Historically, it's been impossible to make these things disappear as they are user settings and not considered part of the page you have control over.

However, as of 2017, the @page at-rule has been standardized, which can be used to hide the page title and date in modern browsers:

@page { size: auto;  margin: 0mm; }

Print headers/footers and print margins

When printing Web documents, margins are set in the browser's Page Setup (or Print Setup) dialog box. These margin settings, although set within the browser, are controlled at the operating system/printer driver level and are not controllable at the HTML/CSS/DOM level. (For CSS-controlled printed page headers and footers see Printing Headers .)

The settings must be big enough to encompass the printer's physical non-printing areas. Further, they must be big enough to encompass the header and footer that the browser is usually configured to print (typically the page title, page number, URL and date). Note that these headers and footers, although specified by the browser and usually configurable through user preferences, are not part of the Web page itself and therefore are not controllable by CSS. In CSS terms, they fall outside the Page Box CSS2.1 Section 13.2.

... i.e. setting a margin of 0 hides the page title because the title is printed in the margin.

Credit to Vigneswaran S for this tip.

get number of columns of a particular row in given excel using Java

/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
    int result = 0;
    Iterator<Row> rowIterator = xssfSheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        List<Cell> cells = new ArrayList<>();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            cells.add(cellIterator.next());
        }
        for (int i = cells.size(); i >= 0; i--) {
            Cell cell = cells.get(i-1);
            if (cell.toString().trim().isEmpty()) {
                cells.remove(i-1);
            } else {
                result = cells.size() > result ? cells.size() : result;
                break;
            }
        }
    }
    return result;
}

How to create a DataTable in C# and how to add rows?

You can write one liner using DataRow.Add(params object[] values) instead of four lines.

dt.Rows.Add("Ravi", "500");

As you create new DataTable object, there seems no need to Clear DataTable in very next statement. You can also use DataTable.Columns.AddRange to add columns with on statement. Complete code would be.

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name"), new DataColumn("Marks") });     
dt.Rows.Add("Ravi", "500");

What does O(log n) mean exactly?

But what exactly is O(log n)? For example, what does it mean to say that the height of a >complete binary tree is O(log n)?

I would rephrase this as 'height of a complete binary tree is log n'. Figuring the height of a complete binary tree would be O(log n), if you were traversing down step by step.

I cannot understand how to identify a function with a logarithmic time.

Logarithm is essentially the inverse of exponentiation. So, if each 'step' of your function is eliminating a factor of elements from the original item set, that is a logarithmic time algorithm.

For the tree example, you can easily see that stepping down a level of nodes cuts down an exponential number of elements as you continue traversing. The popular example of looking through a name-sorted phone book is essentially equivalent to traversing down a binary search tree (middle page is the root element, and you can deduce at each step whether to go left or right).

How do I make WRAP_CONTENT work on a RecyclerView

UPDATE

By Android Support Library 23.2 update, all WRAP_CONTENT should work correctly.

Please update version of a library in gradle file.

compile 'com.android.support:recyclerview-v7:23.2.0'

Original Answer

As answered on other question, you need to use original onMeasure() method when your recycler view height is bigger than screen height. This layout manager can calculate ItemDecoration and can scroll with more.

    public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {
        measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);

        if (getOrientation() == HORIZONTAL) {
            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }

    // If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
    if (height < heightSize && width < widthSize) {

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    } else {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {

   View view = recycler.getViewForPosition(position);

   // For adding Item Decor Insets to view
   super.measureChildWithMargins(view, 0, 0);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom() + getPaddingBottom() + getDecoratedBottom(view) , p.height);
            view.measure(childWidthSpec, childHeightSpec);

            // Get decorated measurements
            measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
            measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

original answer : https://stackoverflow.com/a/28510031/1577792

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Here is an alternative way if the data frame just contains numbers.

_x000D_
_x000D_
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
_x000D_
_x000D_

but the most reliable way of converting a data frame to a matrix is using data.matrix() function.

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

How do you create a hidden div that doesn't create a line break or horizontal space?

Use display:none;

<div id="divCheckbox" style="display: none;">
  • visibility: hidden hides the element, but it still takes up space in the layout.

  • display: none removes the element completely from the document, it doesn't take up any space.

How to find Max Date in List<Object>?

Just use Kotlin!

val list = listOf(user1, user2, user3)
val maxDate = list.maxBy { it.date }?.date

How to select all checkboxes with jQuery?

Simple and clean:

_x000D_
_x000D_
$('#select_all').click(function() {_x000D_
  var c = this.checked;_x000D_
  $(':checkbox').prop('checked', c);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" id="select_all" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

You don't have the right to execute it, although you have enough permissions to create it.

For more information, see GRANT Object Permissions (Transact-SQL)

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

This worked for me like a magic.

I logged into database and registered the listener.

alter system set local_listener='(...)';
alter system register;

How do I create a link using javascript?

<html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>

Hashing a file in Python

TL;DR use buffers to not use tons of memory.

We get to the crux of your problem, I believe, when we consider the memory implications of working with very large files. We don't want this bad boy to churn through 2 gigs of ram for a 2 gigabyte file so, as pasztorpisti points out, we gotta deal with those bigger files in chunks!

import sys
import hashlib

# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536  # lets read stuff in 64kb chunks!

md5 = hashlib.md5()
sha1 = hashlib.sha1()

with open(sys.argv[1], 'rb') as f:
    while True:
        data = f.read(BUF_SIZE)
        if not data:
            break
        md5.update(data)
        sha1.update(data)

print("MD5: {0}".format(md5.hexdigest()))
print("SHA1: {0}".format(sha1.hexdigest()))

What we've done is we're updating our hashes of this bad boy in 64kb chunks as we go along with hashlib's handy dandy update method. This way we use a lot less memory than the 2gb it would take to hash the guy all at once!

You can test this with:

$ mkfile 2g bigfile
$ python hashes.py bigfile
MD5: a981130cf2b7e09f4686dc273cf7187e
SHA1: 91d50642dd930e9542c39d36f0516d45f4e1af0d
$ md5 bigfile
MD5 (bigfile) = a981130cf2b7e09f4686dc273cf7187e
$ shasum bigfile
91d50642dd930e9542c39d36f0516d45f4e1af0d  bigfile

Hope that helps!

Also all of this is outlined in the linked question on the right hand side: Get MD5 hash of big files in Python


Addendum!

In general when writing python it helps to get into the habit of following pep-8. For example, in python variables are typically underscore separated not camelCased. But that's just style and no one really cares about those things except people who have to read bad style... which might be you reading this code years from now.

How to create major and minor gridlines with different linestyles in Python

A simple DIY way would be to make the grid yourself:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot([1,2,3], [2,3,4], 'ro')

for xmaj in ax.xaxis.get_majorticklocs():
  ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
  ax.axvline(x=xmin, ls='--')

for ymaj in ax.yaxis.get_majorticklocs():
  ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
  ax.axhline(y=ymin, ls='--')
plt.show()

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table

FIDDLE

insert into funds (ID, date, price) 
select 
    T.* 
from 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and funds.date = T.date
where 
    funds.ID is null

How do I add an element to array in reducer of React native redux?

I have a sample

import * as types from '../../helpers/ActionTypes';

var initialState = {
  changedValues: {}
};
const quickEdit = (state = initialState, action) => {

  switch (action.type) {

    case types.PRODUCT_QUICKEDIT:
      {
        const item = action.item;
        const changedValues = {
          ...state.changedValues,
          [item.id]: item,
        };

        return {
          ...state,
          loading: true,
          changedValues: changedValues,
        };
      }
    default:
      {
        return state;
      }
  }
};

export default quickEdit;

How store a range from excel into a Range variable?

Define what GetData is. At the moment it is not defined.

Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant

Bind failed: Address already in use

The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.

Also check if you are binding to the right ip address (I am assuming it would be localhost)

Working with a List of Lists in Java

ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> singleList = new ArrayList<String>();
singleList.add("hello");
singleList.add("world");
listOLists.add(singleList);

ArrayList<String> anotherList = new ArrayList<String>();
anotherList.add("this is another list");
listOLists.add(anotherList);

Angular get object from array by Id

// Used In TypeScript For Angular 4+        
const viewArray = [
          {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
          {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
          {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
          {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
          {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
          {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
          {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
          {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
          {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
          {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
          {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
          {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
          {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
          {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
          {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
    ];

         const arrayObj = any;
         const objectData = any;

          for (let index = 0; index < this.viewArray.length; index++) {
              this.arrayObj = this.viewArray[index];
              this.arrayObj.filter((x) => {
                if (x.id === id) {
                  this.objectData = x;
                }
              });
              console.log('Json Object Data by ID ==> ', this.objectData);
            }
          };

Determine if running on a rooted device

Instead of using isRootAvailable() you can use isAccessGiven(). Direct from RootTools wiki:

if (RootTools.isAccessGiven()) {
    // your app has been granted root access
}

RootTools.isAccessGiven() not only checks that a device is rooted, it also calls su for your app, requests permission, and returns true if your app was successfully granted root permissions. This can be used as the first check in your app to make sure that you will be granted access when you need it.

Reference

How do I apply CSS3 transition to all properties except background-position?

Try this...

* {
    transition: all .2s linear;
    -webkit-transition: all .2s linear;
    -moz-transition: all .2s linear;
    -o-transition: all .2s linear;
}
a {
    -webkit-transition: background-position 1ms linear;
    -moz-transition: background-position 1ms linear;
    -o-transition: background-position 1ms linear;
    transition: background-position 1ms linear;
}