Programs & Examples On #Table structure

PostgreSQL "DESCRIBE TABLE"

You can do that with a psql slash command:

 \d myTable describe table

It also works for other objects:

 \d myView describe view
 \d myIndex describe index
 \d mySequence describe sequence

Source: faqs.org

Change background color of edittext in android

For me this code it work So put this code in XML file rounded_edit_text

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shape="rectangle"> <stroke android:width="1dp" android:color="#3498db" /> <solid android:color="#00FFFFFF" /> <padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" > </padding> </shape> </item> </layer-list>

Start script missing error when running npm start

Another possible reason: you're using npm when your project is initialized in yarn. (I did this myself). So it would be yarn start instead of npm start.

How to take keyboard input in JavaScript?

You should register an event handler on the window or any element that you want to observe keystrokes on, and use the standard key values instead of keyCode. This modified code from MDN will respond to keydown when the left, right, up, or down arrow keys are pressed:

_x000D_
_x000D_
window.addEventListener("keydown", function (event) {_x000D_
  if (event.defaultPrevented) {_x000D_
    return; // Do nothing if the event was already processed_x000D_
  }_x000D_
_x000D_
  switch (event.key) {_x000D_
    case "ArrowDown":_x000D_
      // code for "down arrow" key press._x000D_
      break;_x000D_
    case "ArrowUp":_x000D_
      // code for "up arrow" key press._x000D_
      break;_x000D_
    case "ArrowLeft":_x000D_
      // code for "left arrow" key press._x000D_
      break;_x000D_
    case "ArrowRight":_x000D_
      // code for "right arrow" key press._x000D_
      break;_x000D_
    default:_x000D_
      return; // Quit when this doesn't handle the key event._x000D_
  }_x000D_
_x000D_
  // Cancel the default action to avoid it being handled twice_x000D_
  event.preventDefault();_x000D_
}, true);_x000D_
// the last option dispatches the event to the listener first,_x000D_
// then dispatches event to window
_x000D_
_x000D_
_x000D_

Show space, tab, CRLF characters in editor of Visual Studio

Edit -> Advanced -> View White Space or Ctrl+E,S

HAX kernel module is not installed

After reading many questions on stackoverflow I found out that my CPU does not support Virtualization. I have to upgrade to the cpu which supports Virtualization in order to install Intel X 86 Emulator accelerator(Haxm Installer)

How To: Execute command line in C#, get STD OUT results

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "YOURBATCHFILE.bat";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

Code is from MSDN.

How to search for a part of a word with ElasticSearch

without changing your index mappings you could do a simple prefix query that will do partial searches like you are hoping for

ie.

