Programs & Examples On #Comtypes

Why do we not have a virtual constructor in C++?

If you think logically about how constructors work and what the meaning/usage of a virtual function is in C++ then you will realise that a virtual constructor would be meaningless in C++. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you cannot be creating a sub-class of the class, you must be creating the class so there would never be any need to declare a constructor virtual.

And another reason is, the constructors have the same name as its class name and if we declare constructor as virtual, then it should be redefined in its derived class with the same name, but you can not have the same name of two classes. So it is not possible to have a virtual constructor.

How to generate a Dockerfile from an image?

Update Dec 2018 to BMW's answer

chenzj/dfimage - as described on hub.docker.com regenerates Dockerfile from other images. So you can use it as follows:

docker pull chenzj/dfimage
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"
dfimage IMAGE_ID > Dockerfile

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

I had the URL from run time, below gave the correct answer:

let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);

hope this helps

Getting the exception value in Python

Use repr() and The difference between using repr and str

Using repr:

>>> try:
...     print(x)
... except Exception as e:
...     print(repr(e))
... 
NameError("name 'x' is not defined")

Using str:

>>> try:
...     print(x)
... except Exception as e:
...     print(str(e))
... 
name 'x' is not defined

Find an element by class name, from a known parent element

You were close. You can do:

var element = $("#parentDiv").find(".myClassNameOfInterest");

Alternatively, you can do:

var element = $(".myClassNameOfInterest", "#parentDiv");

...which sets the context of the jQuery object to the #parentDiv.

EDIT:

Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest instead of just .myClassNameOfInterest.

Using OpenSSL what does "unable to write 'random state'" mean?

One other issue on the Windows platform, make sure you are running your command prompt as an Administrative User!

I don't know how many times this has bitten me...

How to compile and run C in sublime text 3?

We can compile the code of C in Sublime Text and can print some value or strings but it does not accept input from the user. (Till I know... I am sure about compiling but not about output from given input.) If you are using Windows you have to set the environment variables for Sublime Text and GCC compiler.

How can I convert byte size into a human-readable format in Java?

I usually do it in this way, what do you think?

public static String getFileSize(double size) {
    return _getFileSize(size,0,1024);
}

public static String _getFileSize(double size, int i, double base) {
    String units = " KMGTP";
    String unit = (i>0)?(""+units.charAt(i)).toUpperCase()+"i":"";
    if(size<base)
        return size +" "+unit.trim()+"B";
    else {
        size = Math.floor(size/base);
        return _getFileSize(size,++i,base);
    }
}

How to import module when module name has a '-' dash or hyphen in it?

If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary:

 ---- foo_proxy.py ----
 tmp = __import__('foo-bar')
 globals().update(vars(tmp))

 ---- main.py ----
 from foo_proxy import * 

Unzipping files

I wrote "Binary Tools for JavaScript", an open source project that includes the ability to unzip, unrar and untar: https://github.com/codedread/bitjs

Used in my comic book reader: https://github.com/codedread/kthoom (also open source).

HTH!

Vue Js - Loop via v-for X times (in a range)

The same goes for v-for in range:

<li v-for="n in 20 " :key="n">{{n}}</li>

'this' vs $scope in AngularJS controllers

$scope has a different 'this' then the controller 'this'.Thus if you put a console.log(this) inside controller it gives you a object(controller) and this.addPane() adds addPane Method to the controller Object. But the $scope has different scope and all method in its scope need to be accesed by $scope.methodName(). this.methodName() inside controller means to add methos inside controller object.$scope.functionName() is in HTML and inside

$scope.functionName(){
    this.name="Name";
    //or
    $scope.myname="myname"//are same}

Paste this code in your editor and open console to see...

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>this $sope vs controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
    <script>
        var app=angular.module("myApp",[]);
app.controller("ctrlExample",function($scope){
          console.log("ctrl 'this'",this);
          //this(object) of controller different then $scope
          $scope.firstName="Andy";
          $scope.lastName="Bot";
          this.nickName="ABot";
          this.controllerMethod=function(){

            console.log("controllerMethod ",this);
          }
          $scope.show=function(){
              console.log("$scope 'this",this);
              //this of $scope
              $scope.message="Welcome User";
          }

        });
</script>
</head>
<body ng-app="myApp" >
<div ng-controller="ctrlExample">
       Comming From $SCOPE :{{firstName}}
       <br><br>
       Comming from $SCOPE:{{lastName}}
       <br><br>
       Should Come From Controller:{{nickName}}
       <p>
            Blank nickName is because nickName is attached to 
           'this' of controller.
       </p>

       <br><br>
       <button ng-click="controllerMethod()">Controller Method</button>

       <br><br>
       <button ng-click="show()">Show</button>
       <p>{{message}}</p>

   </div>

</body>
</html>

static linking only some libraries

gcc -lsome_dynamic_lib code.c some_static_lib.a

ActionController::InvalidAuthenticityToken

If you have done a rake rails:update or otherwise recently changed your config/initializers/session_store.rb, this may be a symptom of old cookies in the browser. Hopefully this is done in dev/test (it was for me), and you can just clear all browser cookies related to the domain in question.

If this is in production, and you changed key, consider changing it back to use the old cookies (<- just speculation).

Can I access variables from another file?

You can export the variable from first file using export.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
export { colorCode };

Then, import the variable in second file using import.

//second.js
import { colorCode } from './first.js'

export - MDN

array of string with unknown size

Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?

How to set a parameter in a HttpServletRequest?

You can't, not using the standard API. HttpServletRequest represent a request received by the server, and so adding new parameters is not a valid option (as far as the API is concerned).

You could in principle implement a subclass of HttpServletRequestWrapper which wraps the original request, and intercepts the getParameter() methods, and pass the wrapped request on when you forward.

If you go this route, you should use a Filter to replace your HttpServletRequest with a HttpServletRequestWrapper:

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    if (servletRequest instanceof HttpServletRequest) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // Check wether the current request needs to be able to support the body to be read multiple times
        if (MULTI_READ_HTTP_METHODS.contains(request.getMethod())) {
            // Override current HttpServletRequest with custom implementation
            filterChain.doFilter(new HttpServletRequestWrapper(request), servletResponse);
            return;
        }
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

Closing Applications

Application.Exit is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.

Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).

For more detail see the MSDN documentation.

Angular, content type is not being sent with $http

In case it's useful to anyone. For AngularJS 1.5x I wanted to set CSRF for all requests and I found that when I did this:

$httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; 
$httpProvider.defaults.headers.put = { 'CSRF-Token': afToken };
$httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; 

Angular removed the content type so I had to add this:

$httpProvider.defaults.headers.common = { "Content-Type": "application/json"};

Otherwise I get a 415 media type error.

So I am doing this to configure my application for all requests:

angular.module("myapp.maintenance", [])
    .controller('maintenanceCtrl', MaintenanceCtrl)
    .directive('convertToNumber', ConvertToNumber)
    .config(configure);

MaintenanceCtrl.$inject = ["$scope", "$http", "$sce", "$window", "$document", "$timeout", "$filter", 'alertService'];
configure.$inject = ["$httpProvider"];

// configure the header tokens for  CSRF for http operations in this module
function configure($httpProvider) {

    const afToken = angular.element('input[id="__AntiForgeryToken"]').attr('value');

    $httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; // only added for GET
    $httpProvider.defaults.headers.put = { 'CSRF-Token': afToken }; // added for PUT
    $httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; // added for POST

    // for some reason if we do the above we have to set the default content type for all 
    // looks like angular clears it when we add our own headers
    $httpProvider.defaults.headers.common = { "Content-Type": "application/json" };

}

Compiling problems: cannot find crt1.o

./configure --disable-multilib

works for it

How to re-render flatlist?

If you are going to have a Button, you can update the data with a setState inside the onPress. SetState will then re-render your FlatList.

How to implement endless list with RecyclerView?

My answer is a modified version of Noor. I passed from a ListView where i had EndlessScrollListener (that you can find easily in many answers on SO) to a RecyclerView so i wanted a EndlessRecyclScrollListener to easily update my past listener.

So here is the code, hope it helps:

public abstract class EndlessScrollRecyclListener extends RecyclerView.OnScrollListener
{
    // The total number of items in the dataset after the last load
    private int previousTotalItemCount = 0;
    private boolean loading = true;
    private int visibleThreshold = 5;
    int firstVisibleItem, visibleItemCount, totalItemCount;
    private int startingPageIndex = 0;
    private int currentPage = 0;

    @Override
    public void onScrolled(RecyclerView mRecyclerView, int dx, int dy)
    {
        super.onScrolled(mRecyclerView, dx, dy);
        LinearLayoutManager mLayoutManager = (LinearLayoutManager) mRecyclerView
                .getLayoutManager();

        visibleItemCount = mRecyclerView.getChildCount();
        totalItemCount = mLayoutManager.getItemCount();
        firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
        onScroll(firstVisibleItem, visibleItemCount, totalItemCount);
    }

    public void onScroll(int firstVisibleItem, int visibleItemCount, int totalItemCount)
    {
        // If the total item count is zero and the previous isn't, assume the
        // list is invalidated and should be reset back to initial state
        if (totalItemCount < previousTotalItemCount)
        {
            this.currentPage = this.startingPageIndex;
            this.previousTotalItemCount = totalItemCount;
            if (totalItemCount == 0)
            {
                this.loading = true;
            }
        }
        // If it’s still loading, we check to see if the dataset count has
        // changed, if so we conclude it has finished loading and update the current page
        // number and total item count.
        if (loading && (totalItemCount > previousTotalItemCount))
        {
            loading = false;
            previousTotalItemCount = totalItemCount;
            currentPage++;
        }

        // If it isn’t currently loading, we check to see if we have breached
        // the visibleThreshold and need to reload more data.
        // If we do need to reload some more data, we execute onLoadMore to fetch the data.
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem +
                visibleThreshold))
        {
            onLoadMore(currentPage + 1, totalItemCount);
            loading = true;
        }
    }

    // Defines the process for actually loading more data based on page
    public abstract void onLoadMore(int page, int totalItemsCount);

}

How do I know which version of Javascript I'm using?

All of todays browsers use at least version 1.5:
http://en.wikipedia.org/wiki/ECMAScript#Dialect

Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide

You may still want to watch out for features which require version 1.6 or above, as this might give Internet Explorer some troubles.

Swift's guard keyword

Guard statement going to do . it is couple of different

1) it is allow me to reduce nested if statement
2) it is increase my scope which my variable accessible

if Statement

func doTatal(num1 : Int?, num2: Int?) {
  // nested if statement
    if let fistNum = num1 where num1 > 0 {
        if let lastNum = num2 where num2 < 50 {

          let total = fistNum + lastNum
        }
    }
 // don't allow me to access out of the scope 
 //total = fistNum + lastNum 
}

Guard statement

func doTatal(num1 : Int?, num2: Int?) {
   //reduce  nested if statement and check positive way not negative way 
    guard let fistNum = num1 where num1 > 0 else{
      return
    }
    guard  let lastNum = num2 where num2 < 50 else {
     return
    }
    // increase my scope which my variable accessible
    let total = fistNum + lastNum

}