{
  "query": { 
    "prefix" : { "name" : "Doe" }
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html

How to remove provisioning profiles from Xcode

-Download iPhone configuration utility tool

-open it-> In Library section:- select provisioning profile(Left side of tool)

-select provisioning profile(which you want to delete) using back space delete it.

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

python: how to identify if a variable is an array or a scalar

To answer the question in the title, a direct way to tell if a variable is a scalar is to try to convert it to a float. If you get TypeError, it's not.

N = [1, 2, 3]
try:
    float(N)
except TypeError:
    print('it is not a scalar')
else:
    print('it is a scalar')

Is Python interpreted, or compiled, or both?

The CPU can only understand machine code indeed. For interpreted programs, the ultimate goal of an interpreter is to "interpret" the program code into machine code. However, usually a modern interpreted language does not interpret human code directly because it is too inefficient.

The Python interpreter first reads the human code and optimizes it to some intermediate code before interpreting it into machine code. That's why you always need another program to run a Python script, unlike in C++ where you can run the compiled executable of your code directly. For example, c:\Python27\python.exe or /usr/bin/python.

Deep-Learning Nan loss reasons

If using integers as targets, makes sure they aren't symmetrical at 0.

I.e., don't use classes -1, 0, 1. Use instead 0, 1, 2.

How to set space between listView Items in Android

Although the solution by Nik Reiman DOES work, I found it not to be an optimal solution for what I wanted to do. Using the divider to set the margins had the problem that the divider will no longer be visible so you can not use it to show a clear boundary between your items. Also, it does not add more "clickable area" to each item thus if you want to make your items clickable and your items are thin, it will be very hard for anyone to click on an item as the height added by the divider is not part of an item.

Fortunately I found a better solution that allows you to both show dividers and allows you to adjust the height of each item using not margins but padding. Here is an example:

ListView

<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

ListItem

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"
    android:paddingTop="10dp" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="Item"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>

current/duration time of html5 video?

HTML:

<video
    id="video-active"
    class="video-active"
    width="640"
    height="390"
    controls="controls">
    <source src="myvideo.mp4" type="video/mp4">
</video>
<div id="current">0:00</div>
<div id="duration">0:00</div>

JavaScript:

$(document).ready(function(){
  $("#video-active").on(
    "timeupdate", 
    function(event){
      onTrackedVideoFrame(this.currentTime, this.duration);
    });
});

function onTrackedVideoFrame(currentTime, duration){
    $("#current").text(currentTime); //Change #current to currentTime
    $("#duration").text(duration)
}

Notes:

Every 15 to 250ms, or whenever the MediaController's media controller position changes, whichever happens least often, the user agent must queue a task to fire a simple event named timeupdate at the MediaController.

http://www.w3.org/TR/html5/embedded-content-0.html#media-controller-position

What is the difference between Promises and Observables?

  1. a Promise is eager, whereas an Observable is lazy,
  2. a Promise is always asynchronous, while an Observable can be either synchronous or asynchronous,
  3. a Promise can provide a single value, whereas an Observable is a
    stream of values (from 0 to multiple values),
  4. you can apply RxJS operators to an Observable to get a new tailored stream.

Storing images in SQL Server?

When storing images in SQL Server do not use the 'image' datatype, according to MS it is being phased out in new versions of SQL server. Use varbinary(max) instead

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

css3 transition animation on load?

If anyone else had problems doing two transitions at once, here's what I did. I needed text to come from top to bottom on page load.

HTML

<body class="existing-class-name" onload="document.body.classList.add('loaded')">

HTML

<div class="image-wrapper">
    <img src="db-image.jpg" alt="db-image-name">
    <span class="text-over-image">DB text</span>
</div>

CSS

.text-over-image {
    position: absolute;
    background-color: rgba(110, 186, 115, 0.8);
    color: #eee;
    left: 0;
    width: 100%;
    padding: 10px;
    opacity: 0;
    bottom: 100%;
    -webkit-transition: opacity 2s, bottom 2s;
    -moz-transition: opacity 2s, bottom 2s;
    -o-transition: opacity 2s, bottom 2s;
    transition: opacity 2s, bottom 2s;
}

body.loaded .text-over-image {
    bottom: 0;
    opacity: 1;
}

Don't know why I kept trying to use 2 transition declarations in 1 selector and (not really) thinking it would use both.

Convert array values from string to int?

So I was curious about the performance of some of the methods mentioned in the answers for large number of integers.

Preparation

Just creating an array of 1 million random integers between 0 and 100. Than, I imploded them to get the string.

  $integers = array();

  for ($i = 0; $i < 1000000; $i++) {
      $integers[] = rand(0, 100);
  }

  $long_string = implode(',', $integers);

Method 1

This is the one liner from Mark's answer:

$integerIDs = array_map('intval', explode(',', $long_string));

Method 2

This is the JSON approach:

  $integerIDs = json_decode('[' . $long_string . ']', true);

Method 3

I came up with this one as modification of Mark's answer. This is still using explode() function, but instead of calling array_map() I'm using regular foreach loop to do the work to avoid the overhead array_map() might have. I am also parsing with (int) vs intval(), but I tried both, and there is not much difference in terms of performance.

  $result_array = array();
  $strings_array = explode(',', $long_string);

  foreach ($strings_array as $each_number) {
      $result_array[] = (int) $each_number;
  }

Results:

Method 1        Method 2        Method 3
0.4804770947    0.3608930111    0.3387751579
0.4748001099    0.363986969     0.3762528896
0.4625790119    0.3645150661    0.3335959911
0.5065748692    0.3570590019    0.3365750313
0.4803431034    0.4135499001    0.3330330849
0.4510772228    0.4421861172    0.341176033
0.503674984     0.3612480164    0.3561749458
0.5598649979    0.352314949     0.3766179085
0.4573421478    0.3527538776    0.3473439217

0.4863037268    0.3742785454    0.3488383293

The bottom line is the average. It looks like the first method was a little slower for 1 million integers, but I didn't notice 3x performance gain of Method 2 as stated in the answer. It turned out foreach loop was the quickest one in my case. I've done the benchmarking with Xdebug.

Edit: It's been a while since the answer was originally posted. To clarify, the benchmark was done in php 5.6.

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

I tried all of the other answers first but none of them seemed to work so I set the pear path statically in the pear config file

C:\xampp\php\pear\Config.php

find this code:

if (!defined('PEAR_INSTALL_DIR') || !PEAR_INSTALL_DIR) {
    $PEAR_INSTALL_DIR = PHP_LIBDIR . DIRECTORY_SEPARATOR . 'pear';
} 
else {
    $PEAR_INSTALL_DIR = PEAR_INSTALL_DIR;
}

and just replace it with this:

$PEAR_INSTALL_DIR = "C:\\xampp\\php\\pear";

I restarted apache and used the command:

pear config-all 

make sure the all of the paths no longer start with C:\php\pear

How to change app default theme to a different app theme?

To change your application to a different built-in theme, just add this line under application tag in your app's manifest.xml file.

Example:

<application 
    android:theme="@android:style/Theme.Holo"/>

<application 
    android:theme="@android:style/Theme.Holo.Light"/>

<application 
    android:theme="@android:style/Theme.Black"/>

<application 
    android:theme="@android:style/Theme.DeviceDefault"/>

If you set style to DeviceDefault it will require min SDK version 14, but if you won't add a style, it will set to the device default anyway.

<uses-sdk
    android:minSdkVersion="14"/>

Load json from local file with http.get() in angular 2

If you are using Angular CLI: 7.3.3 What I did is, On my assets folder I put my fake json data then on my services I just did this.

const API_URL = './assets/data/db.json';

getAllPassengers(): Observable<PassengersInt[]> {
    return this.http.get<PassengersInt[]>(API_URL);
  }

enter image description here

How can two strings be concatenated?

For the first non-paste() answer, we can look at stringr::str_c() (and then toString() below). It hasn't been around as long as this question, so I think it's useful to mention that it also exists.

Very simple to use, as you can see.

tmp <- cbind("GAD", "AB")
library(stringr)
str_c(tmp, collapse = ",")
# [1] "GAD,AB"

From its documentation file description, it fits this problem nicely.

To understand how str_c works, you need to imagine that you are building up a matrix of strings. Each input argument forms a column, and is expanded to the length of the longest argument, using the usual recyling rules. The sep string is inserted between each column. If collapse is NULL each row is collapsed into a single string. If non-NULL that string is inserted at the end of each row, and the entire matrix collapsed to a single string.

Added 4/13/2016: It's not exactly the same as your desired output (extra space), but no one has mentioned it either. toString() is basically a version of paste() with collapse = ", " hard-coded, so you can do

toString(tmp)
# [1] "GAD, AB"

Why do you have to link the math library in C?

If I put stdlib.h or stdio.h, I don't have to link those but I have to link when I compile:

stdlib.h, stdio.h are the header files. You include them for your convenience. They only forecast what symbols will become available if you link in the proper library. The implementations are in the library files, that's where the functions really live.

Including math.h is only the first step to gaining access to all the math functions.

Also, you don't have to link against libm if you don't use it's functions, even if you do a #include <math.h> which is only an informational step for you, for the compiler about the symbols.

stdlib.h, stdio.h refer to functions available in libc, which happens to be always linked in so that the user doesn't have to do it himself.

Python logging: use milliseconds in time format

If you prefer to use style='{', fmt="{asctime}.{msecs:0<3.0f}" will 0-pad your microseconds to three places for consistency.

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

How to remove all files from directory without removing directory in Node.js

Yes, there is a module fs-extra. There is a method .emptyDir() inside this module which does the job. Here is an example:

const fsExtra = require('fs-extra')

fsExtra.emptyDirSync(fileDir)

There is also an asynchronous version of this module too. Anyone can check out the link.

What does .shape[] do in "for i in range(Y.shape[0])"?

In Python shape() is use in pandas to give number of row/column:

Number of rows is given by:

train = pd.read_csv('fine_name') //load the data
train.shape[0]

Number of columns is given by

train.shape[1]

How can I align YouTube embedded video in the center in bootstrap

Using Bootstrap's built in .center-block class, which sets margin left and right to auto:

<iframe class="center-block" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>

Or using the built in .text-center class, which sets text-align: center:

<div class="text-center">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div>

Use of "this" keyword in formal parameters for static methods in C#

I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).

JAXB :Need Namespace Prefix to all the elements

MSK,

Have you tried setting a namespace declaration to your member variables like this? :

@XmlElement(required = true, namespace = "http://example.com/a")
protected String username;

@XmlElement(required = true, namespace = "http://example.com/a")
protected String password;

For our project, it solved namespace issues. We also had to create NameSpacePrefixMappers.

Convert Unix timestamp to a date string

Python:

python -c "from datetime import datetime; print(datetime.fromtimestamp($TIMESTAMP))"

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

To add WebAPI in my MVC 5 project.

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already

  3. Right click controllers folder > add new item > web > Add Web API controller

  4. Web.config will be modified accordingly by VS

  5. Add Application_Start method if not there already

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  6. Add the following class (I added in global.asax.cs file)

    public static class WebApiConfig
    {
         public static void Register(HttpConfiguration config)
         {
             // Web API routes
             config.MapHttpAttributeRoutes();
    
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
    
  7. Modify web api method accordingly

    namespace <Your.NameSpace.Here>
    {
        public class VSController : ApiController
        {
            // GET api/<controller>   : url to use => api/vs
            public string Get()
            {
                return "Hi from web api controller";
            }
    
            // GET api/<controller>/5   : url to use => api/vs/5
            public string Get(int id)
            {
                return (id + 1).ToString();
            }
        }
    }
    
  8. Rebuild and test

  9. Build a simple html page

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>    
        <script src="../<path_to_jquery>/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
            var uri = '/api/vs';
            $(document).ready(function () {
                $.getJSON(uri)
                .done(function (data) {
                    alert('got: ' + data);
                });
    
                $.ajax({
                    url: '/api/vs/5',
                    async: true,
                    success: function (data) {
                        alert('seccess1');
                        var res = parseInt(data);
                        alert('got res=' + res);
                    }
                });
            });
        </script>
    </head>
    <body>
    ....
    </body>
    </html>
    

nvarchar(max) vs NText

Wanted to add my experience with converting. I had many text fields in ancient Linq2SQL code. This was to allow text columns present in indexes to be rebuilt ONLINE.

First I've known about the benefits for years, but always assumed that converting would mean some scary long queries where SQL Server would have to rebuild the table and copy everything over, bringing down my websites and raising my heartrate.

I was also concerned that the Linq2SQL could cause errors if it was doing some kind of verification of the column type.

Happy to report though, that the ALTER commands returned INSTANTLY - so they are definitely only changing table metadata. There may be some offline work happening to bring <8000 character data back to be in-table, but the ALTER command was instant.

I ran the following to find all columns needing conversion:

SELECT concat('ALTER TABLE dbo.[', table_name, '] ALTER COLUMN [', column_name, '] VARCHAR(MAX)'), table_name, column_name
FROM information_schema.columns where data_type = 'TEXT' order by table_name, column_name

SELECT concat('ALTER TABLE dbo.[', table_name, '] ALTER COLUMN [', column_name, '] NVARCHAR(MAX)'), table_name, column_name
FROM information_schema.columns where data_type = 'NTEXT' order by table_name, column_name

This gave me a nice list of queries, which I just selected and copied to a new window. Like I said - running this was instant.

enter image description here

Linq2SQL is pretty ancient - it uses a designer that you drag tables onto. The situation may be more complex for EF Code first but I haven't tackled that yet.

How to convert 'binary string' to normal string in Python3?

Please, see oficial encode() and decode() documentation from codecs library. utf-8 is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1 or utf_32.

How to name an object within a PowerPoint slide?

Click Insert ->Object->Create from file ->Browse.

Once the file is selected choose the "Change icon" option and you will be able to rename the file and change the icon if you wish.

Hope this helps!

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

How to disable editing of elements in combobox for c#?

Use the ComboStyle property:

comboBox.DropDownStyle = ComboBoxStyle.DropDownList;

How to check whether a int is not null or empty?

I think you can initialize the variables a value like -1, because if the int type variables is not initialized it can't be used. When you want to check if it is not the value you want you can check if it is -1.

How to use ADB in Android Studio to view an SQLite DB

What it mentions as you type adb?

step1. >adb shell
step2. >cd data/data
step3. >ls -l|grep "your app package here"
step4. >cd "your app package here"
step5. >sqlite3 xx.db

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

An another one: you might want to avoid running Eclipse and Android Studio together, it helped me.

How to choose between Hudson and Jenkins?

Up front .. I am a Hudson committer and author of the Hudson book, but I was not involved in the whole split of the projects.

In any case here is my advice:

Check out both and see what fits your needs better.

Hudson is going to complete the migration to be a top level Eclipse projects later this year and has gotten a whole bunch of full time developers, QA and others working on the project. It is still going strong and has a lot of users and with being the default CI server at Eclipse it will continue to serve the needs of many Java developers. Looking at the roadmap and plans for the future you can see that after the Maven 3 integration accomplished with the 2.1.0 release a whole bunch of other interesting feature are ahead.

http://www.eclipse.org/hudson

Jenkins on the other side has won over many original Hudson users and has a large user community across multiple technologies and also has a whole bunch of developers working on it.

At this stage both CI servers are great tools to use and depending on your needs in terms of technology to integrate with one or the other might be better. Both products are available as open source and you can get commercial support from various companies for both.

In any case .. if you are not using a CI server yet.. start now with either of them and you will see huge benefits.

Update Jan 2013: After a long process of IP cleanup and further improvements Hudson 3.0 as the first Eclipse foundation approved release is now available.

What is the purpose of nameof?

It's really useful for ArgumentException and its derivatives:

public string DoSomething(string input) 
{
    if(input == null) 
    {
        throw new ArgumentNullException(nameof(input));
    }
    ...

Now if someone refactors the name of the input parameter the exception will be kept up to date too.

It is also useful in some places where previously reflection had to be used to get the names of properties or parameters.

In your example nameof(T) gets the name of the type parameter - this can be useful too:

throw new ArgumentException(nameof(T), $"Type {typeof(T)} does not support this method.");

Another use of nameof is for enums - usually if you want the string name of an enum you use .ToString():

enum MyEnum { ... FooBar = 7 ... }

Console.WriteLine(MyEnum.FooBar.ToString());

> "FooBar"

This is actually relatively slow as .Net holds the enum value (i.e. 7) and finds the name at run time.

Instead use nameof:

Console.WriteLine(nameof(MyEnum.FooBar))

> "FooBar"

Now .Net replaces the enum name with a string at compile time.


Yet another use is for things like INotifyPropertyChanged and logging - in both cases you want the name of the member that you're calling to be passed to another method:

// Property with notify of change
public int Foo
{
    get { return this.foo; }
    set
    {
        this.foo = value;
        PropertyChanged(this, new PropertyChangedEventArgs(nameof(this.Foo));
    }
}

Or...

// Write a log, audit or trace for the method called
void DoSomething(... params ...)
{
    Log(nameof(DoSomething), "Message....");
}

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

How to terminate process from Python using pid?

So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.

It also answers the question in a way(even though it is an old one with lots of answers).

While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!

import pandas as pd
import wmi
from re import escape
import os

def kill_process(kill_path, execs):
    f = wmi.WMI()
    esc = escape(kill_path)
    temp = {'id':[], 'path':[], 'name':[]}
    for process in f.Win32_Process():
        temp['id'].append(process.ProcessId)
        temp['path'].append(process.ExecutablePath)
        temp['name'].append(process.Name)
    temp = pd.DataFrame(temp)
    temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
    temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
    [os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]

MySQL select where column is not empty

We can use CASE for setting blank value to some char or String. I am using NA as Default string.

SELECT phone,   
CASE WHEN phone2 = '' THEN 'NA' END AS phone2 ELSE ISNULL(phone2,0) 
FROM jewishyellow.users  WHERE phone LIKE '813%'

How to tackle daylight savings using TimeZone in Java

As per this answer:

TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());

Is there a typescript List<> and/or Map<> class/library?

Did they add a runtime List<> and/or Map<> type class to typepad 1.0

No, providing a runtime is not the focus of the TypeScript team.

is there a solid library out there someone wrote that provides this functionality?

I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections

Update

JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts : https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want

How to get character for a given ascii value

Simply Try this:

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));

How do we change the URL of a working GitLab install?

GitLab Omnibus

For an Omnibus install, it is a little different.

The correct place in an Omnibus install is:

/etc/gitlab/gitlab.rb
    external_url 'http://gitlab.example.com'

Finally, you'll need to execute sudo gitlab-ctl reconfigure and sudo gitlab-ctl restart so the changes apply.


I was making changes in the wrong places and they were getting blown away.

The incorrect paths are:

/opt/gitlab/embedded/service/gitlab-rails/config/gitlab.yml
/var/opt/gitlab/.gitconfig
/var/opt/gitlab/nginx/conf/gitlab-http.conf

Pay attention to those warnings that read:

# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.

Generating random numbers in Objective-C

Use the arc4random_uniform(upper_bound) function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.

arc4random_uniform(74)

arc4random_uniform(upper_bound) avoids modulo bias as described in the man page:

arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

How do I space out the child elements of a StackPanel?

Usually, I use Grid instead of StackPanel like this:

horizontal case

<Grid>
 <Grid.ColumnDefinitions>
    <ColumnDefinition Width="auto"/>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition  Width="auto"/>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition  Width="auto"/>
 </Grid.ColumnDefinitions>
 <TextBox Height="30" Grid.Column="0">Apple</TextBox>
 <TextBox Height="80" Grid.Column="2">Banana</TextBox>
 <TextBox Height="120" Grid.Column="4">Cherry</TextBox>
</Grid>

vertical case

<Grid>
     <Grid.ColumnDefinitions>
        <RowDefinition Width="auto"/>
        <RowDefinition Width="*"/>
        <RowDefinition  Width="auto"/>
        <RowDefinition Width="*"/>
        <RowDefinition  Width="auto"/>
     </Grid.ColumnDefinitions>
     <TextBox Height="30" Grid.Row="0">Apple</TextBox>
     <TextBox Height="80" Grid.Row="2">Banana</TextBox>
     <TextBox Height="120" Grid.Row="4">Cherry</TextBox>
</Grid>

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Well, I'm late.


In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(???) channel in HSV color space. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.


Main steps:

  1. Read into BGR
  2. Convert the image from bgr to hsv space
  3. Threshold the S channel
  4. Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

This is my result:

enter image description here


The Python code(Python 3.5 + OpenCV 3.3):

#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST

import cv2
import numpy as np

##(1) read into  bgr-space
img = cv2.imread("test2.jpg")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)

##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas  = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)

## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]

## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)

## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)

Related answers:

  1. How to detect colored patches in an image using OpenCV?
  2. Edge detection on colored background using OpenCV
  3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
  4. How to use `cv2.findContours` in different OpenCV versions?

List<T> or IList<T>

What if .NET 5.0 replaces System.Collections.Generic.List<T> to System.Collection.Generics.LinearList<T>. .NET always owns the name List<T> but they guarantee that IList<T> is a contract. So IMHO we (atleast I) are not supposed to use someone's name (though it is .NET in this case) and get into trouble later.

In case of using IList<T>, the caller is always guareented things to work, and the implementer is free to change the underlying collection to any alternative concrete implementation of IList

UITableView, Separator color where to set?

Swift 3, xcode version 8.3.2, storyboard->choose your table View->inspector->Separator.

Swift 3, xcode version 8.3.2

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

You don't create subfolders of the drawable folder but rather 'sibling' folders next to it under the /res folder for the different screen densities or screen sizes. The /drawable folder (without any dimension) is mostly used for drawables that don't relate to any screen sizes like selectors.

See this screenshot (use the name drawable-hdpi instead of mipmap-hdpi):

enter image description here

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

Clean project,Clean build folder,Restart Xcode. i just remove path at project goto > Build Settings > Search the keyword. Swift Compiler - General -> Objective-C Bridging header worked for me.

Jquery how to find an Object by attribute in an Array

Best, Fastest way is

function arrayLookup(array, prop, val) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i].hasOwnProperty(prop) && array[i][prop] === val) {
            return array[i];
        }
    }
    return null;
}