c# - approach for saving user settings in a WPF application?

  1. In all the places I've worked, database has been mandatory because of application support. As Adam said, the user might not be at his desk or the machine might be off, or you might want to quickly change someone's configuration or assign a new-joiner a default (or team member's) config.

  2. If the settings are likely to grow as new versions of the application are released, you might want to store the data as blobs which can then be deserialized by the application. This is especially useful if you use something like Prism which discovers modules, as you can't know what settings a module will return. The blobs could be keyed by username/machine composite key. That way you can have different settings for every machine.

  3. I've not used the in-built Settings class much so I'll abstain from commenting. :)

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

If that's a valid date/time entry then excel simply stores it as a number (days are integers and the time is the decimal part) so you can do a simple subtraction.

I'm not sure if 7/6 is 7th June or 6th July, assuming the latter then it's a future date so you can get the difference in days with

=INT(A1-TODAY())

Make sure you format result cell as general or number (not date)

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.

Formatting PowerShell Get-Date inside string

You can use the -f operator

$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)

Spécificator    Type                                Example (with [datetime]::now)
d   Short date                                        26/09/2002
D   Long date                                       jeudi 26 septembre 2002
t   Short Hour                                      16:49
T   Long Hour                                       16:49:31
f   Date and hour                                   jeudi 26 septembre 2002 16:50
F   Long Date and hour                              jeudi 26 septembre 2002 16:50:51
g   Default Date                                    26/09/2002 16:52
G   Long default Date and hour                      26/09/2009 16:52:12
M   Month Symbol                                    26 septembre
r   Date string RFC1123                             Sat, 26 Sep 2009 16:54:50 GMT
s   Sortable string date                            2009-09-26T16:55:58
u   Sortable string date universal local hour       2009-09-26 16:56:49Z
U   Sortable string date universal GMT hour         samedi 26 septembre 2009 14:57:22 (oups)
Y   Year symbol                                     septembre 2002

Spécificator    Type                       Example      Output Example
dd              Jour                       {0:dd}       10
ddd             Name of the day            {0:ddd}      Jeu.
dddd            Complet name of the day    {0:dddd}     Jeudi
f, ff, …        Fractions of seconds       {0:fff}      932
gg, …           position                   {0:gg}       ap. J.-C.
hh              Hour two digits            {0:hh}       10
HH              Hour two digits (24 hours) {0:HH}       22
mm              Minuts 00-59               {0:mm}       38
MM              Month 01-12                {0:MM}       12
MMM             Month shortcut             {0:MMM}      Sep.
MMMM            complet name of the month  {0:MMMM}     Septembre
ss              Seconds 00-59              {0:ss}       46
tt              AM or PM                   {0:tt}       ““
yy              Years, 2 digits            {0:yy}       02
yyyy            Years                      {0:yyyy}     2002
zz              Time zone, 2 digits        {0:zz}       +02
zzz             Complete Time zone         {0:zzz}      +02:00
:               Separator                  {0:hh:mm:ss}     10:43:20
/               Separator                  {0:dd/MM/yyyy}   10/12/2002

Batch file to split .csv file

I found this question while looking for a similar solution. I modified the answer that @Dale gave to suit my purposes. I wanted something that was a little more flexible and had some error trapping. Just thought I might put it here for anyone looking for the same thing.

@echo off
setLocal EnableDelayedExpansion
GOTO checkvars

:checkvars
    IF "%1"=="" GOTO syntaxerror
    IF NOT "%1"=="-f"  GOTO syntaxerror
    IF %2=="" GOTO syntaxerror
    IF NOT EXIST %2 GOTO nofile
    IF "%3"=="" GOTO syntaxerror
    IF NOT "%3"=="-n" GOTO syntaxerror
    IF "%4"==""  GOTO syntaxerror
    set param=%4
    echo %param%| findstr /xr "[1-9][0-9]* 0" >nul && (
        goto proceed
    ) || (
        echo %param% is NOT a valid number
        goto syntaxerror
    )

:proceed
    set limit=%4
    set file=%2
    set lineCounter=1+%limit%
    set filenameCounter=0

    set name=
    set extension=

    for %%a in (%file%) do (
        set "name=%%~na"
        set "extension=%%~xa"
    )

    for /f "usebackq tokens=*" %%a in (%file%) do (
        if !lineCounter! gtr !limit! (
            set splitFile=!name!_part!filenameCounter!!extension!
            set /a filenameCounter=!filenameCounter! + 1
            set lineCounter=1
            echo Created !splitFile!.
        )
        cls
        echo Adding Line !splitFile! - !lineCounter!
        echo %%a>> !splitFile!
        set /a lineCounter=!lineCounter! + 1
    )
    echo Done!
    goto end
:syntaxerror
    Echo Syntax: %0 -f Filename -n "Number Of Rows Per File"
    goto end
:nofile
    echo %2 does not exist
    goto end
:end

adding child nodes in treeview

You can improve that code

 private void Form1_Load(object sender, EventArgs e)
    {
        /*
         D:\root\Project1\A\A.pdf
         D:\root\Project1\B\t.pdf
         D:\root\Project2\c.pdf
         */
        List<string> n = new List<string>();
        List<string> kn = new List<string>();
        n = Directory.GetFiles(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        kn = Directory.GetDirectories(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        foreach (var item in kn)
        {
            treeView1.Nodes.Add(item.ToString());
        }
        for (int i = 0; i < treeView1.Nodes.Count; i++)
        {
            n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
            for (int zik = 0; zik < n.Count; zik++)
            {
                treeView1.Nodes[i].Nodes.Add(n[zik].ToString());
            }
        }        
    }

Uploading files to file server using webclient class

namespace FileUpload
{
public partial class Form1 : Form
{
    string fileName = "";
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        string path = "";
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "Attach customer proposal document";
        fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
        fDialog.InitialDirectory = @"C:\";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = System.IO.Path.GetFileName(fDialog.FileName);
            path = Path.GetDirectoryName(fDialog.FileName);
            textBox1.Text = path + "\\" + fileName;

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            WebClient client = new WebClient();

            NetworkCredential nc = new NetworkCredential("erandika1986", "123");

            Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);

            client.Credentials = nc;
            byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
            MessageBox.Show(arrReturn.ToString());

        }
        catch (Exception ex1)
        {
            MessageBox.Show(ex1.Message);
        }
    }
}
}

Keyboard shortcut to comment lines in Sublime Text 2

In keyboard (Spanish), SO: Win7.

Go into Preferences->Key Bindings - Default, replace..."ctrl+/"]... by "ctrl+7"...

And don't use the numpad, it doesn't work. Just use the numbers above the letters

Get single listView SelectedItem

foreach (ListViewItem itemRow in taskShowListView.Items)
{
    if (itemRow.Items[0].Checked == true)
    {
        int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

        string taskDate = itemRow.SubItems[1].ToString();
        string taskDescription = itemRow.SubItems[2].ToString();            
    }
}

How to initialize private static members in C++?

I don't have enough rep here to add this as a comment, but IMO it's good style to write your headers with #include guards anyway, which as noted by Paranaix a few hours ago would prevent a multiple-definition error. Unless you're already using a separate CPP file, it's not necessary to use one just to initialize static non-integral members.

#ifndef FOO_H
#define FOO_H
#include "bar.h"

class foo
{
private:
    static bar i;
};

bar foo::i = VALUE;
#endif

I see no need to use a separate CPP file for this. Sure, you can, but there's no technical reason why you should have to.

No @XmlRootElement generated by JAXB

JAXBElement wrappers works for cases where no @XmlRootElement is generated by JAXB. These wrappers are available in ObjectFactory class generated by maven-jaxb2-plugin. For eg:

     public class HelloWorldEndpoint {
        @PayloadRoot(namespace = NAMESPACE_URI, localPart = "person")
        @ResponsePayload
        public JAXBElement<Greeting> sayHello(@RequestPayload JAXBElement<Person> request) {

        Person person = request.getValue();

        String greeting = "Hello " + person.getFirstName() + " " + person.getLastName() + "!";

        Greeting greet = new Greeting();
        greet.setGreeting(greeting);

        ObjectFactory factory = new ObjectFactory();
        JAXBElement<Greeting> response = factory.createGreeting(greet);
        return response;
      }
 }

Basic communication between two fragments

The nicest and recommended way is to use a shared ViewModel.

https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

From Google doc:

public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

public void select(Item item) {
    selected.setValue(item);
}

public LiveData<Item> getSelected() {
    return selected;
}
}


public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
    itemSelector.setOnClickListener(item -> {
        model.select(item);
    });
}
}


public class DetailFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
    model.getSelected().observe(this, { item ->
       // Update the UI.
    });
}
}

ps: two fragments never communicate directly

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Take for example the case where Class A has a getSomething method and class B has a getSomething method and class C extends A and B. What would happen if someone called C.getSomething? There is no way to determine which method to call.

Interfaces basically just specify what methods a implementing class needs to contain. A class that implements multiple interfaces just means that class has to implement the methods from all those interfaces. Whci would not lead to any issues as described above.

How to increase size of DOSBox window?

Here's how to change the dosbox.conf file in Linux to increase the size of the window. I actually DID what follows, so I can say it works (in 32-bit PCLinuxOS fullmontyKDE, anyway). The question's answer is in the .conf file itself.

You find this file in Linux at /home/(username)/.dosbox . In Konqueror or Dolphin, you must first check 'Hidden files' or you won't see the folder. Open it with KWrite superuser or your fav editor.

  1. Save the file with another name like 'dosbox-0.74original.conf' to preserve the original file in case you need to restore it.
  2. Search on 'resolution' and carefully read what the conf file says about changing it. There are essentially two variables: resolution and output. You want to leave fullresolution alone for now. Your question was about WINDOW, not full. So look for windowresolution, see what the comments in conf file say you can do. The best suggestion is to use a bigger-window resolution like 900x800 (which is what I used on a 1366x768 screen), but NOT the actual resolution of your machine (which would make the window fullscreen, and you said you didn't want that). Be specific, replacing the 'windowresolution=original' with 'windowresolution=900x800' or other dimensions. On my screen, that doubled the window size just as it does with the max Font tab in Windows Properties (for the exe file; as you'll see below the ==== marks, 32-bit Windows doesn't need Dosbox).

Then, search on 'output', and as the instruction in the conf file warns, if and only if you have 'hardware scaling', change the default 'output=surface' to something else; he then lists the optional other settings. I changed it to 'output=overlay'. There's one other setting to test: aspect. Search the file for 'aspect', and change the 'false' to 'true' if you want an even bigger window. When I did this, the window took up over half of the screen. With 'false' left alone, I had a somewhat smaller window (I use widescreen monitors, whether laptop or desktop, maybe that's why).

So after you've made the changes, save the file with the original name of dosbox-0.74.conf . Then, type dosbox at the command line or create a Launcher (in KDE, this is a right click on the desktop) with the command dosbox. You still have to go through the mount command (i.e., mount c~ c:\123 if that's the location and file you'll execute). I'm sure there's a way to make a script, but haven't yet learned how to do that.

How can you represent inheritance in a database?

I lean towards method #1 (a unified Section table), for the sake of efficiently retrieving entire policies with all their sections (which I assume your system will be doing a lot).

Further, I don't know what version of SQL Server you're using, but in 2008+ Sparse Columns help optimize performance in situations where many of the values in a column will be NULL.

Ultimately, you'll have to decide just how "similar" the policy sections are. Unless they differ substantially, I think a more-normalized solution might be more trouble than it's worth... but only you can make that call. :)

Paused in debugger in chrome?

At the right upper corner second last icon (encircled red in attached image) is for activate/deactivate debugging. Click it to toggle debugging anytime.

Chrome Debug console

MongoDB: How to find the exact version of installed MongoDB

To check mongodb version use the mongod command with --version option.

To check MongoDB Server version, Open the command line via your terminal program and execute the following command:

Path : C:\Program Files\MongoDB\Server\3.2\bin Open Cmd and execute the following command: mongod --version To Check MongoDB Shell version, Type:

mongo --version

How to know what the 'errno' means?

There's a few useful functions for dealing with errnos. (Just to make it clear, these are built-in to libc -- I'm just providing sample implementations because some people find reading code clearer than reading English.)

#include <string.h>
char *strerror(int errnum);

/* you can think of it as being implemented like this: */
static char strerror_buf[1024];
const char *sys_errlist[] = {
    [EPERM]  = "Operation not permitted",
    [ENOENT] = "No such file or directory",
    [ESRCH]  = "No such process",
    [EINTR]  = "Interrupted system call",
    [EIO]    = "I/O error",
    [ENXIO]  = "No such device or address",
    [E2BIG]  = "Argument list too long",
    /* etc. */
};
int sys_nerr = sizeof(sys_errlist) / sizeof(char *);
char *strerror(int errnum) {
    if (0 <= errnum && errnum < sys_nerr && sys_errlist[errnum])
        strcpy(strerror_buf, sys_errlist[errnum]);
    else
        sprintf(strerror_buf, "Unknown error %d", errnum);
    return strerror_buf;
}

strerror returns a string describing the error number you've passed to it. Caution, this is not thread- or interrupt-safe; it is free to rewrite the string and return the same pointer on the next invocation. Use strerror_r if you need to worry about that.

#include <stdio.h>
void perror(const char *s);

/* you can think of it as being implemented like this: */
void perror(const char *s) {
    fprintf(stderr, "%s: %s\n", s, strerror(errno));
}

perror prints out the message you give it, plus a string describing the current errno, to standard error.

"std::endl" vs "\n"

The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.

The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl.

Link and execute external JavaScript file hosted on GitHub

I had the same issue as you, what I did is change to

<script type="application/javascript" src="bootstrap-wysiwyg.js"></script>

It works for me.

Telnet is not recognized as internal or external command

You have to go to Control Panel>Programs>Turn Windows features on or off. Then, check "Telnet Client" and save the changes. You might have to wait about a few minutes before the change could take effect.

deny directory listing with htaccess

Options -Indexes should work to prevent directory listings.

If you are using a .htaccess file make sure you have at least the "allowoverride options" setting in your main apache config file.

Can I have multiple background images using CSS?

You could have a div for the top with one background and another for the main page, and seperate the page content between them or put the content in a floating div on another z-level. The way you are doing it may work but I doubt it will work across every browser you encounter.

How can I print out C++ map values?

If your compiler supports (at least part of) C++11 you could do something like:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "\n";

For C++03 I'd use std::copy with an insertion operator instead:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first << " " << t.second.first << " " << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));

Is it necessary to use # for creating temp tables in SQL server?

Yes. You need to prefix the table name with "#" (hash) to create temporary tables.

If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.

"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.

Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005

If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.

They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.

DECLARE @ItemBack1 TABLE
(
 column1 int,
 column2 int,
 someInt int,
 someVarChar nvarchar(50)
);

INSERT INTO @ItemBack1
SELECT column1, 
       column2, 
       someInt, 
       someVarChar 
  FROM table2
 WHERE table2.ID = 7;

More Info on Table Variables: http://odetocode.com/articles/365.aspx

How to Join to first row

EDIT: nevermind, Quassnoi has a better answer.

For SQL2K, something like this:

SELECT 
  Orders.OrderNumber
, LineItems.Quantity
, LineItems.Description
FROM (  
  SELECT 
    Orders.OrderID
  , Orders.OrderNumber
  , FirstLineItemID = (
      SELECT TOP 1 LineItemID
      FROM LineItems
      WHERE LineItems.OrderID = Orders.OrderID
      ORDER BY LineItemID -- or whatever else
      )
  FROM Orders
  ) Orders
JOIN LineItems 
  ON LineItems.OrderID = Orders.OrderID 
 AND LineItems.LineItemID = Orders.FirstLineItemID

ITSAppUsesNonExemptEncryption export compliance while internal testing?

Add this key in plist file...Everything will be alright..

<key>ITSAppUsesNonExemptEncryption</key>  
<false/>

Just paste before </dict></plist>

Visual c++ can't open include file 'iostream'

Make sure you have Desktop Development with C++ installed. I was experiencing the same problem because I only had Universal Windows Platform Development installed.

How to play video with AVPlayerViewController (AVKit) in Swift

Swift 5+

First of all you have to define 2 variables globally inside your view controller.

var player: AVPlayer!
var playerViewController: AVPlayerViewController!

Here I'm adding player to a desired view.

@IBOutlet weak var playerView: UIView!

Then add following code to the viewDidLoad method.

let videoURL = URL(string: "videoUrl")
self.player = AVPlayer(url: videoURL!)
self.playerViewController = AVPlayerViewController()
playerViewController.player = self.player
playerViewController.view.frame = self.playerView.frame
playerViewController.player?.pause()
self.playerView.addSubview(playerViewController.view)

If you are not defining player and playerViewController globally, you won't be able to embed player.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

I had the same error. I checked the error logs: C:\ProgramData\MySQL\MySQL Server 5.5\data\inf3rno-PC.err. According to them

170208  1:06:25 [Note] C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld: Shutdown complete

170208  1:10:44 [Note] Plugin 'FEDERATED' is disabled.
170208  1:10:44 InnoDB: The InnoDB memory heap is disabled
170208  1:10:44 InnoDB: Mutexes and rw_locks use Windows interlocked functions
170208  1:10:44 InnoDB: Compressed tables use zlib 1.2.3
170208  1:10:44  InnoDB: Error: unable to create temporary file; errno: 2
170208  1:10:44 [ERROR] Plugin 'InnoDB' init function returned error.
170208  1:10:44 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
170208  1:10:44 [ERROR] Unknown/unsupported storage engine: INNODB
170208  1:10:44 [ERROR] Aborting

I think the important part here

170208  1:10:44  InnoDB: Error: unable to create temporary file; errno: 2

I changed the TMP and TEMP env variables from C:\Windows\Temp to %USERPROFILE%\AppData\Local\Temp yesterday, because I was unable to compress a directory and according to many post the solution is that. Now compression works, but mysql and apparently nod32 complains that they cannot create temporary files...

I added tmpdir=c:/server/mytmp to C:\Program Files\MySQL\MySQL Server 5.5\my.ini. And after that started the service again with services.msc. It is okay now.

So this can be a possible cause as well. I strongly suggest to everybody encountering this problem to check the error logs.

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

How to customize the background/border colors of a grouped table view cell?

I know the answers are relating to changing grouped table cells, but in case someone is wanting to also change the tableview's background color:

Not only do you need to set:

tableview.backgroundColor = color;

You also need to change or get rid of the background view:

tableview.backgroundView = nil;  

How to get first N number of elements from an array

arr.length = n

This might be surprising but length property of an array is not only used to get number of array elements but it's also writable and can be used to set array's length MDN link. This will mutate the array.

If you don't care about immutability or don't want to allocate memory i.e. for a game this will be the fastest way.

to empty an array

arr.length = 0

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

I like the other suggestions but I would rather not update the machine.config for a single application. I suggest that you just add it to the web.config / app.config. Here is what I needed to use the MySql Connector/NET that I "bin" deployed.

<system.data>
    <DbProviderFactories >
        <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
</system.data>

Java JDBC connection status

If you are using MySQL

public static boolean isDbConnected() {
    final String CHECK_SQL_QUERY = "SELECT 1";
    boolean isConnected = false;
    try {
        final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
        isConnected = true;
    } catch (SQLException | NullPointerException e) {
        // handle SQL error here!
    }
    return isConnected;
}

I have not tested with other databases. Hope this is helpful.

How Should I Set Default Python Version In Windows?

Running 'py' command will tell you what version you have running. If you currently running 3.x and you need to switch to 2.x, you will need to use switch '-2'

py -2

If you need to switch from python 2.x to python 3.x you will have to use '-3' switch

py -3

If you would like to have Python 3.x as a default version, then you will need to create environment variable 'PY_PYTHON' and set it's value to 3.

Finding multiple occurrences of a string within a string in Python

Maybe not so Pythonic, but somewhat more self-explanatory. It returns the position of the word looked in the original string.

def retrieve_occurences(sequence, word, result, base_counter):
     indx = sequence.find(word)
     if indx == -1:
         return result
     result.append(indx + base_counter)
     base_counter += indx + len(word)
     return retrieve_occurences(sequence[indx + len(word):], word, result, base_counter)

Android Studio: Module won't show up in "Edit Configuration"

Well, nothing worked for me from all the answers. Finally, I clicked Run > Edit Configuration. On the left, u can choose a new main module and remove to deleted ones.

Plot mean and standard deviation

plt.errorbar can be used to plot x, y, error data (as opposed to the usual plt.plot)

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])

plt.errorbar(x, y, e, linestyle='None', marker='^')

plt.show()

plt.errorbar accepts the same arguments as plt.plot with additional yerr and xerr which default to None (i.e. if you leave them blank it will act as plt.plot).

Example plot

Properly Handling Errors in VBA (Excel)

This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...

I hope this summarizes it for others. There is an Err object and an active (or inactive) ErrorHandler. Both need to be handled and reset for new errors.

Paste this into a workbook and step through it with F8.

Sub ErrorHandlingDemonstration()

    On Error GoTo ErrorHandler

    'this will error
    Debug.Print (1 / 0)

    'this will also error
    dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)

    'silly error
    Dummy2 = "string" * 50

    Exit Sub

zeroDivisionErrorBlock:
    maybeWe = "did some cleanup on variables that shouldnt have been divided!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

vlookupFailedErrorBlock:
    maybeThisTime = "we made sure the value we were looking for was in the range!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

catchAllUnhandledErrors:
    MsgBox(thisErrorsDescription)
    Exit Sub

ErrorHandler:
    thisErrorsNumberBeforeReset = Err.Number
    thisErrorsDescription = Err.Description
    'this will reset the error object and error handling
    On Error GoTo 0
    'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
    On Error GoTo ErrorHandler

    ' 11 is the err.number for division by 0
    If thisErrorsNumberBeforeReset = 11 Then
        GoTo zeroDivisionErrorBlock
    ' 1004 is the err.number for vlookup failing
    ElseIf thisErrorsNumberBeforeReset = 1004 Then
        GoTo vlookupFailedErrorBlock
    Else
        GoTo catchAllUnhandledErrors
    End If

End Sub

Converting JSON String to Dictionary Not List

You can use the following:

import json

 with open('<yourFile>.json', 'r') as JSON:
       json_dict = json.load(JSON)

 # Now you can use it like dictionary
 # For example:

 print(json_dict["username"])