PHP mySQL - Insert new record into table with auto-increment on primary key

Use the DEFAULT keyword:

$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')";

Also, you can specify the columns, (which is better practice):

$query = "INSERT INTO myTable
          (fname, lname, website)
          VALUES
          ('fname', 'lname', 'website')";

Reference:

Output (echo/print) everything from a PHP Array

var_dump() can do this.

This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

http://php.net/manual/en/function.var-dump.php

How to select <td> of the <table> with javascript?

try document.querySelectorAll("#table td");

Selected tab's color in Bottom Navigation View

1. Inside res create folder with name color (like drawable)

2. Right click on color folder. Select new-> color resource file-> create color.xml file (bnv_tab_item_foreground) (Figure 1: File Structure)

3. Copy and paste bnv_tab_item_foreground

<android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="0dp"
            android:layout_marginStart="0dp"
            app:itemBackground="@color/appcolor"//diffrent color
            app:itemIconTint="@color/bnv_tab_item_foreground" //inside folder 2 diff colors
            app:itemTextColor="@color/bnv_tab_item_foreground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation" />

bnv_tab_item_foreground:

 <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="true" android:color="@color/white" />
        <item android:color="@android:color/darker_gray"  />
    </selector>

Figure 1: File Structure:

Figure 1: File Structure

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Use either. They are both equally (in)secure, as in many cases SERVER_NAME is just populated from HTTP_HOST anyway. I normally go for HTTP_HOST, so that the user stays on the exact host name they started on. For example if I have the same site on a .com and .org domain, I don't want to send someone from .org to .com, particularly if they might have login tokens on .org that they'd lose if sent to the other domain.

Either way, you just need to be sure that your webapp will only ever respond for known-good domains. This can be done either (a) with an application-side check like Gumbo's, or (b) by using a virtual host on the domain name(s) you want that does not respond to requests that give an unknown Host header.