Difference between SelectedItem, SelectedValue and SelectedValuePath

Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.

To be more specific if you literally want to retrieve Text of Selected Item then you can write:

ListBox1.SelectedItem.Text;

Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.

Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use

ListBox1.SelectedValue

Source

Change primary key column in SQL Server

Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

ALTER TABLE history ADD PRIMARY KEY (id)

ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name

with these:

ALTER TABLE history DROP CONSTRAINT pk_history

ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)

If you don't know what the name of the PK is, you can find it with the following query:

SELECT * 
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
 WHERE TABLE_NAME = 'history'

Left align block of equations

Try this:

\begin{flalign*}
    &|\vec a| = \sqrt{3^{2}+1^{2}} = \sqrt{10} & \\
    &|\vec b| = \sqrt{1^{2}+23^{2}} = \sqrt{530} &\\ 
    &\cos v = \frac{26}{\sqrt{10} \cdot \sqrt{530}} &\\
    &v = \cos^{-1} \left(\frac{26}{\sqrt{10} \cdot \sqrt{530}}\right) &\\
\end{flalign*}

The & sign separates two columns, so an & at the beginning of a line means that the line starts with a blank column.

jquery select option click handler

The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.

I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:

let blockChange = false;

$element.keydown(function (e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);

    // prevents select opening when enter is pressed
    if (keycode === 13) {
        e.preventDefault();
    }

    // lets the change event know that these keypresses are to be ignored
    if([38, 40].indexOf(keycode) > -1){
        blockChange = true;
    }

});

$element.keyup(function(e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);
    // handle enter press
    if(keycode === 13) {
        doSomething();
    }

});

$element.change(function(e) {

    // this effective handles the click only as preventDefault was used on enter
    if(!blockChange) {
        doSomething();
    }
    blockChange = false;

});

Send response to all clients except sender

For namespaces within rooms looping the list of clients in a room (similar to Nav's answer) is one of only two approaches I've found that will work. The other is to use exclude. E.G.

socket.on('message',function(data) {
    io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
}

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

Setting the height of a SELECT in IE

you can use a combination of font-size and line-height to force it to go larger, but obviously only in the situations where you need the font larger too

edit:

Example -> http://www.bse.co.nz EDIT: (this link is no longer relevant)

the select next to the big search box has the following css rules:

#navigation #search .locationDrop {
    font-size:2em;
    line-height:27px;
    display:block;
    float:left;
    height:27px;
    width:200px;
}

How to test if a file is a directory in a batch script?

A very simple way is to check if the child exists.

If a child does not have any child, the exist command will return false.

IF EXIST %1\. (
  echo %1 is a folder
) else (
  echo %1 is a file
)

You may have some false negative if you don't have sufficient access right (I have not tested it).

How to create Android Facebook Key Hash?

You can get all your fingerprints from https://console.developers.google.com/projectselector/apis/credentials
And use this Kotlin code to convert it to keyhash:

fun main(args: Array<String>) {
    listOf("<your_production_sha1_fingerprint>",
            "<your_debug1_sha1_fingerprint>",
            "<your_debug2_sha1_fingerprint>")
            .map { it.split(":") }
            .map { it.map { it.toInt(16).toByte() }.toByteArray() }
            .map { String(Base64.getEncoder().encode(it)) }
            .forEach { println(it) }
}

.NET Core vs Mono

This question is especially actual because yesterday Microsoft officially announced .NET Core 1.0 release. Assuming that Mono implements most of the standard .NET libraries, the difference between Mono and .NET core can be seen through the difference between .NET Framework and .NET Core:

  • APIs — .NET Core contains many of the same, but fewer, APIs as the .NET Framework, and with a different factoring (assembly names are
    different; type shape differs in key cases). These differences
    currently typically require changes to port source to .NET Core. .NET Core implements the .NET Standard Library API, which will grow to
    include more of the .NET Framework BCL APIs over time.
  • Subsystems — .NET Core implements a subset of the subsystems in the .NET Framework, with the goal of a simpler implementation and
    programming model. For example, Code Access Security (CAS) is not
    supported, while reflection is supported.

If you need to launch something quickly, go with Mono because it is currently (June 2016) more mature product, but if you are building a long-term website, I would suggest .NET Core. It is officially supported by Microsoft and the difference in supported APIs will probably disappear soon, taking into account the effort that Microsoft puts in the development of .NET Core.

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

Linq and Entity framework are included in .NET Core, so you are safe to take a shot.

Occurrences of substring in a string

I'm very surprised no one has mentioned this one liner. It's simple, concise and performs slightly better than str.split(target, -1).length-1

public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If you don't want to upgrade your tomcat, Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

It works for me http://www.zhoulujun.cn/zhoulujun/html/java/tomcat/2018_0508_8109.html

Confirm deletion in modal / dialog using Twitter Bootstrap?

http://bootboxjs.com/ - latest works with Bootstrap 3.0.0

The simplest possible example:

bootbox.alert("Hello world!"); 

From the site:

The library exposes three methods designed to mimic their native JavaScript equivalents. Their exact method signatures are flexible as each can take various parameters to customise labels and specify defaults, but they are most commonly called like so:

bootbox.alert(message, callback)
bootbox.prompt(message, callback)
bootbox.confirm(message, callback)

Here's a snippet of it in action (click "Run code snippet" below):

_x000D_
_x000D_
$(function() {_x000D_
  bootbox.alert("Hello world!");_x000D_
});
_x000D_
<!-- required includes -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- bootbox.js at 4.4.0 -->_x000D_
<script src="https://rawgit.com/makeusabrew/bootbox/f3a04a57877cab071738de558581fbc91812dce9/bootbox.js"></script>
_x000D_
_x000D_
_x000D_

Reading RFID with Android phones

NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.

You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.

I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.

If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.

What is the difference between supervised learning and unsupervised learning?

Supervised Learning is basically a technique in which the training data from which the machine learns is already labelled that is suppose a simple even odd number classifier where you have already classified the data during training . Therefore it uses "LABELLED" data.

Unsupervised learning on the contrary is a technique in which the machine by itself labels the data . Or you can say its the case when the machine learns by itself from scratch.

How to find the size of a table in SQL?

Here's a simple query, if you are just trying to find the largest tables.

  -- Find largest table partitions
 SELECT top 20 obj.name, LTRIM (STR ( sz.in_row_data_page_count * 8, 15, 0) + ' KB') as Size, * FROM sys.dm_db_partition_stats sz
inner join sys.objects obj on obj.object_id = sz.object_id
  order by sz.in_row_data_page_count desc

How to persist data in a dockerized postgres database using volumes

Strangely enough, the solution ended up being to change

volumes:
  - ./postgres-data:/var/lib/postgresql

to

volumes:
  - ./postgres-data:/var/lib/postgresql/data

Get selected option text with JavaScript

Try the below:

myNewFunction = function(id, index) {
    var selection = document.getElementById(id);
    alert(selection.options[index].innerHTML);
};

See here jsfiddle sample

How to detect a remote side socket close?

The isConnected method won't help, it will return true even if the remote side has closed the socket. Try this:

public class MyServer {
    public static final int PORT = 12345;
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
        Socket s = ss.accept();
        Thread.sleep(5000);
        ss.close();
        s.close();
    }
}

public class MyClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
        System.out.println(" connected: " + s.isConnected());
        Thread.sleep(10000);
        System.out.println(" connected: " + s.isConnected());
    }
}

Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.

The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException (broken pipe) will be thrown) on the associated Input/OutputStreams.

Insert an element at a specific index in a list and return the updated list

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

To know more about slice indexing, you can refer: Understanding slice notation.

Note: In Python 3.x, difference of performance between slice indexing and list.index(...) is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.


Alternative using list comprehension (but very slow in terms of performance):

As an alternative, it can be achieved using list comprehension with enumerate too. (But please don't do it this way. It is just for illustration):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

Performance comparison of all solutions

Here's the timeit comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.

Python 3.9.1

  1. My answer using sliced insertion - Fastest ( 2.25 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 5: 2.25 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.33 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 5: 2.33 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    50000 loops, best of 5: 5.01 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 135 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    2000 loops, best of 5: 135 µsec per loop
    

Python 2.7.16

  1. My answer using sliced insertion - Fastest (2.09 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 3: 2.09 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.36 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 3: 2.36 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    100000 loops, best of 3: 4.44 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 103 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    10000 loops, best of 3: 103 µsec per loop
    

C# using streams

A stream is an object used to transfer data. There is a generic stream class System.IO.Stream, from which all other stream classes in .NET are derived. The Stream class deals with bytes.

The concrete stream classes are used to deal with other types of data than bytes. For example:

  • The FileStream class is used when the outside source is a file
  • MemoryStream is used to store data in memory
  • System.Net.Sockets.NetworkStream handles network data

Reader/writer streams such as StreamReader and StreamWriter are not streams - they are not derived from System.IO.Stream, they are designed to help to write and read data from and to stream!

Display Back Arrow on Toolbar

This worked perfectly

public class BackButton extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_box);
        Toolbar chatbox_toolbar=(Toolbar)findViewById(R.id.chat_box_toolbar);
        chatbox_toolbar.setTitle("Demo Back Button");
        chatbox_toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        setSupportActionBar(chatbox_toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        chatbox_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Define Back Button Function
            }
        });
    }
}

The name 'ConfigurationManager' does not exist in the current context

If this code is on a separate project, like a library project. Don't forgeet to add reference to system.configuration.

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Flattening a shallow list in Python

If each item in the list is a string (and any strings inside those strings use " " rather than ' '), you can use regular expressions (re module)

>>> flattener = re.compile("\'.*?\'")
>>> flattener
<_sre.SRE_Pattern object at 0x10d439ca8>
>>> stred = str(in_list)
>>> outed = flattener.findall(stred)

The above code converts in_list into a string, uses the regex to find all the substrings within quotes (i.e. each item of the list) and spits them out as a list.

Is it possible to get element from HashMap by its position?

HashMaps do not preserve ordering:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Take a look at LinkedHashMap, which guarantees a predictable iteration order.

How to convert XML to java.util.Map and vice versa

I used the approach with the custom converter:

public static class MapEntryConverter implements Converter {

    public boolean canConvert(Class clazz) {
        return AbstractMap.class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {

        AbstractMap map = (AbstractMap) value;
        for (Object obj : map.entrySet()) {
            Entry entry = (Entry) obj;
            writer.startNode(entry.getKey().toString());
            context.convertAnother(entry.getValue());
            writer.endNode();
        }
    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        // dunno, read manual and do it yourself ;)
    }

}

But i changed the the serialization of the maps value to delegate to the MarshallingContext. This should improve the solution to work for composite map values and nested maps as well.

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Example query: SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

Can Mockito stub a method without regard to the argument?

Use like this:

when(
  fooDao.getBar(
    Matchers.<Bazoo>any()
  )
).thenReturn(myFoo);

Before you need to import Mockito.Matchers

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

Angular2 - Focusing a textbox on component load

I didn't have much luck with many of these solutions on all browsers. This is the solution that worked for me.

For router changes:

router.events.subscribe((val) => {
    setTimeout(() => {
        if (this.searchElement) {
            this.searchElement.nativeElement.focus();
        }
    }, 1);
})

Then ngAfterViewInit() for the onload scenario.

How to decode HTML entities using jQuery?

Security note: using this answer (preserved in its original form below) may introduce an XSS vulnerability into your application. You should not use this answer. Read lucascaro's answer for an explanation of the vulnerabilities in this answer, and use the approach from either that answer or Mark Amery's answer instead.

Actually, try

_x000D_
_x000D_
var encodedStr = "This is fun &amp; stuff";
var decoded = $("<div/>").html(encodedStr).text();
console.log(decoded);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div/>
_x000D_
_x000D_
_x000D_

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

Try granting permission to the NETWORK SERVICE user.

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Your local port is using by another app. I faced the same problem! You can try the following step:

  1. Go to command line and run it as administrator!

  2. Type:

    netstat -ano | find ":5000"
    => TCP    0.0.0.0:5000           0.0.0.0:0              LISTENING       4032
       TCP    [::]:5000              [::]:0                 LISTENING       4032
    
  3. Type:

    TASKKILL /F /PID 4032
    

=> SUCCESS: The process with PID 4032 has been terminated.

Note: My 5000 local port was listing by PID 4032. You should give yours!

Check OS version in Swift?

Swift 5

func run() {
    let version = OperatingSystemVersion(majorVersion: 13, minorVersion: 0, patchVersion: 0)
    if ProcessInfo.processInfo.isOperatingSystemAtLeast(version) {
        runNewCode()
    } else {
        runLegacyCode()
    }
}

func runNewCode() {
    guard #available(iOS 13.0, *) else {
        fatalError()
    }
    // do new stuff
}

func runLegacyCode() {
    // do old stuff
}

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

Select fonts by specifying the weights you need on load

Font-families consist of several distinct fonts

For example, extra-bold will make the font look quite different in say, Photoshop, because you're selecting a different font. The same applies to italic font, which can look very different indeed. Setting font-weight:800 or font-style:italic may result in just a best effort of the web browser to fatten or slant the normal font in the family.

Even though you're loading a font-family, you must specify the weights and styles you need for some web browsers to let you select a different font in the family with font-weight and font-style.

Example

This example specifies the light, normal, normal italic, bold, and extra-bold fonts in the font family Open Sans:

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <link rel="stylesheet"_x000D_
          href="https://fonts.googleapis.com/css?family=Open+Sans:100,400,400i,600,800">_x000D_
    <style>_x000D_
      body {_x000D_
        font-family: 'Open Sans', serif;_x000D_
        font-size: 48px;_x000D_
      }_x000D_
    </style>_x000D_
  </head>_x000D_
  <body>    _x000D_
    <div style="font-weight:400">Didn't work with all the fonts</div>_x000D_
   <div style="font-weight:600">Didn't work with all the fonts</div>_x000D_
   <div style="font-weight:800">Didn't work with all the fonts</div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference

(Quora warning, please remove if not allowed.)

https://www.quora.com/How-do-I-make-Open-Sans-extra-bold-once-imported-from-Google-Fonts

Testing

Tested working in Firefox 66.0.3 on Mac and Firefox 36.0.1 in Windows.

Non-Google fonts

Other fonts must be uploaded to the server, style and weight specified by their individual names.

System fonts

Assume nothing, font-wise, about what device is visiting your website or what fonts are installed on its OS.