The reason for this is that if you allow your site to be accessed under any old name, you lay yourself open to DNS rebinding attacks (where another site's hostname points to your IP, a user accesses your site with the attacker's hostname, then the hostname is moved to the attacker's IP, taking your cookies/auth with it) and search engine hijacking (where an attacker points their own hostname at your site and tries to make search engines see it as the ‘best’ primary hostname).

Apparently the discussion is mainly about $_SERVER['PHP_SELF'] and why you shouldn't use it in the form action attribute without proper escaping to prevent XSS attacks.

Pfft. Well you shouldn't use anything in any attribute without escaping with htmlspecialchars($string, ENT_QUOTES), so there's nothing special about server variables there.

Copy all files with a certain extension from all subdirectories

--parents is copying the directory structure, so you should get rid of that.

The way you've written this, the find executes, and the output is put onto the command line such that cp can't distinguish between the spaces separating the filenames, and the spaces within the filename. It's better to do something like

$ find . -name \*.xls -exec cp {} newDir \;

in which cp is executed for each filename that find finds, and passed the filename correctly. Here's more info on this technique.

Instead of all the above, you could use zsh and simply type

$ cp **/*.xls target_directory

zsh can expand wildcards to include subdirectories and makes this sort of thing very easy.

NSAttributedString add text alignment

 NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
 paragraphStyle.alignment                = NSTextAlignmentCenter;

 NSAttributedString *attributedString   = 
[NSAttributedString.alloc initWithString:@"someText" 
                              attributes:
         @{NSParagraphStyleAttributeName:paragraphStyle}];

Swift 4.2

let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.center

    let attributedString = NSAttributedString(string: "someText", attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle])

Convert array of integers to comma-separated string

int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

This was happening to me when I had to fix an old project that had not been looked at in a while. The chromedriver associated to the project was not compatible with my version of chrome, so when I updated the chromedriver it worked fine.

Why do I need to configure the SQL dialect of a data source?

Dialect is the SQL dialect that your database uses.

List of SQL dialects for Hibernate.

Either provide it in hibernate.cfg.xml as :

<hibernate-configuration>
   <session-factory name="session-factory">
      <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
       ...
   </session-factory>
</hibernate-configuration>

or in the properties file as :

hibernate.dialect=org.hibernate.dialect.SQLServerDialect

Configure cron job to run every 15 minutes on Jenkins

1) Your cron is wrong. If you want to run job every 15 mins on Jenkins use this:

H/15 * * * *

2) Warning from Jenkins Spread load evenly by using ‘...’ rather than ‘...’ came with JENKINS-17311:

To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.

Examples:

  • H/15 * * * * - every fifteen minutes (perhaps at :07, :22, :37, :52):
  • H(0-29)/10 * * * * - every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24)
  • H 9-16/2 * * 1-5 - once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM)
  • H H 1,15 1-11 * - once a day on the 1st and 15th of every month except December

How to make bootstrap 3 fluid layout without horizontal scrollbar

Just my 2 cents here. Mostly this will work for you, as it did for me.

body > .row {
    margin-left: 0px;
    margin-right: 0px;
}

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

Is a URL allowed to contain a space?

Can someone point to an RFC indicating that a URL with a space must be encoded?

URIs, and thus URLs, are defined in RFC 3986.

If you look at the grammar defined over there you will eventually note that a space character never can be part of a syntactically legal URL, thus the term "URL with a space" is a contradiction in itself.

Receive JSON POST with PHP

Read the doc:

In general, php://input should be used instead of $HTTP_RAW_POST_DATA.

as in the php Manual

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

You are correct in that static files are copied to the application at link-time, and that shared files are just verified at link time and loaded at runtime.

The dlopen call is not only for shared objects, if the application wishes to do so at runtime on its behalf, otherwise the shared objects are loaded automatically when the application starts. DLLS and .so are the same thing. the dlopen exists to add even more fine-grained dynamic loading abilities for processes. You dont have to use dlopen yourself to open/use the DLLs, that happens too at application startup.

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

How to convert rdd object to dataframe in spark

Here is a simple example of converting your List into Spark RDD and then converting that Spark RDD into Dataframe.

Please note that I have used Spark-shell's scala REPL to execute following code, Here sc is an instance of SparkContext which is implicitly available in Spark-shell. Hope it answer your question.

scala> val numList = List(1,2,3,4,5)
numList: List[Int] = List(1, 2, 3, 4, 5)

scala> val numRDD = sc.parallelize(numList)
numRDD: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[80] at parallelize at <console>:28

scala> val numDF = numRDD.toDF
numDF: org.apache.spark.sql.DataFrame = [_1: int]

scala> numDF.show
+---+
| _1|
+---+
|  1|
|  2|
|  3|
|  4|
|  5|
+---+

Angularjs autocomplete from $http

I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.

Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete

So basically you have to return a promise when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $qservice/directive/controller where you issue your HTTP Request.

Example:

function getMyHttpData(){
  var deferred = $q.defer();
  $http.jsonp(request).success(function(data){
    // the promise gets resolved with the data from HTTP
    deferred.resolve(data);
  });
  // return the promise
  return deferred.promise;
}

I hope this helps.

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

How to Consume WCF Service with Android

From my recent experience i would recommend ksoap library to consume a Soap WCF Service, its actually really easy, this anddev thread migh help you out too.

Writing File to Temp Folder

For %appdata% take a look to

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Autonumber value of last inserted row - MS Access / VBA

In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:

  Dim query As String
  Dim newRow As Long  ' note change of data type
  Dim db As DAO.Database

  query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
  Set db = CurrentDB
  db.Execute(query)
  newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
  Set db = Nothing

I used to do INSERTs by opening an AddOnly recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO.

Drop default constraint on a column in TSQL

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from 
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where 
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

Internal vs. Private Access Modifiers

Find an explanation below. You can check this link for more details - http://www.dotnetbull.com/2013/10/public-protected-private-internal-access-modifier-in-c.html

Private: - Private members are only accessible within the own type (Own class).

Internal: - Internal member are accessible only within the assembly by inheritance (its derived type) or by instance of class.

enter image description here

Reference :

dotnetbull - what is access modifier in c#

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

What is a Data Transfer Object (DTO)?

DefN

A DTO is a hardcoded data model. It only solves the problem of modeling a data record handled by a hardcoded production process, where all fields are known at compile-time and therefore accessed via strongly typed properties.

In contrast, a dynamic model or "property bag" solves the problem of modeling a data record when the production process is created at runtime.

The Cvar

A DTO can be modeled with fields or properties, but someone invented a very useful data container called the Cvar. It is a reference to a value. When a DTO is modeled with what I call reference properties, modules can be configured to share heap memory and thereby collaboratively work on it. This completely eliminates parameter passing and O2O communication from your code. In other words, DTOs having reference properties allow code to achieve zero coupling.

    class Cvar { ... }

    class Cvar<T> : Cvar
    {
        public T Value { get; set; }
    }

    class MyDTO
    {
        public Cvar<int> X { get; set; }
        public Cvar<int> Y { get; set; }
        public Cvar<string> mutableString { get; set; } // >;)
    }

Source: http://www.powersemantics.com/

Dynamic DTOs are a necessary component for dynamic software. To instantiate a dynamic process, one compiler step is to bind each machine in the script to the reference properties the script defines. A dynamic DTO is built by adding the Cvars to a collection.

    // a dynamic DTO
    class CvarRegistry : Dictionary<string, Cvar> { }

Contentions

Note: because Wix labeled the use of DTOs for organizing parameters as an "anti-pattern", I will give an authoritative opinion.

    return View(model);  // MVC disagrees

My collaborative architecture replaces design patterns. Refer to my web articles.

Parameters provide immediate control of a stack frame machine. If you use continuous control and therefore do not need immediate control, your modules do not need parameters. My architecture has none. In-process configuration of machines (methods) adds complexity but also value (performance) when the parameters are value types. However, reference type parameters make the consumer cause cache misses to get the values off the heap anyway -- therefore, just configure the consumer with reference properties. Fact from mechanical engineering: reliance on parameters is a kind of preoptimization, because processing (making components) itself is waste. Refer to my W article for more information. http://www.powersemantics.com/w.html.

Fowler and company might realize the benefits of DTOs outside of distributed architecture if they had ever known any other architecture. Programmers only know distributed systems. Integrated collaborative systems (aka production aka manufacturing) are something I had to claim as my own architecture, because I am the first to write code this way.

Some consider the DTO an anemic domain model, meaning it lacks functionality, but this assumes an object must own the data it interacts with. This conceptual model then forces you to deliver the data between objects, which is the model for distributed processing. However on a manufacturing line, each step can access the end product and change it without owning or controlling it. That's the difference between distributed and integrated processing. Manufacturing separates the product from operations and logistics.

There's nothing inherently wrong with modeling processing as a bunch of useless office workers who e-mail work to one another without keeping an e-mail trail, except for all the extra work and headache it creates in handling logistics and return problems. A properly modeled distributed process attaches a document (active routing) to the product describing what operations it came from and will go to. The active routing is a copy of the process source routing, which is written before the process begins. In the event of a defect or other emergency change, the active routing is modified to include the operation steps it will be sent to. This then accounts for all the labor which went into production.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

It looks like you added a dependency on a Paypal library but did not include that library in your project:

Caused by: java.lang.ClassNotFoundException: com.paypal.exception.SSLConfigurationException

I'm not sure which jar, but it is most likely paypal-core.jar. Try adding it under WEB-INF/lib.

Bootstrap Modal Backdrop Remaining

for Bootstrap 4, this should work for you

 $('.modal').remove();
 $('.modal-backdrop').remove();

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

javascript close current window

Works only in Google Chrome with self.close();. Tested in v48.

window.close() won't do what you want as the documentation for it clearly states that scripts may close only the windows that were opened by it.

Android - SMS Broadcast receiver

I've encountered such issue recently. Though code was correct, I didn't turn on permissions in app settings. So, all permissions hasn't been set by default on emulators, so you should do it yourself.

Finding local maxima/minima with Numpy in a 1D numpy array

Update: I wasn't happy with gradient so I found it more reliable to use numpy.diff. Please let me know if it does what you want.

Regarding the issue of noise, the mathematical problem is to locate maxima/minima if we want to look at noise we can use something like convolve which was mentioned earlier.

import numpy as np
from matplotlib import pyplot

a=np.array([10.3,2,0.9,4,5,6,7,34,2,5,25,3,-26,-20,-29],dtype=np.float)

gradients=np.diff(a)
print gradients


maxima_num=0
minima_num=0
max_locations=[]
min_locations=[]
count=0
for i in gradients[:-1]:
        count+=1

    if ((cmp(i,0)>0) & (cmp(gradients[count],0)<0) & (i != gradients[count])):
        maxima_num+=1
        max_locations.append(count)     

    if ((cmp(i,0)<0) & (cmp(gradients[count],0)>0) & (i != gradients[count])):
        minima_num+=1
        min_locations.append(count)


turning_points = {'maxima_number':maxima_num,'minima_number':minima_num,'maxima_locations':max_locations,'minima_locations':min_locations}  

print turning_points

pyplot.plot(a)
pyplot.show()

How to pass table value parameters to stored procedure from .net code

The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)

Create this extension method...

public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List<int> data)
{
   if(paramCollection != null)
   {
       var p = paramCollection.Add(parameterName, SqlDbType.Structured);
       p.TypeName = "dbo.tvp_Int";
       DataTable _dt = new DataTable() {Columns = {"Value"}};
       data.ForEach(value => _dt.Rows.Add(value));
       p.Value = _dt;
   }
}

Now you can add a table valued parameter in one line anywhere simply by doing this:

cmd.Parameters.AddWithValueFor_Tvp_Int("@IDValues", listOfIds);

Adding external library into Qt Creator project

in .pro : LIBS += Ole32.lib OleAut32.lib Psapi.lib advapi32.lib

in .h/.cpp: #pragma comment(lib,"user32.lib")

#pragma comment(lib,"psapi.lib")

Reset Entity-Framework Migrations

This method doesn't require deleting of the __MigrationHistory table, so you don't have to put your hands on the database on deploy.

  1. Delete existing migrations from the Migrations folder.
  2. In Package Manager Console run Add-Migration ResetMigrations
  3. Clean migration history in the Up() method:
/// <summary>
/// Reset existing migrations by cleaning the __MigrationHistory table
/// and creating a new initial migration with the current model snapshot.
/// </summary>
public partial class ResetMigrations : DbMigration
{
    public override void Up()
    {
        Sql("DELETE FROM [dbo].[__MigrationHistory]");
    }

    public override void Down()
    {
    }
}

How can I align two divs horizontally?

<html>
<head>
<style type="text/css">
#floatingDivs{float:left;}
</style>
</head>

<body>
<div id="floatingDivs">
    <span>source list</span>
    <select size="10">
        <option />
        <option />
        <option />
    </select>
</div>

<div id="floatingDivs">
    <span>destination list</span>
    <select size="10">
        <option />
        <option />
        <option />
    </select>
</div>

</body>
</html>

What is a segmentation fault?

According to Wikipedia:

A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).

Val and Var in Kotlin

Both variables are used as initialising

  • val like a constant variable, It can be readable, and the properties of a val can be modified.

  • var just like a mutable variable. you can change the value at any time.

How to get the cursor to change to the hand when hovering a <button> tag

see: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor

so you need to add: cursor:pointer;

In your case use:

#more {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

This will apply the curser to the element with the ID "more" (can be only used once). So in your HTML use

<input type="button" id="more" />

If you want to apply this to more than one button then you have more than one possibility:

using CLASS

.more {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

and in your HTML use

<input type="button" class="more" value="first" />
<input type="button" class="more" value="second" />

or apply to a html context:

input[type=button] {
  background:none;
  border:none;
  color:#FFF;
  font-family:Verdana, Geneva, sans-serif;
  cursor:pointer;
}

and in your HTML use

<input type="button" value="first" />
<input type="button" value="second" />

SQL Server: combining multiple rows into one row

_x000D_
_x000D_
declare @maxColumnCount int=0;
 declare @Query varchar(max)='';
 declare @DynamicColumnName nvarchar(MAX)='';

-- table type variable that store all values of column row no
 DECLARE @TotalRows TABLE( row_count int)
 INSERT INTO @TotalRows (row_count)
 SELECT (ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc)) as row_no FROM tblExportPartProforma

-- Get the MAX value from @TotalRows table
 set @maxColumnCount= (select max(row_count) from @TotalRows)
 
-- loop to create Dynamic max/case and store it into local variable 
 DECLARE @cnt INT = 1;
 WHILE @cnt <= @maxColumnCount
 BEGIN
   set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then InvoiceType end )as InvoiceType'+cast(@cnt as varchar)+''
      set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then BankRefno end )as BankRefno'+cast(@cnt as varchar)+''
            set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceived end )as AmountReceived'+cast(@cnt as varchar)+''

      set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceivedDate end )as AmountReceivedDate'+cast(@cnt as varchar)+''


   SET @cnt = @cnt + 1;
END;

-- Create dynamic CTE and store it into local variable @query 
  set @Query='
     with CTE_tbl as
     (
       SELECT InvoiceNo,InvoiceType,BankRefno,AmountReceived,AmountReceivedDate,
       ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc) as row_no
       FROM tblExportPartProforma
      )
  select
     InvoiceNo
     '+@DynamicColumnName+'
     FROM CTE_tbl
     group By InvoiceNo'

-- Execute the Query
 execute (@Query)
_x000D_
_x000D_
_x000D_

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

Change the

private static final long serialVersionUID = 1L;

to any other value like

private static final long serialVersionUID = 102831973239L;

also you can generate it automatically in eclipse.

It is because each servlet in a app has a unique id.and tomcat causes problem with two servlets having same id...

Fastest way to check if a value exists in a list

It sounds like your application might gain advantage from the use of a Bloom Filter data structure.

In short, a bloom filter look-up can tell you very quickly if a value is DEFINITELY NOT present in a set. Otherwise, you can do a slower look-up to get the index of a value that POSSIBLY MIGHT BE in the list. So if your application tends to get the "not found" result much more often then the "found" result, you might see a speed up by adding a Bloom Filter.

For details, Wikipedia provides a good overview of how Bloom Filters work, and a web search for "python bloom filter library" will provide at least a couple useful implementations.

PHP: get the value of TEXTBOX then pass it to a VARIABLE

In testing2.php use the following code to get the name:

if ( ! empty($_POST['name'])){
    $name = $_POST['name']);
}

When you create the next page, use the value of $name to prefill the form field:

Name: <input type="text" name="name" id="name" value="<?php echo $name; ?>"><br/>

However, before doing that, be sure to use regular expressions to verify that the $name only contains valid characters, such as:

$pattern =  '/^[0-9A-Za-zÁ-Úá-úàÀÜü]+$/';//integers & letters
if (preg_match($pattern, $name) == 1){
    //continue
} else {
    //reload form with error message
}

Clone only one branch

--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check

#git --version 

If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch

#git clone -b branch --single-branch git://github/repository.git

By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.

sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version

Once 1.8.X is installed now simply do:

git clone -b branch --single-branch git://github/repository.git

Git will now only download a single branch from the server.

Laravel migration default value

In Laravel 6 you have to add 'change' to your migrations file as follows:

$table->enum('is_approved', array('0','1'))->default('0')->change();

#1062 - Duplicate entry for key 'PRIMARY'

I had this error from mySQL using DataNucleus and a database created with UTF8 - the error was being caused by this annotation for a primary key:

@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDSTRING)
protected String id;

dropping the table and regenerating it with this fixed it.

@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDHEX)
protected String id;

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

convert htaccess to nginx

Have not tested it yet, but the looks are better than the one Alex mentions.

The description at winginx.com/en/htaccess says:

About the htaccess to nginx converter

The service is to convert an Apache's .htaccess to nginx configuration instructions.

First of all, the service was thought as a mod_rewrite to nginx converter. However, it allows you to convert some other instructions that have reason to be ported from Apache to nginx.

Note server instructions (e.g. php_value, etc.) are ignored.

The converter does not check syntax, including regular expressions and logic errors.

Please, check the result manually before use.

How to save and load numpy.array() data properly?

np.save('data.npy', num_arr) # save
new_num_arr = np.load('data.npy') # load

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

The WebKit Developer Console (found in Chrome, Safari, etc.) lets you view attached events for elements.

More detail in this Stack Overflow question

Reflection generic get field value

You should pass the object to get method of the field, so

  Field field = object.getClass().getDeclaredField(fieldName);    
  field.setAccessible(true);
  Object value = field.get(object);

Python argparse: default value or specified value

Actually, you only need to use the default argument to add_argument as in this test.py script:

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--example', default=1)
    args = parser.parse_args()
    print(args.example)

test.py --example
% 1
test.py --example 2
% 2

Details are here.

What is a good practice to check if an environmental variable exists or not?

Use the first; it directly tries to check if something is defined in environ. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and only use it for a comparison.

You're trying to see if something is present in environ, why would you get just to compare it and then toss it away?

That's exactly what getenv does:

Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.

(this also means your check could just be if getenv("FOO"))

you don't want to get it, you want to check for it's existence.

Either way, getenv is just a wrapper around environ.get but you don't see people checking for membership in mappings with:

from os import environ
if environ.get('Foo') is not None:

To summarize, use:

if "FOO" in os.environ:
    pass

if you just want to check for existence, while, use getenv("FOO") if you actually want to do something with the value you might get.

Change size of text in text input tag?

The Javascript to change font size for an input control is:

input.style.fontSize = "16px";

How can I take a screenshot/image of a website using Python?

I can't comment on ars's answer, but I actually got Roland Tapken's code running using QtWebkit and it works quite well.

Just wanted to confirm that what Roland posts on his blog works great on Ubuntu. Our production version ended up not using any of what he wrote but we are using the PyQt/QtWebKit bindings with much success.

Note: The URL used to be: http://www.blogs.uni-osnabrueck.de/rotapken/2008/12/03/create-screenshots-of-a-web-page-using-python-and-qtwebkit/ I've updated it with a working copy.

Write and read a list from file

As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:

with open('my_file.txt', 'rU') as in_file:
    data = in_file.read().split('\n')

That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:

with open('new_file.txt', 'w') as out_file:
    out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters

Hopefully that fits what you're looking for.

Getting error: ISO C++ forbids declaration of with no type

Your declaration is int ttTreeInsert(int value);

However, your definition/implementation is

ttTree::ttTreeInsert(int value)
{
}

Notice that the return type int is missing in the implementation. Instead it should be

int ttTree::ttTreeInsert(int value)
{
    return 1; // or some valid int
}

Use of Finalize/Dispose method in C#

1) WebClient is a managed type, so you don't need a finalizer. The finalizer is needed in the case your users don't Dispose() of your NoGateway class and the native type (which is not collected by the GC) needs to be cleaned up after. In this case, if the user doesn't call Dispose(), the contained WebClient will be disposed by the GC right after the NoGateway does.

2) Indirectly yes, but you shouldn't have to worry about it. Your code is correct as stands and you cannot prevent your users from forgetting to Dispose() very easily.

Calling a function within a Class method?

In order to have a "function within a function", if I understand what you're asking, you need PHP 5.3, where you can take advantage of the new Closure feature.

So you could have:

public function newTest() {
   $bigTest = function() {
        //Big Test Here
   }
}

Get Time from Getdate()

You might want to check out this old thread.

If you can omit AM/PM portion and using SQL Server 2008, you should go with the approach suggested here

To get the rid from nenoseconds in time(SQL Server 2008), do as below :

SELECT CONVERT(TIME(0),GETDATE()) AS HourMinuteSecond

I hope it helps!!

Scroll part of content in fixed position container

I changed scrollable div to be with absolute position, and everything works for me

div.sidebar {
    overflow: hidden;
    background-color: green;
    padding: 5px;
    position: fixed;
    right: 20px;
    width: 40%;
    top: 30px;
    padding: 20px;
    bottom: 30%;
}
div#fixed {
    background: #76a7dc;
    color: #fff;
    height: 30px;
}

div#scrollable {
    overflow-y: scroll;
    background: lightblue;

    position: absolute;
    top:55px; 
    left:20px;
    right:20px;
    bottom:10px;
}

DEMO with two scrollable divs

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

With Bootstrap 4+, you can simply add the class custom-select for your select inputs to drop the browser-specific styling and keep the arrow icons.

Documentation Here: Bootstrap 4 Custom Forms Select Menu

How to create a drop shadow only on one side of an element?

Another idea based on the answer of @theengineear where I will use inset instead of polygon. It's easier since it works the same way as margin or padding. I will also rely on CSS variable to easily define all the different cases.

_x000D_
_x000D_
.shadow {
  box-shadow: 0 0 8px 5px rgba(200, 0, 0, 0.5);
  clip-path:inset(var(--t,0) var(--r,0) var(--b,0) var(--l,0))
}

.top { --t:-100%; }
.right { --r:-100%;}
.bottom { --b:-100%; }
.left { --l:-100%;}


/* layout for example */

.box {
  display: inline-block;
  vertical-align: top;
  background: #338484;
  color: #fff;
  width: 4em;
  height: 2em;
  margin: 1em;
  padding: 1em;
}
_x000D_
<div class="box">none</div>
<div class="box shadow top right left bottom">all</div>
<div class="box shadow top">top</div>
<div class="box shadow right">right</div>
<div class="box shadow bottom">bottom</div>
<div class="box shadow left">left</div>
<div class="box shadow bottom right">bottom right</div>
<div class="box shadow bottom top">top bottom</div>
<div class="box shadow left top right">top left right</div>
<div class="box shadow left right"> left right</div>
_x000D_
_x000D_
_x000D_

Jquery: how to trigger click event on pressing enter key

Jquery: Fire Button click event Using enter Button Press try this::

tabindex="0" onkeypress="return EnterEvent(event)"

 <!--Enter Event Script-->
    <script type="text/javascript">
        function EnterEvent(e) {
            if (e.keyCode == 13) {
                __doPostBack('<%=btnSave.UniqueID%>', "");
            }
        }
    </script>
    <!--Enter Event Script-->

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

In UNIX systems, you can append to the LD_LIBRARY_PATH environment variable. On Windows, the JVM automatically sets the system property, java.library.path, to PATH; so if the dll is on your PATH, then you're set.

HttpContext.Current.User.Identity.Name is Empty

These might resolve the issue(It did for me). In IIS Express change the project property values, "Anonymous Authentication" and "Windows Authentication". To do this, when project is selected, press F4 and then change these properties.

enter image description here

In case you are deploying it on IIS locally, make sure local machines "Windows Authentication" feature is enabled and "Anonymous Authentication" is disabled.

Refer to

https://grekai.wordpress.com/2011/03/31/httpcontext-current-user-identity-name-is-empty/

Get List of connected USB Devices

Adel Hazzah's answer gives working code, Daniel Widdis's and Nedko's comments mention that you need to query Win32_USBControllerDevice and use its Dependent property, and Daniel's answer gives a lot of detail without code.

Here's a synthesis of the above discussion to provide working code that lists the directly accessible PNP device properties of all connected USB devices:

using System;
using System.Collections.Generic;
using System.Management; // reference required

namespace cSharpUtilities
{
    class UsbBrowser
    {

        public static void PrintUsbDevices()
        {
            IList<ManagementBaseObject> usbDevices = GetUsbDevices();

            foreach (ManagementBaseObject usbDevice in usbDevices)
            {
                Console.WriteLine("----- DEVICE -----");
                foreach (var property in usbDevice.Properties)
                {
                    Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
                }
                Console.WriteLine("------------------");
            }
        }

        public static IList<ManagementBaseObject> GetUsbDevices()
        {
            IList<string> usbDeviceAddresses = LookUpUsbDeviceAddresses();

            List<ManagementBaseObject> usbDevices = new List<ManagementBaseObject>();

            foreach (string usbDeviceAddress in usbDeviceAddresses)
            {
                // query MI for the PNP device info
                // address must be escaped to be used in the query; luckily, the form we extracted previously is already escaped
                ManagementObjectCollection curMoc = QueryMi("Select * from Win32_PnPEntity where PNPDeviceID = " + usbDeviceAddress);
                foreach (ManagementBaseObject device in curMoc)
                {
                    usbDevices.Add(device);
                }
            }

            return usbDevices;
        }

        public static IList<string> LookUpUsbDeviceAddresses()
        {
            // this query gets the addressing information for connected USB devices
            ManagementObjectCollection usbDeviceAddressInfo = QueryMi(@"Select * from Win32_USBControllerDevice");

            List<string> usbDeviceAddresses = new List<string>();

            foreach(var device in usbDeviceAddressInfo)
            {
                string curPnpAddress = (string)device.GetPropertyValue("Dependent");
                // split out the address portion of the data; note that this includes escaped backslashes and quotes
                curPnpAddress = curPnpAddress.Split(new String[] { "DeviceID=" }, 2, StringSplitOptions.None)[1];

                usbDeviceAddresses.Add(curPnpAddress);
            }

            return usbDeviceAddresses;
        }

        // run a query against Windows Management Infrastructure (MI) and return the resulting collection
        public static ManagementObjectCollection QueryMi(string query)
        {
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection result = managementObjectSearcher.Get();

            managementObjectSearcher.Dispose();
            return result;
        }

    }

}

You'll need to add exception handling if you want it. Consult Daniel's answer if you want to figure out the device tree and such.

Export table from database to csv file

Some ideas:

From SQL Server Management Studio

 1. Run a SELECT statement to filter your data
 2. Click on the top-left corner to select all rows
 3. Right-click to copy all the selected
 4. Paste the copied content on Microsoft Excel
 5. Save as CSV

Using SQLCMD (Command Prompt)

Example:

From the command prompt, you can run the query and export it to a file:

sqlcmd -S . -d DatabaseName -E -s, -W -Q "SELECT * FROM TableName" > C:\Test.csv

Do not quote separator use just -s, and not quotes -s',' unless you want to set quote as separator.

More information here: ExcelSQLServer

Notes:

  • This approach will have the "Rows affected" information in the bottom of the file, but you can get rid of this by using the "SET NOCOUNT ON" in the query itself.

  • You may run a stored procedure instead of the actual query (e.g. "EXEC Database.dbo.StoredProcedure")

  • You can use any programming language or even a batch file to automate this

Using BCP (Command Prompt)

Example:

bcp "SELECT * FROM Database.dbo.Table" queryout C:\Test.csv -c -t',' -T -S .\SQLEXPRESS

It is important to quote the comma separator as -t',' vs just -t,

More information here: bcp Utility

Notes:

  • As per when using SQLCMD, you can run stored procedures instead of the actual queries
  • You can use any programming language or a batch file to automate this

Hope this helps.

<> And Not In VB.NET

If you need to know if the variable exists use Is/IsNot Nothing.

Using <> requires that the variable you're evaluating have the "<>" operator defined. Check out

 Dim b As HttpContext
 If b <> Nothing Then
    ...
 End If

and the resultant error

Error   1   Operator '<>' is not defined for types 'System.Web.HttpContext' and 'System.Web.HttpContext'.   

Frequency table for a single variable

You can use list comprehension on a dataframe to count frequencies of the columns as such

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]