(You may use the fall-backs of serif and sans-serif, but you will get the font mapped to these by the individual web browser version used, within the fonts available in the OS version it's running under, and not what you designed.)

Testing should be done with the font temporarily uninstalled from your system, to be sure that your design is in effect.

Read file-contents into a string in C++

The most efficient, but not the C++ way would be:

   FILE* f = fopen(filename, "r");

   // Determine file size
   fseek(f, 0, SEEK_END);
   size_t size = ftell(f);

   char* where = new char[size];

   rewind(f);
   fread(where, sizeof(char), size, f);

   delete[] where;

#EDIT - 2

Just tested the std::filebuf variant also. Looks like it can be called the best C++ approach, even though it's not quite a C++ approach, but more a wrapper. Anyway, here is the chunk of code that works almost as fast as plain C does.

   std::ifstream file(filename, std::ios::binary);
   std::streambuf* raw_buffer = file.rdbuf();

   char* block = new char[size];
   raw_buffer->sgetn(block, size);
   delete[] block;

I've done a quick benchmark here and the results are following. Test was done on reading a 65536K binary file with appropriate (std::ios:binary and rb) modes.

[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN      ] IO.C_Kotti
[       OK ] IO.C_Kotti (78 ms)
[ RUN      ] IO.CPP_Nikko
[       OK ] IO.CPP_Nikko (106 ms)
[ RUN      ] IO.CPP_Beckmann
[       OK ] IO.CPP_Beckmann (1891 ms)
[ RUN      ] IO.CPP_Neil
[       OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)

[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[  PASSED  ] 4 tests.

PowerShell says "execution of scripts is disabled on this system."

Open the PowerShell window as an Administrator. It will work.

BitBucket - download source as ZIP

In case you want to download the repo from your shell/terminal it should work like this:

wget https://user:[email protected]/user-name/repo-name/get/master.tar.bz2

or whatever download URL you might have.

Please make sure the user:password are both URL-encoded. So for instance if your username contains the @ symbol then replace it with %40.

object==null or null==object?

As others have said, it's a habit learned from C to avoid typos - although even in C I'd expect decent compilers at high enough warning levels to give a warning. As Chandru says, comparing against null in Java in this way would only cause problems if you were using a variable of type Boolean (which you're not in the sample code). I'd say that's a pretty rare situation, and not one for which it's worth changing the way you write code everywhere else. (I wouldn't bother reversing the operands even in this case; if I'm thinking clearly enough to consider reversing them, I'm sure I can count the equals signs.)

What hasn't been mentioned is that many people (myself certainly included) find the if (variable == constant) form to be more readable - it's a more natural way of expressing yourself. This is a reason not to blindly copy a convention from C. You should always question practices (as you're doing here :) before assuming that what may be useful in one environment is useful in another.

Printing without newline (print 'a',) prints a space, how to remove?

You can suppress the space by printing an empty string to stdout between the print statements.

>>> import sys
>>> for i in range(20):
...   print 'a',
...   sys.stdout.write('')
... 
aaaaaaaaaaaaaaaaaaaa

However, a cleaner solution is to first build the entire string you'd like to print and then output it with a single print statement.

AngularJS ng-if with multiple conditions

OR operator:

<div ng-repeat="k in items">
    <div ng-if="k || 'a' or k == 'b'">
        <!-- SOME CONTENT -->
    </div>
</div>

Even though it is simple enough to read, I hope as a developer you are use better names than 'a' 'k' 'b' etc..

For Example:

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin || group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

Another OR example

<p ng-if="group.title != 'Dispatcher News' or group.title != 'Coordinator News'" style="padding: 5px;">No links in group.</p>

AND operator (For those stumbling across this stackoverflow answer looking for an AND instead of OR condition)

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin && group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

Make an image width 100% of parent div, but not bigger than its own width

Setting a width of 100% is the full width of the div it's in, not the original full-sized image. There is no way to do that without JavaScript or some other scripting language that can measure the image. If you can have a fixed width or fixed height of the div (like 200px wide) then it shouldn't be too hard to give the image a range to fill. But if you put a 20x20 pixel image in a 200x300 pixel box it will still be distorted.

Display PDF file inside my android application

Highly recommend you check out PDF.js which is able to render PDF documents in a standard a WebView component.

Also see https://github.com/loosemoose/androidpdf for a sample implementation of this.

Jenkins - how to build a specific branch

I don't think you can both within the same jenkins job, what you need to do is to configure a new jenkins job which will have access to your github to retrieve branches and then you can choose which one to manually build.

Just mark it as a parameterized build, specify a name, and a parameter configured as git parameter

enter image description here

and now you can configure git options:

enter image description here

How to decode jwt token in javascript without using a library?

As "window" object is not present in nodejs environment, we could use the following lines of code :

let base64Url = token.split('.')[1]; // token you get
let base64 = base64Url.replace('-', '+').replace('_', '/');
let decodedData = JSON.parse(Buffer.from(base64, 'base64').toString('binary'));

It's working for me perfectly. Hope it helps.

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

In order of activity, demos/examples available, and simplicity:

Related:

Better way of getting time in milliseconds in javascript?

Try Date.now().

The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.

sql searching multiple words in a string

Select * from table where 
  columnname like'%David%' and 
  columnname like '%Moses%' and columnname like'%Robi%' 

Manually raising (throwing) an exception in Python

For the common case where you need to throw an exception in response to some unexpected conditions, and that you never intend to catch, but simply to fail fast to enable you to debug from there if it ever happens — the most logical one seems to be AssertionError:

if 0 < distance <= RADIUS:
    #Do something.
elif RADIUS < distance:
    #Do something.
else:
    raise AssertionError("Unexpected value of 'distance'!", distance)

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

Determine SQL Server Database Size

According to SQL2000 help, sp_spaceused includes data and indexes.

This script should do:

CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18), 
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))

EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''
-- SELECT * FROM #t ORDER BY name
-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY name
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #t
DROP TABLE #t

How to format Joda-Time DateTime to only mm/dd/yyyy?

Please try to this one

public void Method(Datetime time)
{
    time.toString("yyyy-MM-dd'T'HH:mm:ss"));
}

Determine whether an array contains a value

Using array .map function that executes a function for every value in an array seems cleanest to me.

Ref: Array.prototype.map()

This method can work well both for simple arrays and for arrays of objects where you need to see if a key/value exists in an array of objects.

function inArray(myArray,myValue){
    var inArray = false;
    myArray.map(function(key){
        if (key === myValue){
            inArray=true;
        }
    });
    return inArray;
};

var anArray = [2,4,6,8]
console.log(inArray(anArray, 8)); // returns true
console.log(inArray(anArray, 1)); // returns false

function inArrayOfObjects(myArray,myValue,objElement){
    var inArray = false;
    myArray.map(function(arrayObj){
        if (arrayObj[objElement] === myValue) {
            inArray=true;
        }
    });
    return inArray;
};

var objArray = [{id:4,value:'foo'},{id:5,value:'bar'}]
console.log(inArrayOfObjects(objArray, 4, 'id')); // returns true
console.log(inArrayOfObjects(objArray, 'bar', 'value')); // returns true
console.log(inArrayOfObjects(objArray, 1, 'id')); // returns false

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

Inline onclick JavaScript variable

There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider

JS

var myvar=15;
function init(){
    document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;

HTML

<input id="EditBanner" type="button"  value="Edit Image" />

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

check below link in which you can download suitable AjaxControlToolkit which suits your .NET version.

http://ajaxcontroltoolkit.codeplex.com/releases/view/43475

AjaxControlToolkit.Binary.NET4.zip - used for .NET 4.0

AjaxControlToolkit.Binary.NET35.zip - used for .NET 3.5

How can you get the active users connected to a postgreSQL database via SQL?

(question) Don't you get that info in

select * from pg_user;

or using the view pg_stat_activity:

select * from pg_stat_activity;

Added:

the view says:

One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.

can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...

something like that.

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

How do I create a URL shortener?

This is my initial thoughts, and more thinking can be done, or some simulation can be made to see if it works well or any improvement is needed:

My answer is to remember the long URL in the database, and use the ID 0 to 9999999999999999 (or however large the number is needed).

But the ID 0 to 9999999999999999 can be an issue, because

  1. it can be shorter if we use hexadecimal, or even base62 or base64. (base64 just like YouTube using A-Z a-z 0-9 _ and -)
  2. if it increases from 0 to 9999999999999999 uniformly, then hackers can visit them in that order and know what URLs people are sending each other, so it can be a privacy issue

We can do this:

  1. have one server allocate 0 to 999 to one server, Server A, so now Server A has 1000 of such IDs. So if there are 20 or 200 servers constantly wanting new IDs, it doesn't have to keep asking for each new ID, but rather asking once for 1000 IDs
  2. for the ID 1, for example, reverse the bits. So 000...00000001 becomes 10000...000, so that when converted to base64, it will be non-uniformly increasing IDs each time.
  3. use XOR to flip the bits for the final IDs. For example, XOR with 0xD5AA96...2373 (like a secret key), and the some bits will be flipped. (whenever the secret key has the 1 bit on, it will flip the bit of the ID). This will make the IDs even harder to guess and appear more random

Following this scheme, the single server that allocates the IDs can form the IDs, and so can the 20 or 200 servers requesting the allocation of IDs. The allocating server has to use a lock / semaphore to prevent two requesting servers from getting the same batch (or if it is accepting one connection at a time, this already solves the problem). So we don't want the line (queue) to be too long for waiting to get an allocation. So that's why allocating 1000 or 10000 at a time can solve the issue.

How do I post button value to PHP?

Change the type to submit and give it a name (and remove the useless onclick and flat out the 90's style uppercased tags/attributes).

<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />
...

The value will be available by $_POST['foo'] (if the parent <form> has a method="post").

How to get UTC timestamp in Ruby?

What good is a timestamp with its granularity given in seconds? I find it much more practical working with Time.now.to_f. Heck, you may even throw a to_s.sub('.','') to get rid of the decimal point, or perform a typecast like this: Integer(1e6*Time.now.to_f).

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

How do I plot list of tuples in Python?

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2))
>>> plt.show()

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()

which would give you

enter image description here

Avoiding "resource is out of sync with the filesystem"

If you are a regular Eclipse user than you might have got this error many times. The error simply says, “you’ve made changes in files in your workspace from outside eclipse”. The simplest solution would be to select the project and press F5 (Right click -> Refresh).

if you need more explanation you can read from this web site

How to debug in Django, the good way?

From my own experience , there are two way:

  1. use ipdb,which is a enhanced debugger likes pdb.

    import ipdb;ipdb.set_trace() or breakpoint() (from python3.7)

  2. use django shell ,just use the command below. This is very helpfull when you are developing a new view.

    python manage.py shell

How to import a SQL Server .bak file into MySQL?

I highly doubt it. You might want to use DTS/SSIS to do this as Levi says. One think that you might want to do is start the process without actually importing the data. Just do enough to get the basic table structures together. Then you are going to want to change around the resulting table structure, because whatever structure tat will likely be created will be shaky at best.

You might also have to take this a step further and create a staging area that takes in all the data first n a string (varchar) form. Then you can create a script that does validation and conversion to get it into the "real" database, because the two databases don't always work well together, especially when dealing with dates.

Retrieve Button value with jQuery

try this for your button:

<input type="button" class="my_button" name="buttonName" value="buttonValue" />

Can I mask an input text in a bat file?

Up to XP and Server 2003, you can make use of another included tool (VBScript) - the following two scripts do the job you want.

First, getpwd.cmd:

@echo off
<nul: set /p passwd=Password: 
for /f "delims=" %%i in ('cscript /nologo getpwd.vbs') do set passwd=%%i
echo.

Then, getpwd.vbs:

Set oScriptPW = CreateObject("ScriptPW.Password")
strPassword = oScriptPW.GetPassword()
Wscript.StdOut.WriteLine strPassword

The getpwd.vbs simply uses the password object to input the password from the user and then print it to standard output (the next paragraph will explain why that doesn't show up in the terminal).

The getpwd.cmd command script is a bit trickier but it basically works as follows.

The effect of the "<nul: set /p passwd=Password: " command is to output the prompt with no trailing newline character - it's a sneaky way to emulate the "echo -n" command from the bash shell. It sets passwd to an empty string as an irrelevant side effect and doesn't wait for input since it's taking its input from the nul: device.

The "for /f "delims=" %%i in ('cscript /nologo getpwd.vbs') do set passwd=%%i" statement is the trickiest bit. It runs the VBScript with no Microsoft "advertising", so that the only line output is the password (from the VBscript "Wscript.StdOut.WriteLine strPassword".

Setting the delimiters to nothing is required to capture an entire input line with spaces, otherwise you just get the first word. The "for ... do set ..." bit sets passwd to be the actual password output from the VBScript.

Then we echo a blank line (to terminate the "Password: " line) and the password will be in the passwd environment variable after the code has run.


Now, as mentioned, scriptpw.dll is available only up to XP/2003. In order to rectify this, you can simply copy the scriptpw.dll file from the Windows\System32 folder of an XP/2003 system to the Winnt\System32 or Windows\System32 folder on your own system. Once the DLL has been copied, you will need to register it by running:

regsvr32 scriptpw.dll

To successfully register the DLL on Vista and later, you will need administrator privileges. I haven't examined the legality of such a move so cave lector.


If you're not overly keen on trying to track down and register older DLL files (for convenience or legal reasons), there is another way. Later versions of Windows (the ones that don't have the required DLL) should have Powershell available to you.

And, in fact, you really should consider upgrading your scripts to use it fully since it's a much more capable scripting language than cmd.exe. However, if you want to keep the bulk of your code as cmd.exe scripts (such as if you have a lot of code that you don't want to convert), you can use the same trick.

First, modify the cmd script so it calls Powershell rather than CScript:

@echo off
for /f "delims=" %%i in ('powershell -file getpwd.ps1') do set passwd=%%i

The Powershell script is equally simple:

$password = Read-Host "Enter password" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto($password)
echo $password

although with some marshalling to get the actual password text.

Remember that, to run local unsigned Powershell scripts on your machine, you may need to modify the execution policy from the (draconian, though very safe) default, with something like:

set-executionpolicy remotesigned

from within Powershell itself.

Linking a qtDesigner .ui file to python/pyqt?

You can also use uic in PyQt5 with the following code.

from PyQt5 import uic, QtWidgets
import sys

class Ui(QtWidgets.QDialog):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('SomeUi.ui', self)
        self.show()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Ui()
    sys.exit(app.exec_())

Day Name from Date in JS

use the Date.toLocaleString() method :

new Date(dateString).toLocaleString('en-us', {weekday:'long'})

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get Selected Item Using Checkbox in Listview

I had similar problem. Provided xml sample is put as single ListViewItem, and i couldn't click on Item itself, but checkbox was workng.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/source_container"
    >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/menu_source_icon"
        android:background="@drawable/bla"
        android:layout_margin="5dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/menu_source_name"
        android:text="Test"
        android:textScaleX="1.5"
        android:textSize="20dp"
        android:padding="8dp"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:textColor="@color/source_text_color"/>
    <CheckBox
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:id="@+id/menu_source_check_box"/>

</LinearLayout>

Solution: add attribute

android:focusable="false"

to CheckBox control.

MySQL connection not working: 2002 No such file or directory

I encountered this problem too, then i modified 'localhost' to '127.0.0.1',it works.

Post order traversal of binary tree without recursion

The simplest solution, it may look like not the best answer but it is easy to understand. And I believe if you have understood the solution then you can modify it to make the best possible solution

// using two stacks

public List<Integer> postorderTraversal(TreeNode root){

 Stack<TreeNode> st=new Stack<>();
 Stack<TreeNode> st2=new Stack<>();
 ArrayList<Integer> al = new ArrayList<Integer>(); 

    if(root==null)
        return al;

 st.push(root);  //push the root to 1st stack

 while(!st.isEmpty())
 {
     TreeNode curr=st.pop();

     st2.push(curr);

     if(curr.left!=null)
        st.push(curr.left);
     if(curr.right!=null)
         st.push(curr.right);

 }

while(!st2.isEmpty())
    al.add(st2.pop().val);

//this ArrayList contains the postorder traversal

  return al;  
}

Boolean vs tinyint(1) for boolean values in MySQL

My experience when using Dapper to connect to MySQL is that it does matter. I changed a non nullable bit(1) to a nullable tinyint(1) by using the following script:

ALTER TABLE TableName MODIFY Setting BOOLEAN null;

Then Dapper started throwing Exceptions. I tried to look at the difference before and after the script. And noticed the bit(1) had changed to tinyint(1).

I then ran:

ALTER TABLE TableName CHANGE COLUMN Setting Setting BIT(1) NULL DEFAULT NULL;

Which solved the problem.

Blank HTML SELECT without blank item in dropdown list

You can't. They simply do not work that way. A drop down menu must have one of its options selected at all times.

You could (although I don't recommend it) watch for a change event and then use JS to delete the first option if it is blank.

Excel 2007 - Compare 2 columns, find matching values

VLOOKUP deosnt work for String literals

How do I create a master branch in a bare Git repository?

A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.

$ mkdir repo
$ cd repo
$ git init
Initialized empty Git repository in /home/me/repo/.git/
$ git branch
$ touch foo
$ git add foo
$ git commit -m "new file"
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
$ git branch
* master

ImportError: No module named 'Tkinter'

Firstly you should test your python idle to see if you have tkinter:

import tkinter

tkinter._test()

Trying typing it, copy paste doesn't work.

So after 20 hours of trying every way that recommended on those websites figured out that you can't use "tkinter.py" or any other file name that contains "tkinter..etc.py". If you have the same problem, just change the file name.

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

Declaring abstract method in TypeScript

If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:

/**
 * The interface defines all abstract methods and extends the concrete base class
 */
interface IAnimal extends Animal {
    speak() : void;
}

/**
 * The abstract base class only defines concrete methods & properties.
 */
class Animal {

    private _impl : IAnimal;

    public name : string;

    /**
     * Here comes the clever part: by letting the constructor take an 
     * implementation of IAnimal as argument Animal cannot be instantiated
     * without a valid implementation of the abstract methods.
     */
    constructor(impl : IAnimal, name : string) {
        this.name = name;
        this._impl = impl;

        // The `impl` object can be used to delegate functionality to the
        // implementation class.
        console.log(this.name + " is born!");
        this._impl.speak();
    }
}

class Dog extends Animal implements IAnimal {
    constructor(name : string) {
        // The child class simply passes itself to Animal
        super(this, name);
    }

    public speak() {
        console.log("bark");
    }
}

var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"

Since the Animal class requires an implementation of IAnimal it's impossible to construct an object of type Animal without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal, not Animal. E.g.:

//This works
function letTheIAnimalSpeak(animal: IAnimal) {
    console.log(animal.name + " says:");
    animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
    console.log(animal.name + " says:");
    animal.speak();
}

The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.

How do I view the list of functions a Linux shared library is exporting?

On a MAC, you need to use nm *.o | c++filt, as there is no -C option in nm.

ArrayList of int array in java

For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.

    ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
    while(n > 0)
    {
        int d = scan.nextInt();
       Integer temp[] = new Integer[d];
        for (int i = 0 ; i < d ; i++)
        {
            int t = scan.nextInt();
            temp[i]=Integer.valueOf(t);
        }
        arrayList.add(temp);
        n--;
    }//n is the size of the ArrayList that has been taken as a user input & d is the size 
    //of each individual array.

     //to print something  out from this ArrayList, we take in two 
    // values,index and index1 which is the number of the line we want and 
    // and the position of the element within that line (since the question
    // followed a 1-based numbering scheme, I did not change it here)

    System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));

Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