Breakdown:

my_series.select_dtypes(include=['O']) 

Selects just the categorical data

list(my_series.select_dtypes(include=['O']).columns) 

Turns the columns from above into a list

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)] 

Iterates through the list above and applies value_counts() to each of the columns

Append column to pandas dataframe

Both join() and concat() way could solve the problem. However, there is one warning I have to mention: Reset the index before you join() or concat() if you trying to deal with some data frame by selecting some rows from another DataFrame.

One example below shows some interesting behavior of join and concat:

dat1 = pd.DataFrame({'dat1': range(4)})
dat2 = pd.DataFrame({'dat2': range(4,8)})
dat1.index = [1,3,5,7]
dat2.index = [2,4,6,8]

# way1 join 2 DataFrames
print(dat1.join(dat2))
# output
   dat1  dat2
1     0   NaN
3     1   NaN
5     2   NaN
7     3   NaN

# way2 concat 2 DataFrames
print(pd.concat([dat1,dat2],axis=1))
#output
   dat1  dat2
1   0.0   NaN
2   NaN   4.0
3   1.0   NaN
4   NaN   5.0
5   2.0   NaN
6   NaN   6.0
7   3.0   NaN
8   NaN   7.0

#reset index 
dat1 = dat1.reset_index(drop=True)
dat2 = dat2.reset_index(drop=True)
#both 2 ways to get the same result

print(dat1.join(dat2))
   dat1  dat2
0     0     4
1     1     5
2     2     6
3     3     7


print(pd.concat([dat1,dat2],axis=1))
   dat1  dat2
0     0     4
1     1     5
2     2     6
3     3     7

Javascript: Load an Image from url and display

When the button is clicked, get the value of the input and use it to create an image element which is appended to the body (or anywhere else) :

<html>
<body>
<form>
    <input type="text" id="imagename" value="" />
    <input type="button" id="btn" value="GO" />
</form>
    <script type="text/javascript">
        document.getElementById('btn').onclick = function() {
            var val = document.getElementById('imagename').value,
                src = 'http://webpage.com/images/' + val +'.png',
                img = document.createElement('img');

            img.src = src;
            document.body.appendChild(img);
        }
    </script>
</body>
</html>

FIDDLE

the same in jQuery:

$('#btn').on('click', function() {
    var img = $('<img />', {src : 'http://webpage.com/images/' + $('#imagename').val() +'.png'});
    img.appendTo('body');
});

Copying data from one SQLite database to another

If you use DB Browser for SQLite, you can copy the table from one db to another in following steps:

  1. Open two instances of the app and load the source db and target db side by side.
  2. If the target db does not have the table, "Copy Create Statement" from the source db and then paste the sql statement in "Execute SQL" tab and run the sql to create the table.
  3. In the source db, export the table as a CSV file.
  4. In the target db, import the CSV file to the table with the same table name. The app will ask you do you want to import the data to the existing table, click yes. Done.

How to make sure that a certain Port is not occupied by any other process

netstat -ano|find ":port_no" will give you the list.
a: Displays all connections and listening ports.
n: Displays addresses and port numbers in numerical form.
o: Displays the owning process ID associated with each connection .

example : netstat -ano | find ":1900" This gives you the result like this.

UDP    107.109.121.196:1900   *:*                                    1324  
UDP    127.0.0.1:1900         *:*                                    1324  
UDP    [::1]:1900             *:*                                    1324  
UDP    [fe80::8db8:d9cc:12a8:2262%13]:1900  *:*                      1324

Using two values for one switch case statement

The brackets are unnecessary. Just do

case text1:
case text4:
  doSomethingHere();
  break;
case text2:
  doSomethingElse()
  break;

If anyone is curious, this is called a case fallthrough. The ability to do this is the reason why break; is necessary to end case statements. For more information, see the wikipedia article http://en.wikipedia.org/wiki/Switch_statement.

TERM environment variable not set

Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.

x86 Assembly on a Mac

After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with.

You'll also want to take a look at the Compiler & Debugging Guides, because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to.

Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next.

Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations.

Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days.

what's the differences between r and rb in fopen

This makes a difference on Windows, at least. See that link for details.

How to add a custom right-click menu to a webpage?

I use something similar to the following jsfiddle

function onright(el, cb) {
    //disable right click
    document.body.oncontextmenu = 'return false';
    el.addEventListener('contextmenu', function (e) { e.preventDefault(); return false });
    el.addEventListener('mousedown', function (e) {
        e = e || window.event;
        if (~~(e.button) === 2) {
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
            return false;
        }
    });

    // then bind Your cb
    el.addEventListener('mousedown', function (e) {
        e = e || window.event;
        ~~(e.button) === 2 && cb.call(el, e);
    });
}

if You target older IE browsers you should anyway complete it with the ' attachEvent; case

jQuery How do you get an image to fade in on load?

OK so I did this and it works. It's basically hacked together from different responses here. Since there is STILL not a clear answer in this thread I decided to post this.

<script type="text/javascript">
  $(document).ready(function () {
    $("#logo").hide();
    $("#logo").bind("load", function () { $(this).fadeIn(); });
  });
</script>

This seems to me to be the best way to go about it. Despite Sohnee's best intentions he failed to mention that the object must first be set to display:none with CSS. The problem here is that if for what ever reason the user's JS is not working the object will just never appear. Not good, especially if it's the frikin' logo.

This solution leaves the item alone in the CSS, and first hides, then fades it in all using JS. This way if JS is not working properly the item will just load as normal.

Hope that helps anyone else who stumbles into this google ranked #1 not-so-helpful thread.

Can a unit test project load the target application's app.config file?

If you application is using setting such as Asp.net ConnectionString you need to add the attribute HostType to your method, else they wont load even if you have an App.Config file.

[TestMethod]
[HostType("ASP.NET")] // will load the ConnectionString from the App.Config file
public void Test() {

}

ping response "Request timed out." vs "Destination Host unreachable"

Destination Host Unreachable

This message indicates one of two problems: either the local system has no route to the desired destination, or a remote router reports that it has no route to the destination.

If the message is simply "Destination Host Unreachable," then there is no route from the local system, and the packets to be sent were never put on the wire.

If the message is "Reply From < IP address >: Destination Host Unreachable," then the routing problem occurred at a remote router, whose address is indicated by the "< IP address >" field.

Request Timed Out

This message indicates that no Echo Reply messages were received within the default time of 1 second. This can be due to many different causes; the most common include network congestion, failure of the ARP request, packet filtering, routing error, or a silent discard.

For more info Refer: http://technet.microsoft.com/en-us/library/cc940095.aspx

How to store a large (10 digits) integer?

you can use long or double.

ALTER COLUMN in sqlite

While it is true that the is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of dangerous commands:

PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;

You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.

For example:

Y:\> **sqlite3 booktest**  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> **create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT 
NULL);**  
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
Error: BOOKS.publication_date may not be NULL  
sqlite> **PRAGMA writable_schema = 1;**  
sqlite> **UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT 
NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';**  
sqlite> **PRAGMA writable_schema = 0;**  
sqlite> **.q**  

Y:\> **sqlite3 booktest**  
SQLite version 3.7.4  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";"  
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
sqlite> **.q**  

REFERENCES FOLLOW:


pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.

[alter table](From http://www.sqlite.org/lang_altertable.html)
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

ALTER TABLE SYNTAX

Global npm install location on windows?

According to: https://docs.npmjs.com/files/folders

  • Local install (default): puts stuff in ./node_modules of the current package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.

prefix Configuration

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary.

The docs might be a little outdated, but they explain why global installs can end up in different directories:

(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"

Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.

This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):

mkdir %PROGRAMDATA%\npm
setx PATH "%PROGRAMDATA%\npm;%PATH%" /M
npm config set prefix %PROGRAMDATA%\npm

open a new cmd.exe window and reinstall all global packages.

Explanation (by lineno.):

  1. Create a folder in a sensible location to hold the globals (Microsoft is adamant that you shouldn't write to ProgramFiles, so %PROGRAMDATA% seems like the next logical place.
  2. The directory needs to be on the path, so use setx .. /M to set the system path (under HKEY_LOCAL_MACHINE). This is what requires you to run this in a shell with administrator permissions.
  3. Tell npm to use this new path. (Note: folder isn't visible in %PATH% in this shell, so you must open a new window).

How to install a certificate in Xcode (preparing for app store submission)

These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)

a) Part on the developers' website:

Sign in into: https://developer.apple.com/

Member Center

Certificates, Identifiers & Profiles

Certificates>All

Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.

b) XCode part:

After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

ImportError: No Module named simplejson

That means you must install simplejson. On newer versions of python, it was included by default into python's distribution, and renamed to json. So if you are on python 2.6+ you should change all instances of simplejson to json.

For a quick fix you could also edit the file and change the line:

import simplejson

to:

import json as simplejson

and hopefully things will work.

Change location of log4j.properties

In Eclipse you can set a VM argument to:

-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}

Automating running command on Linux from Windows using PuTTY

Putty usually comes with the "plink" utility.
This is essentially the "ssh" command line command implemented as a windows .exe.
It pretty well documented in the putty manual under "Using the command line tool plink".

You just need to wrap a command like:

plink root@myserver /etc/backups/do-backup.sh

in a .bat script.

You can also use common shell constructs, like semicolons to execute multiple commands. e.g:

plink read@myhost ls -lrt /home/read/files;/etc/backups/do-backup.sh

Why is "except: pass" a bad programming practice?

You should use at least except Exception: to avoid catching system exceptions like SystemExit or KeyboardInterrupt. Here's link to docs.

In general you should define explicitly exceptions you want to catch, to avoid catching unwanted exceptions. You should know what exceptions you ignore.

T-SQL CASE Clause: How to specify WHEN NULL

I tried casting to a string and testing for a zero-length string and it worked.

CASE 
   WHEN LEN(CAST(field_value AS VARCHAR(MAX))) = 0 THEN 
       DO THIS
END AS field 

PIL image to array (numpy array to array) - Python

Based on zenpoy's answer:

import Image
import numpy