You have a typo in your xml; it should be:

android:textColor="@color/text_color"

that's "@color" without the 's'.

How to do Base64 encoding in node.js?

Buffers can be used for taking a string or piece of data and doing base64 encoding of the result. For example:

> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World

Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available toString and Buffer constructor encodings are as follows:

'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.

'utf8' - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.

'ucs2' - 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).

'base64' - Base64 string encoding.

'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

Go back button in a page

You can either use:

<button onclick="window.history.back()">Back</button>

or..

<button onclick="window.history.go(-1)">Back</button>

The difference, of course, is back() only goes back 1 page but go() goes back/forward the number of pages you pass as a parameter, relative to your current page.

jQuery if div contains this text, replace that part of the text

If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:

<div class="text_div">
    This div <span>contains</span> some text.
</div>

You can then easily change its contents with jQuery:

$('.text_div > span').text('hello everyone');

If you can't wrap it in a span tag, you could use regular expressions.

How do you dynamically allocate a matrix?

The other answer describing arrays of arrays are correct.
BUT if you are planning of doing a anything mathematical with the arrays - or need something special like sparse matrices you should look at one of the many maths libs like TNT before re-inventing too many wheels

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

I came across this question when trying to check if a file existed on an FTP site or not. If the file doesn't exist there will be an error when trying to check its timestamp. But I want to make sure the error is not something else, by checking its type.

The Response property on WebException will be of type FtpWebResponse on which you can check its StatusCode property to see which FTP error you have.

Here's the code I ended up with:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

This is an issue if you are using 2008 management studio tools to connect to a SQL 2012 instance.

I experience this a lot if I am working on one server with SQL 2008, and trying to quickly query another server that is running SQL 2012.

I normally keep my personal workstation on the latest version of management studio (2012 in this case), and am able to administer all servers from there.

TransactionRequiredException Executing an update/delete query

I have also faced same issue when I work with Hibernate and Spring Jpa Data Repository. I forgot to place @Transactional on spring data repository method.

Its working for me after annotating with @Transactional.

Make the current Git branch a master branch

The problem with the other two answers is that the new master doesn't have the old master as an ancestor, so when you push it, everyone else will get messed up. This is what you want to do:

git checkout better_branch
git merge --strategy=ours master    # keep the content of this branch, but record a merge
git checkout master
git merge better_branch             # fast-forward master up to the merge

If you want your history to be a little clearer, I'd recommend adding some information to the merge commit message to make it clear what you've done. Change the second line to:

git merge --strategy=ours --no-commit master
git commit          # add information to the template merge message

Convert Date/Time for given Timezone - java

A quick way is :

String dateText ="Thu, 02 Jul 2015 21:51:46";
long hours = -5; // time difference between places

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(E, dd MMM yyyy HH:mm:ss, Locale.ENGLISH);     
LocalDateTime date = LocalDateTime.parse(dateText, formatter);        
date = date.with(date.plusHours(hours));

System.out.println("NEW DATE: "+date);

Output

NEW DATE: 2015-07-02T16:51:46

Javascript: Setting location.href versus location

Even if both work, I would use the latter. location is an object, and assigning a string to an object doesn't bode well for readability or maintenance.

How to get all of the IDs with jQuery?

Not a real array, but objs are all associative arrays in javascript.

I chose not to use a real array with [] and [].push because technically, you can have multiple ID's on a page even though that is incorrect to do so. So just another option in case some html has duplicated ID's

$(function() {

       var oArr = {};
       $("*[id]").each(function() {
           var id = $(this).attr('id');
           if (!oArr[id]) oArr[id] = true;
       });

       for (var prop in oArr)
           alert(prop);

   });

How to add default value for html <textarea>?

A few notes and clarifications:

  • placeholder='' inserts your text, but it is greyed out (in a tool-tip style format) and the moment the field is clicked, your text is replaced by an empty text field.

  • value='' is not a <textarea> attribute, and only works for <input> tags, ie, <input type='text'>, etc. I don't know why the creators of HTML5 decided not to incorporate that, but that's the way it is for now.

  • The best method for inserting text into <textarea> elements has been outlined correctly here as: <textarea> Desired text to be inserted into the field upon page load </textarea> When the user clicks the field, they can edit the text and it remains in the field (unlike placeholder='').

  • Note: If you insert text between the <textarea> and </textarea> tags, you cannot use placeholder='' as it will be overwritten by your inserted text.

Truncate (not round off) decimal numbers in javascript

I'm a bit confused as to why there are so many different answers to such a fundamentally simple question; there are only two approaches which I saw which seemed to be worth looking at. I did a quick benchmark to see the speed difference using https://jsbench.me/.

This is the solution which is currently (9/26/2020) flagged as the answer:

_x000D_
_x000D_
function truncate(n, digits) {
    var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
        m = n.toString().match(re);
    return m ? parseFloat(m[1]) : n.valueOf();
};

[   truncate(5.467,2),
    truncate(985.943,2),
    truncate(17.56,2),
    truncate(0, 1),
    truncate(1.11, 1) + 22];
_x000D_
_x000D_
_x000D_

However, this is doing string and regex stuff, which is usually not very efficient, and there is a Math.trunc function which does exactly what the OP wants just with no decimals. Therefore, you can easily use that plus a little extra arithmetic to get the same thing.

Here is another solution I found on this thread, which is the one I would use:

_x000D_
_x000D_
function truncate(n, digits) {
    var step = Math.pow(10, digits || 0);
    var temp = Math.trunc(step * n);

    return temp / step;
}

[   truncate(5.467,2),
    truncate(985.943,2),
    truncate(17.56,2),
    truncate(0, 1),
    truncate(1.11, 1) + 22];
    
_x000D_
_x000D_
_x000D_

The first method is "99.92% slower" than the second, so the second is definitely the one I would recommend using.

Okay, back to finding other ways to avoid work...

screenshot of the benchmark

How to generate xsd from wsdl

You can use SoapUI: http://www.soapui.org/ This is a generally handy program. Make a new project, connect to the WSDL link, then right click on the project and say "Show interface viewer". Under "Schemas" on the left you can see the XSD.

SoapUI can do many things though!

MySQL compare DATE string with string from DATETIME field

Use the following:

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'

Just for reference I have a 2 million record table, I ran a similar query. Salils answer took 4.48 seconds, the above took 2.25 seconds.

So if the table is BIG I would suggest this rather.

Error "can't use subversion command line client : svn" when opening android project checked out from svn

i was also getting the same Error, if you are using TortoiseSVN-1.9.5 just do two step Process 1:Click on TSVN.exe tool and 2:Select there on Second Window the Command line for Save on Local Drive with giving the path 3:Click ok Now Restart You Android Studio/IntelliJ

What process is listening on a certain port on Solaris?

netstat on Solaris will not tell you this, nor will older versions of lsof, but if you download and build/install a newer version of lsof, this can tell you that.

$ lsof -v
lsof version information:
    revision: 4.85
    latest revision: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/
    latest FAQ: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/FAQ
    latest man page: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/lsof_man
    configuration info: 64 bit kernel
    constructed: Fri Mar 7 10:32:54 GMT 2014
    constructed by and on: user@hostname
    compiler: gcc
    compiler version: 3.4.3 (csl-sol210-3_4-branch+sol_rpath)
    8<- - - - ***SNIP*** - - -

With this you can use the -i option:

$ lsof -i:22
COMMAND   PID     USER   FD   TYPE             DEVICE   SIZE/OFF NODE NAME
sshd      521     root    3u  IPv6 0xffffffff89c67580        0t0  TCP *:ssh (LISTEN)
sshd     5090     root    3u  IPv6 0xffffffffa8668580   0t322598  TCP host.domain.com:ssh->21.43.65.87:52364 (ESTABLISHED)
sshd     5091   johngh    4u  IPv6 0xffffffffa8668580   0t322598  TCP host.domain.com:ssh->21.43.65.87:52364 (ESTABLISHED)

Which shows you exactly what you're asking for.

I had a problem yesterday with a crashed Jetty (Java) process, which only left 2 files in its /proc/[PID] directory (psinfo & usage).

pfiles failed to find the process (because the date it needed was not there)

lsof found it for me.

What is a None value?

largest=none
smallest =none 
While True :
          num =raw_input ('enter a number ') 
          if num =="done ": break 
          try :
           inp =int (inp) 
          except:
              Print'Invalid input' 
           if largest is none :
               largest=inp
           elif inp>largest:
                largest =none 
           print 'maximum', largest

          if smallest is none:
               smallest =none
          elif inp<smallest :
               smallest =inp
          print 'minimum', smallest 

print 'maximum, minimum, largest, smallest 

Sass Variable in CSS calc() function

Try this:

@mixin heightBox($body_padding){
   height: calc(100% - $body_padding);
}

body{
   @include heightBox(100% - 25%);
   box-sizing: border-box
   padding:10px;
}

Flexbox: center horizontally and vertically

diplay: flex; for it's container and margin:auto; for it's item works perfect.

NOTE: You have to setup the width and height to see the effect.

_x000D_
_x000D_
#container{_x000D_
  width: 100%; /*width needs to be setup*/_x000D_
  height: 150px; /*height needs to be setup*/_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.item{_x000D_
  margin: auto; /*These will make the item in center*/_x000D_
  background-color: #CCC;_x000D_
}
_x000D_
<div id="container">_x000D_
   <div class="item">CENTER</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get object size in memory?

In debug mode

load SOS

and execute dumpheap command.

Can't connect to MySQL server on 'localhost' (10061) after Installation

this issue is very to solve by windows server users

  1. go to this path C:\Program Files\MySQL\MySQL Server 5.1\bin

  2. run this tool "MySQLInstanceConfig.exe"

and config the instatnce again and problem solved

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

Get height and width of a layout programmatically

I had same issue but didn't want to draw on screen before measuring so I used this method of measuring the view before trying to get the height and width.

Example of use:

layoutView(view);
int height = view.getHeight();

//...

void layoutView(View view) {
    view.setDrawingCacheEnabled(true);
    int wrapContentSpec = 
        MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    view.measure(wrapContentSpec, wrapContentSpec);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}

Post-increment and pre-increment within a 'for' loop produce same output

There is a difference if:

int main()
{
  for(int i(0); i<2; printf("i = post increment in loop %d\n", i++))
  {
    cout << "inside post incement = " << i << endl;
  }


  for(int i(0); i<2; printf("i = pre increment in loop %d\n",++i))
  {
    cout << "inside pre incement = " << i << endl;
  }

  return 0;
}

The result:

inside post incement = 0

i = post increment in loop 0

inside post incement = 1

i = post increment in loop 1

The second for loop:

inside pre incement = 0

i = pre increment in loop 1

inside pre incement = 1