def image2pixelarray(filepath):
    """
    Parameters
    ----------
    filepath : str
        Path to an image file

    Returns
    -------
    list
        A list of lists which make it simple to access the greyscale value by
        im[y][x]
    """
    im = Image.open(filepath).convert('L')
    (width, height) = im.size
    greyscale_map = list(im.getdata())
    greyscale_map = numpy.array(greyscale_map)
    greyscale_map = greyscale_map.reshape((height, width))
    return greyscale_map

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

Setting Windows PowerShell environment variables

Most answers aren't addressing UAC. This covers UAC issues.

First install PowerShell Community Extensions: choco install pscx via http://chocolatey.org/ (you may have to restart your shell environment).

Then enable pscx

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx

Then use Invoke-Elevated

Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR

Bi-directional Map in Java?

Use Google's BiMap

It is more convenient.

Android ImageView's onClickListener does not work

I defined an OnClickListener for ImageView as an OnClickListener for a button and it seems to be working fine. Here's what I had. Please try and let us know if it doesn't work.

final ImageView imageview1 = (ImageView) findViewById(R.id.imageView1);

imageview1.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        try {
             Log.i("MyTag","Image button is pressed, visible in LogCat");;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }
});

REST API Best practices: Where to put parameters?

IMO the parameters should be better as query arguments. The url is used to identify the resource, while the added query parameters to specify which part of the resource you want, any state the resource should have, etc.

For files in directory, only echo filename (no path)

Use basename:

echo $(basename /foo/bar/stuff)

Change the "From:" address in Unix "mail"

In my version of mail ( Debian linux 4.0 ) the following options work for controlling the source / reply addresses

  • the -a switch, for additional headers to apply, supplying a From: header on the command line that will be appended to the outgoing mail header
  • the $REPLYTO environment variable specifies a Reply-To: header

so the following sequence

export [email protected]
mail -aFrom:[email protected] -s 'Testing'

The result, in my mail clients, is a mail from [email protected], which any replies to will default to [email protected]

NB: Mac OS users: you don't have -a , but you do have $REPLYTO

NB(2): CentOS users, many commenters have added that you need to use -r not -a

NB(3): This answer is at least ten years old(1), please bear that in mind when you're coming in from Google.

How to find nth occurrence of character in a string?

This answer improves on @aioobe 's answer. Two bugs in that answer were fixed.
1. n=0 should return -1.
2. nth occurence returned -1, but it worked on n-1th occurences.

Try this !

    public int nthOccurrence(String str, char c, int n) {
    if(n <= 0){
        return -1;
    }
    int pos = str.indexOf(c, 0);
    while (n-- > 1 && pos != -1)
        pos = str.indexOf(c, pos+1);
    return pos;
}

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

The Date object is used to work with dates and times.

Date objects are created with new Date().

var date= new Date();

 function myFunction() {
        var currentTime = new Date();
        Logger.log(currentTime);
    }

How do I set a fixed background image for a PHP file?

I found my answer.

<?php
$profpic = "bg.jpg";
?>

<html>
<head>
<style type="text/css">

body {
background-image: url('<?php echo $profpic;?>');
}
</style>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>

Contains case insensitive

If referrer is an array, you can use findIndex()

 if(referrer.findIndex(item => 'ral' === item.toLowerCase()) == -1) {...}

Determining the current foreground application from a background task or service

I combined two solutions in one method and it works for me for API 24 and for API 21. Others I didn't test.

The code in Kotlin:

private fun isAppInForeground(context: Context): Boolean {
    val appProcessInfo = ActivityManager.RunningAppProcessInfo()
    ActivityManager.getMyMemoryState(appProcessInfo)
    if (appProcessInfo.importance == IMPORTANCE_FOREGROUND ||
            appProcessInfo.importance == IMPORTANCE_VISIBLE) {
        return true
    } else if (appProcessInfo.importance == IMPORTANCE_TOP_SLEEPING ||
            appProcessInfo.importance == IMPORTANCE_BACKGROUND) {
        return false
    }

    val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val foregroundTaskInfo = am.getRunningTasks(1)[0]
    val foregroundTaskPackageName = foregroundTaskInfo.topActivity.packageName
    return foregroundTaskPackageName.toLowerCase() == context.packageName.toLowerCase()
}

and in Manifest

<!-- Check whether app in background or foreground -->
<uses-permission android:name="android.permission.GET_TASKS" />

Getting individual colors from a color map in matplotlib

I had precisely this problem, but I needed sequential plots to have highly contrasting color. I was also doing plots with a common sub-plot containing reference data, so I wanted the color sequence to be consistently repeatable.

I initially tried simply generating colors randomly, reseeding the RNG before each plot. This worked OK (commented-out in code below), but could generate nearly indistinguishable colors. I wanted highly contrasting colors, ideally sampled from a colormap containing all colors.

I could have as many as 31 data series in a single plot, so I chopped the colormap into that many steps. Then I walked the steps in an order that ensured I wouldn't return to the neighborhood of a given color very soon.

My data is in a highly irregular time series, so I wanted to see the points and the lines, with the point having the 'opposite' color of the line.

Given all the above, it was easiest to generate a dictionary with the relevant parameters for plotting the individual series, then expand it as part of the call.

Here's my code. Perhaps not pretty, but functional.

from matplotlib import cm
cmap = cm.get_cmap('gist_rainbow')  #('hsv') #('nipy_spectral')

max_colors = 31   # Constant, max mumber of series in any plot.  Ideally prime.
color_number = 0  # Variable, incremented for each series.

def restart_colors():
    global color_number
    color_number = 0
    #np.random.seed(1)

def next_color():
    global color_number
    color_number += 1
    #color = tuple(np.random.uniform(0.0, 0.5, 3))
    color = cmap( ((5 * color_number) % max_colors) / max_colors )
    return color

def plot_args():  # Invoked for each plot in a series as: '**(plot_args())'
    mkr = next_color()
    clr = (1 - mkr[0], 1 - mkr[1], 1 - mkr[2], mkr[3])  # Give line inverse of marker color
    return {
        "marker": "o",
        "color": clr,
        "mfc": mkr,
        "mec": mkr,
        "markersize": 0.5,
        "linewidth": 1,
    }

My context is JupyterLab and Pandas, so here's sample plot code:

restart_colors()  # Repeatable color sequence for every plot

fig, axs = plt.subplots(figsize=(15, 8))
plt.title("%s + T-meter"%name)

# Plot reference temperatures:
axs.set_ylabel("°C", rotation=0)
for s in ["T1", "T2", "T3", "T4"]:
    df_tmeter.plot(ax=axs, x="Timestamp", y=s, label="T-meter:%s" % s, **(plot_args()))

# Other series gets their own axis labels
ax2 = axs.twinx()
ax2.set_ylabel(units)

for c in df_uptime_sensors:
    df_uptime[df_uptime["UUID"] == c].plot(
        ax=ax2, x="Timestamp", y=units, label="%s - %s" % (units, c), **(plot_args())
    )

fig.tight_layout()
plt.show()

The resulting plot may not be the best example, but it becomes more relevant when interactively zoomed in. uptime + T-meter

Using variable in SQL LIKE statement

Joel is it that @SearchLetter hasn't been declared yet? Also the length of @SearchLetter2 isn't long enough for 't%'. Try a varchar of a longer length.

How to get just the parent directory name of a specific file

Use below,

File file = new File("file/path");
String parentPath = file.getAbsoluteFile().getParent();

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

What is syntax for selector in CSS for next element?

This is called the adjacent sibling selector, and it is represented by a plus sign...

h1.hc-reform + p {
  clear:both;
}

Note: this is not supported in IE6 or older.

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

I tested various combinations of android:background, android:backgroundTint and android:backgroundTintMode.

android:backgroundTint applies the color filter to the resource of android:background when used together with android:backgroundTintMode.

Here are the results:

Tint Check

Here's the code if you want to experiment further:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:text="Background" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:backgroundTint="#FEFBDE"
        android:text="Background tint" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:backgroundTint="#FEFBDE"
        android:text="Both together" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:backgroundTint="#FEFBDE"
        android:backgroundTintMode="multiply"
        android:text="With tint mode" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:text="Without any" />
</LinearLayout>

Difference between return 1, return 0, return -1 and exit?

As explained here, in the context of main both return and exit do the same thing

Q: Why do we need to return or exit?

A: To indicate execution status.

In your example even if you didnt have return or exit statements the code would run fine (Assuming everything else is syntactically,etc-ally correct. Also, if (and it should be) main returns int you need that return 0 at the end).

But, after execution you don't have a way to find out if your code worked as expected. You can use the return code of the program (In *nix environments , using $?) which gives you the code (as set by exit or return) . Since you set these codes yourself you understand at which point the code reached before terminating.

You can write return 123 where 123 indicates success in the post execution checks.

Usually, in *nix environments 0 is taken as success and non-zero codes as failures.

What does the 'b' character do in front of a string literal?

Python 3.x makes a clear distinction between the types:

If you're familiar with:

  • Java or C#, think of str as String and bytes as byte[];
  • SQL, think of str as NVARCHAR and bytes as BINARY or BLOB;
  • Windows registry, think of str as REG_SZ and bytes as REG_BINARY.

If you're familiar with C(++), then forget everything you've learned about char and strings, because a character is not a byte. That idea is long obsolete.

You use str when you want to represent text.

print('???? ????')

You use bytes when you want to represent low-level binary data like structs.

NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]

You can encode a str to a bytes object.

>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'

And you can decode a bytes into a str.

>>> b'\xE2\x82\xAC'.decode('UTF-8')
'€'

But you can't freely mix the two types.

>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str

The b'...' notation is somewhat confusing in that it allows the bytes 0x01-0x7F to be specified with ASCII characters instead of hex numbers.

>>> b'A' == b'\x41'
True

But I must emphasize, a character is not a byte.

>>> 'A' == b'A'
False

In Python 2.x

Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:

  • unicode = u'...' literals = sequence of Unicode characters = 3.x str
  • str = '...' literals = sequences of confounded bytes/characters
    • Usually text, encoded in some unspecified encoding.
    • But also used to represent binary data like struct.pack output.

In order to ease the 2.x-to-3.x transition, the b'...' literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes in 3.x) from text strings (which should be str in 3.x). The b prefix does nothing in 2.x, but tells the 2to3 script not to convert it to a Unicode string in 3.x.

So yes, b'...' literals in Python have the same purpose that they do in PHP.

Also, just out of curiosity, are there more symbols than the b and u that do other things?

The r prefix creates a raw string (e.g., r'\t' is a backslash + t instead of a tab), and triple quotes '''...''' or """...""" allow multi-line string literals.

Putting -moz-available and -webkit-fill-available in one width (css property)

CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit-prefixed declarations, and WebKit-based browsers will not understand -moz-prefixed declarations.

Because of this, we can simply declare width twice:

elem {
    width: 100%;
    width: -moz-available;          /* WebKit-based browsers will ignore this. */
    width: -webkit-fill-available;  /* Mozilla-based browsers will ignore this. */
    width: fill-available;
}