i = pre increment in loop 2

What's the fastest way to convert String to Number in JavaScript?

Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string. You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code. read the comments to understand better how the conversion is done.

// Here Im creating my variable as a string
var str = "258";


// here im printing the string variable: str
console.log ( str );


// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);


// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);

Detect if a jQuery UI dialog box is open

Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:

if ($('#elem').is(':visible')) { 
  // do something
}

You should set visibility in your CSS first though, using simply:

#elem { display: none; }

ASP.Net MVC: Calling a method from a view

This is how you call an instance method on the Controller:

@{
  ((HomeController)this.ViewContext.Controller).Method1();
}

This is how you call a static method in any class

@{
    SomeClass.Method();
}

This will work assuming the method is public and visible to the view.

javascript toISOString() ignores timezone offset

Moment js solution to this is

var d = new Date(new Date().setHours(0,0,0,0));
m.add(m.utcOffset(), 'm')
m.toDate().toISOString()
// output "2019-07-18T00:00:00.000Z"

Utility of HTTP header "Content-Type: application/force-download" for mobile?

To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type

$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php

R - argument is of length zero in if statement

The argument is of length zero takes places when you get an output as an integer of length 0 and not a NULL output.i.e., integer(0).

You can further verify my point by finding the class of your output- >class(output) "integer"

Android ADB commands to get the device properties

From Linux Terminal:

adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"

From Windows PowerShell:

adb shell 
getprop | grep -e 'model' -e 'version.sdk' -e 'manufacturer' -e 'hardware' -e 'platform' -e 'revision' -e 'serialno' -e 'product.name' -e 'brand'

Sample output for Samsung:

[gsm.version.baseband]: [G900VVRU2BOE1]
[gsm.version.ril-impl]: [Samsung RIL v3.0]
[net.knoxscep.version]: [2.0.1]
[net.knoxsso.version]: [2.1.1]
[net.knoxvpn.version]: [2.2.0]
[persist.service.bdroid.version]: [4.1]
[ro.board.platform]: [msm8974]
[ro.boot.hardware]: [qcom]
[ro.boot.serialno]: [xxxxxx]
[ro.build.version.all_codenames]: [REL]
[ro.build.version.codename]: [REL]
[ro.build.version.incremental]: [G900VVRU2BOE1]
[ro.build.version.release]: [5.0]
[ro.build.version.sdk]: [21]
[ro.build.version.sdl]: [2101]
[ro.com.google.gmsversion]: [5.0_r2]
[ro.config.timaversion]: [3.0]
[ro.hardware]: [qcom]
[ro.opengles.version]: [196108]
[ro.product.brand]: [Verizon]
[ro.product.manufacturer]: [samsung]
[ro.product.model]: [SM-G900V]
[ro.product.name]: [kltevzw]
[ro.revision]: [14]
[ro.serialno]: [e5ce97c7]

@Autowired - No qualifying bean of type found for dependency at least 1 bean

Just add below annotation with qualifier name of service in service Implementation class:

@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService{
}

Center a H1 tag inside a DIV

There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.

position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);

It works most of the time. I did have a problem where a div was in a div in a li. The list item had a height set and the outer divs made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.

Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then?

How to print VARCHAR(MAX) using Print Statement?

There is great function called PrintMax written by Bennett Dill.

Here is slightly modified version that uses temp stored procedure to avoid "schema polution"(idea from https://github.com/Toolien/sp_GenMerge/blob/master/sp_GenMerge.sql)

EXEC (N'IF EXISTS (SELECT * FROM tempdb.sys.objects 
                   WHERE object_id = OBJECT_ID(N''tempdb..#PrintMax'') 
                   AND type in (N''P'', N''PC''))
    DROP PROCEDURE #PrintMax;');
EXEC (N'CREATE PROCEDURE #PrintMax(@iInput NVARCHAR(MAX))
AS
BEGIN
    IF @iInput IS NULL
    RETURN;

    DECLARE @ReversedData NVARCHAR(MAX)
          , @LineBreakIndex INT
          , @SearchLength INT;

    SET @SearchLength = 4000;

    WHILE LEN(@iInput) > @SearchLength
    BEGIN
    SET @ReversedData = LEFT(@iInput COLLATE DATABASE_DEFAULT, @SearchLength);
    SET @ReversedData = REVERSE(@ReversedData COLLATE DATABASE_DEFAULT);
    SET @LineBreakIndex = CHARINDEX(CHAR(10) + CHAR(13),
                          @ReversedData COLLATE DATABASE_DEFAULT);
    PRINT LEFT(@iInput, @SearchLength - @LineBreakIndex + 1);
    SET @iInput = RIGHT(@iInput, LEN(@iInput) - @SearchLength 
                        + @LineBreakIndex - 1);
    END;

    IF LEN(@iInput) > 0
    PRINT @iInput;
END;');

DBFiddle Demo

EDIT:

Using CREATE OR ALTER we could avoid two EXEC calls:

EXEC (N'CREATE OR ALTER PROCEDURE #PrintMax(@iInput NVARCHAR(MAX))
AS
BEGIN
    IF @iInput IS NULL
    RETURN;

    DECLARE @ReversedData NVARCHAR(MAX)
          , @LineBreakIndex INT
          , @SearchLength INT;

    SET @SearchLength = 4000;

    WHILE LEN(@iInput) > @SearchLength
    BEGIN
    SET @ReversedData = LEFT(@iInput COLLATE DATABASE_DEFAULT, @SearchLength);
    SET @ReversedData = REVERSE(@ReversedData COLLATE DATABASE_DEFAULT);
    SET @LineBreakIndex = CHARINDEX(CHAR(10) + CHAR(13), @ReversedData COLLATE DATABASE_DEFAULT);
    PRINT LEFT(@iInput, @SearchLength - @LineBreakIndex + 1);
    SET @iInput = RIGHT(@iInput, LEN(@iInput) - @SearchLength + @LineBreakIndex - 1);
    END;

    IF LEN(@iInput) > 0
    PRINT @iInput;
END;');

db<>fiddle Demo

ValidateAntiForgeryToken purpose, explanation and example

Microsoft provides us built-in functionality which we use in our application for security purposes, so no one can hack our site or invade some critical information.

From Purpose Of ValidateAntiForgeryToken In MVC Application by Harpreet Singh:

Use of ValidateAntiForgeryToken

Let’s try with a simple example to understand this concept. I do not want to make it too complicated, that’s why I am going to use a template of an MVC application, already available in Visual Studio. We will do this step by step. Let’s start.

  1. Step 1 - Create two MVC applications with default internet template and give those names as CrossSite_RequestForgery and Attack_Application respectively.

  2. Now, open CrossSite_RequestForgery application's Web Config and change the connection string with the one given below and then save.

`

<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF;
Integrated Security=true;" providerName="System.Data.SqlClient" /> 
 </connectionStrings>
  1. Now, click on Tools >> NuGet Package Manager, then Package Manager Console

  2. Now, run the below mentioned three commands in Package Manager Console to create the database.

Enable-Migrations add-migration first update-database

Important Notes - I have created database with code first approach because I want to make this example in the way developers work. You can create database manually also. It's your choice.

  1. Now, open Account Controller. Here, you will see a register method whose type is post. Above this method, there should be an attribute available as [ValidateAntiForgeryToken]. Comment this attribute. Now, right click on register and click go to View. There again, you will find an html helper as @Html.AntiForgeryToken() . Comment this one also. Run the application and click on register button. The URL will be open as:

http://localhost:52269/Account/Register

Notes- I know now the question being raised in all readers’ minds is why these two helpers need to be commented, as everyone knows these are used to validate request. Then, I just want to let you all know that this is just because I want to show the difference after and before applying these helpers.

  1. Now, open the second application which is Attack_Application. Then, open Register method of Account Controller. Just change the POST method with the simple one, shown below.

    Registration Form
    1. @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
    2. @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
    3. @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)

7.Now, suppose you are a hacker and you know the URL from where you can register user in CrossSite_RequestForgery application. Now, you created a Forgery site as Attacker_Application and just put the same URL in post method.

8.Run this application now and fill the register fields and click on register. You will see you are registered in CrossSite_RequestForgery application. If you check the database of CrossSite_RequestForgery application then you will see and entry you have entered.

  1. Important - Now, open CrossSite_RequestForgery application and comment out the token in Account Controller and register the View. Try to register again with the same process. Then, an error will occur as below.

Server Error in '/' Application. ________________________________________ The required anti-forgery cookie "__RequestVerificationToken" is not present.

This is what the concept says. What we add in View i.e. @Html.AntiForgeryToken() generates __RequestVerificationToken on load time and [ValidateAntiForgeryToken] available on Controller method. Match this token on post time. If token is the same, then it means this is a valid request.

how to clear JTable

I had to get clean table without columns. I have done folowing:

jMyTable.setModel(new DefaultTableModel());

CSS two div width 50% in one line with line break in file

<div id="wrapper" style="width: 400px">
    <div id="left" style="float: left; width: 200px;">Left</div>
    <div id="right" style="float: right; width: 200px;">Left</div>
    <div style="clear: both;"></div>
</div>

I know this question wanted inline block, but try to view http://jsfiddle.net/N9mzE/1/ in IE 7 (the oldest browser supported where I work). The divs are not side by side.

OP said he did not want to use floats because he did not like them. Well...in my opinion, making good webpages that does not look weird in any browsers should be the maingoal, and you do this by using floats.

Honestly, I can see the problem. Floats are fantastic.

TextView Marquee not working

I've encountered the same problem. Amith GC's answer(the first answer checked as accepted) is right, but sometimes textview.setSelected(true); doesn't work when the text view can't get the focus all the time. So, to ensure TextView Marquee working, I had to use a custom TextView.

public class CustomTextView extends TextView {
    public CustomTextView(Context context) {
        super(context);
    }
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }


    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }


    @Override
    public boolean isFocused() {
        return true;
    }
}

And then, you can use the custom TextView as the scrolling text view in your layout .xml file like this:

<com.example.myapplication.CustomTextView
            android:id="@+id/tvScrollingMessage"
            android:text="@string/scrolling_message_main_wish_list"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit ="marquee_forever"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:scrollHorizontally="true"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/black"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:freezesText="true"/>

NOTE: in the above code snippet com.example.myapplication is an example package name and should be replaced by your own package name.

Hope this will help you. Cheers!

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

Convert seconds to hh:mm:ss in Python

Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:

minutes = seconds / 60
hours = minutes / 60

Now, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59

Android Firebase, simply get one child object's data

Firebase listeners fire for both the initial data and any changes.

If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.

This is covered in Firebase's quickstart guide for Android. The relevant code and quote:

FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    System.out.println(snapshot.getValue());  //prints "Do you have data? You'll love Firebase."
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {        
  }
});

In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.

Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

Permissions for /var/www/html

You just need 775 for /var/www/html as long as you are logging in as myuser. The 7 octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:

chmod -R g+w /var/www/html

How do I use Comparator to define a custom sort order?

In Java 8 you can do something like this:

You first need an Enum:

public enum Color {
    BLUE, YELLOW, RED
}

Car class:

public class Car {

    Color color;

    ....

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }
}

And then, using your car list, you can simply do:

Collections.sort(carList, Comparator:comparing(CarSort::getColor));