The width: 100% declared at the start will be used by browsers which ignore both the -moz and -webkit-prefixed declarations or do not support -moz-available or -webkit-fill-available.

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

onclick event pass <li> id or value

Try this:

<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>


function getPaging(str)
{
    $("#loading-content").load("dataSearch.php?"+str, hideLoader);
}

Most useful NLog configurations

Log from Silverlight

When using NLog with Silverlight you can send the trace to the server side via the provided web service. You can also write to a local file in the Isolated Storage, which come in handy if the web server is unavailable. See here for details, i.e. use something like this to make yourself a target:

namespace NLogTargets
{
    [Target("IsolatedStorageTarget")]
    public sealed class IsolatedStorageTarget : TargetWithLayout
    {
        IsolatedStorageFile _storageFile = null;
        string _fileName = "Nlog.log"; // Default. Configurable through the 'filename' attribute in nlog.config

        public IsolatedStorageTarget()
        {
        }

        ~IsolatedStorageTarget()
        {
            if (_storageFile != null)
            {
                _storageFile.Dispose();
                _storageFile = null;
            }
        }

        public string filename
        {
            set
            {
                _fileName = value; 
            }
            get
            {
                return _fileName;  
            }
         }

        protected override void Write(LogEventInfo logEvent)
        {
            try
            {
                writeToIsolatedStorage(this.Layout.Render(logEvent));
            }
            catch (Exception e)
            {
                // Not much to do about his....
            }
        }

        public void writeToIsolatedStorage(string msg)
        {
            if (_storageFile == null)
                _storageFile = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // The isolated storage is limited in size. So, when approaching the limit
                // simply purge the log file. (Yeah yeah, the file should be circular, I know...)
                if (_storageFile.AvailableFreeSpace < msg.Length * 100)
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, FileMode.Truncate, FileAccess.Write, isolatedStorage))
                    { }
                }
                // Write to isolated storage
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, FileMode.Append, FileAccess.Write, isolatedStorage))
                {
                    using (TextWriter writer = new StreamWriter(stream))
                    {
                        writer.WriteLine(msg);
                    }
                }
            }
        }
    } 
}

.ssh/config file for windows (git)

These instructions work fine in Linux. In Windows, they are not working for me today.

I found an answer that helps for me, maybe this will help OP. I kissed a lot of frogs trying to solve this. You need to add your new non-standard-named key file with "ssh-add"! Here's instruction for the magic bullet: Generating a new SSH key and adding it to the ssh-agent. Once you know the magic search terms are "add key with ssh-add in windows" you find plenty of other links.

If I were using Windows often, I'd find some way to make this permanent. https://github.com/raeesbhatti/ssh-agent-helper.

The ssh key agent looks for default "id_rsa" and other keys it knows about. The key you create with a non-standard name must be added to the ssh key agent.

First, I start the key agent in the Git BASH shell:

$ eval $(ssh-agent -s)
Agent pid 6276

$ ssh-add ~/.ssh/Paul_Johnson-windowsvm-20180318
Enter passphrase for /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318:
Identity added: /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318 (/c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318)

Then I change to the directory where I want to clone the repo

$ cd ~/Documents/GIT/

$ git clone [email protected]:test/spr2018.git
Cloning into 'spr2018'...
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.

I fought with this for a long long time.

Here are other things I tried along the way

At first I was certain it is because of file and folder permissions. On Linux, I have seen .ssh settings rejected if the folder is not set at 700. Windows has 711. In Windows, I cannot find any way to make permissions 700.

After fighting with that, I think it must not be the problem. Here's why. If the key is named "id_rsa" then git works! Git is able to connect to server. However, if I name the key file something else, and fix the config file in a consistent way, no matter what, then git fails to connect. That makes me think permissions are not the problem.

A thing you can do to debug this problem is to watch verbose output from ssh commands using the configured key.

In the git bash shell, run this

$ ssh -T git@name-of-your-server

Note, the user name should be "git" here. If your key is set up and the config file is found, you see this, as I just tested in my Linux system:

$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!

On the other hand, in Windows I have same trouble you do before applying "ssh-add". It wants git's password, which is always a fail.

$ ssh -T [email protected]
[email protected]'s password:

Again, If i manually copy my key to "id_rsa" and "id_rsa.pub", then this works fine. After running ssh-add, observe the victory in Windows Git BASH:

$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!

You would hear the sound of me dancing with joy if you were here.

To figure out what was going wrong, you can I run 'ssh' with "-Tvv"

In Linux, I see this when it succeeds:

debug1: Offering RSA public key: pauljohn@pols124
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug2: input_userauth_pk_ok: fp SHA256:bCoIWSXE5fkOID4Kj9Axt2UOVsRZz9JW91RQDUoasVo
debug1: Authentication succeeded (publickey).

In Windows, when this fails, I see it looking for default names:

debug1: Found key in /c/Users/pauljohn32/.ssh/known_hosts:1
debug2: set_newkeys: mode 1
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 4294967296 blocks
debug2: key: /c/Users/pauljohn32/.ssh/id_rsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_dsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ecdsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ed25519 (0x0)
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_rsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_dsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ecdsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ed25519
debug2: we did not send a packet, disable method
debug1: Next authentication method: password
[email protected]'s password:

That was the hint I needed, it says it finds my ~/.ssh/config file but never tries the key I want it to try.

I only use Windows once in a long while and it is frustrating. Maybe the people who use Windows all the time fix this and forget it.

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

You can also specify a commit hash (often also called commit ID) with the git show command.


In a nutshell

git show <commitHash>:/path/to/file


Step by step

  1. Show the log of all the changes for a given file with git log /path/to/file
  2. In the list of changes shown, it shows the commit hash such as commit 06c98... (06c98... being the commit hash)
  3. Copy the commit hash
  4. Run the command git show <commitHash>:/path/to/file using the commit hashof step 3 & the path/to/file of step 1.

Note: adding the ./ when specifying a relative path seems important, i.e. git show b2f8be577166577c59b55e11cfff1404baf63a84:./flight-simulation/src/main/components/nav-horiz.html.

How to print GETDATE() in SQL Server with milliseconds in time?

these 2 are the same:

Print CAST(GETDATE() as Datetime2 (3) )
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))

enter image description here

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

There second method will be many times more effective (mostly because of compilers inlining and boxing but still numbers are very expressive):

public static bool CheckObjectImpl(object o)
{
    return o != null;
}

public static bool CheckNullableImpl<T>(T? o) where T: struct
{
    return o.HasValue;
}

Benchmark test:

BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
  [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Clr    : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Core   : .NET Core 4.6.25009.03, 64bit RyuJIT


        Method |  Job | Runtime |       Mean |     Error |    StdDev |        Min |        Max |     Median | Rank |  Gen 0 | Allocated |
-------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
   CheckObject |  Clr |     Clr | 80.6416 ns | 1.1983 ns | 1.0622 ns | 79.5528 ns | 83.0417 ns | 80.1797 ns |    3 | 0.0060 |      24 B |
 CheckNullable |  Clr |     Clr |  0.0029 ns | 0.0088 ns | 0.0082 ns |  0.0000 ns |  0.0315 ns |  0.0000 ns |    1 |      - |       0 B |
   CheckObject | Core |    Core | 77.2614 ns | 0.5703 ns | 0.4763 ns | 76.4205 ns | 77.9400 ns | 77.3586 ns |    2 | 0.0060 |      24 B |
 CheckNullable | Core |    Core |  0.0007 ns | 0.0021 ns | 0.0016 ns |  0.0000 ns |  0.0054 ns |  0.0000 ns |    1 |      - |       0 B |

Benchmark code:

public class BenchmarkNullableCheck
{
    static int? x = (new Random()).Next();

    public static bool CheckObjectImpl(object o)
    {
        return o != null;
    }

    public static bool CheckNullableImpl<T>(T? o) where T: struct
    {
        return o.HasValue;
    }

    [Benchmark]
    public bool CheckObject()
    {
        return CheckObjectImpl(x);
    }

    [Benchmark]
    public bool CheckNullable()
    {
        return CheckNullableImpl(x);
    }
}

https://github.com/dotnet/BenchmarkDotNet was used

So if you have an option (e.g. writing custom serializers) to process Nullable in different pipeline than object - and use their specific properties - do it and use Nullable specific properties. So from consistent thinking point of view HasValue should be preferred. Consistent thinking can help you to write better code do not spending too much time in details.

PS. People say that advice "prefer HasValue because of consistent thinking" is not related and useless. Can you predict the performance of this?

public static bool CheckNullableGenericImpl<T>(T? t) where T: struct
{
    return t != null; // or t.HasValue?
}

PPS People continue minus, seems nobody tries to predict performance of CheckNullableGenericImpl. I will tell you: there compiler will not help you replacing !=null with HasValue. HasValue should be used directly if you are interested in performance.

How to check certificate name and alias in keystore files?

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

keytool -v -list -keystore .keystore

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

keytool -list -keystore .keystore -alias foo

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

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

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

Difference between Inheritance and Composition

Inheritance between two classes, where one class extends another class establishes "IS A" relationship.

Composition on the other end contains an instance of another class in your class establishes "Has A" relationship. Composition in java is is useful since it technically facilitates multiple inheritance.

How to find out line-endings in a text file?

In the bash shell, try cat -v <filename>. This should display carriage-returns for windows files.

(This worked for me in rxvt via Cygwin on Windows XP).

Editor's note: cat -v visualizes \r (CR) chars. as ^M. Thus, line-ending \r\n sequences will display as ^M at the end of each output line. cat -e will additionally visualize \n, namely as $. (cat -et will additionally visualize tab chars. as ^I.)

Calling Java from Python

You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:

from py4j.java_gateway import JavaGateway
gateway = JavaGateway()                        # connect to the JVM
java_object = gateway.jvm.mypackage.MyClass()  # invoke constructor
other_object = java_object.doThat()
other_object.doThis(1,'abc')
gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.

The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)

Disclaimer: I am the author of Py4J

how to make label visible/invisible?

Change visible="false" to style="visibility:hidden" on your tags..


or better use a class to show/hide the labels..

.hidden{
   visibility:hidden;
}

then on your labels add class="hidden"

and with your script remove the class

document.getElementById("endTimeLabel").className = 'hidden'; // to hide

and

document.getElementById("endTimeLabel").className = ''; // to show

How do I call a dynamically-named method in Javascript?

A simple function to call a function dynamically with parameters:

this.callFunction = this.call_function = function(name) {
    var args = Array.prototype.slice.call(arguments, 1);
    return window[name].call(this, ...args);
};

function sayHello(name, age) {
    console.log('hello ' + name + ', your\'e age is ' + age);
    return some;
}

console.log(call_function('sayHello', 'john', 30)); // hello john, your'e age is 30

Better way to sort array in descending order

Yes, you can pass predicate to sort. That would be your reverse implementation.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

With default Github repository import it is possible, but just make sure the two factor authentication is not enabled in Gitlab.

Thanks

On npm install: Unhandled rejection Error: EACCES: permission denied

Restore ownership of the user's npm related folders, to the current user, like this:

sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config