Programs & Examples On #Typed dataset

Where is svcutil.exe in Windows 7?

If you are using vs 2010 then you can get it in

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools

How to use random in BATCH script?

You'll probably want to get several random numbers, and may want to be able to specify a different range for each one, so you should define a function. In my example, I generate numbers from 25 through 30 with call:rand 25 30. And the result is in RAND_NUM after that function exits.

@echo off & setlocal EnableDelayedExpansion

for /L %%a in (1 1 10) do (
        call:rand 25 30
        echo !RAND_NUM!
)

goto:EOF

REM The script ends at the above goto:EOF.  The following are functions.

REM rand()
REM Input: %1 is min, %2 is max.
REM Output: RAND_NUM is set to a random number from min through max.
:rand
SET /A RAND_NUM=%RANDOM% * (%2 - %1 + 1) / 32768 + %1
goto:EOF

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

You might looking for the placeholder attribute which will display a grey text in the input field while empty.

From Mozilla Developer Network:

A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.

However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )

And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/

Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/

SSIS cannot convert because a potential loss of data

I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.

Solution

To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.

Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.

This will work.

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

You dont need both jTDS and JDBC in your classpath. Any one is required. Here you need only sqljdbc.jar.

Also, I would suggest to place sqljdbc.jar at physical location to /WEB-INF/lib directory of your project rather than adding it in the Classpath via IDE. Then Tomcat takes care the rest. And also try restarting Tomcat.

You can download Jar from : www.java2s.com/Code/JarDownload/sqlserverjdbc/sqlserverjdbc.jar.zip

EDIT:

As you are supplying Username and Password when connecting,

You need only jdbc:sqlserver://localhost:1433;databaseName=test, Skip integratedSecurity attribute.

Converting a column within pandas dataframe from int to string

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))

In [17]: df
Out[17]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [18]: df.dtypes
Out[18]: 
A    int64
B    int64
dtype: object

Convert a series

In [19]: df['A'].apply(str)
Out[19]: 
0    0
1    2
2    4
3    6
4    8
Name: A, dtype: object

In [20]: df['A'].apply(str)[0]
Out[20]: '0'

Don't forget to assign the result back:

df['A'] = df['A'].apply(str)

Convert the whole frame

In [21]: df.applymap(str)
Out[21]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'

df = df.applymap(str)

how to save canvas as png image?

I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:

function download(){
        var download = document.getElementById("download");
        var image = document.getElementById("canvas").toDataURL("image/png")
                    .replace("image/png", "image/octet-stream");
        download.setAttribute("href", image);

    }

In the body part of your HTML specify the button:

<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>

This is working and download link looks like a button. Tested in Firefox and Chrome.

How to read a .xlsx file using the pandas Library in iPython?

If you use read_excel() on a file opened using the function open(), make sure to add rb to the open function to avoid encoding errors

How do I check if an index exists on a table field in MySQL?

SHOW KEYS FROM  tablename WHERE Key_name='unique key name'

you can find if there exists an unique key in the table

Adding three months to a date in PHP

Following should work

$d = strtotime("+1 months",strtotime("2015-05-25"));
echo   date("Y-m-d",$d); // This will print **2015-06-25** 

How to mock a final class with mockito

This can be done if you are using Mockito2, with the new incubating feature which supports mocking of final classes & methods.

Key points to note:
1. Create a simple file with the name “org.mockito.plugins.MockMaker” and place it in a folder named “mockito-extensions”. This folder should be made available on the classpath.
2. The content of the file created above should be a single line as given below:
mock-maker-inline

The above two steps are required in order to activate the mockito extension mechanism and use this opt-in feature.

Sample classes are as follows:-

FinalClass.java

public final class FinalClass {

public final String hello(){
    System.out.println("Final class says Hello!!!");
    return "0";
}

}

Foo.java

public class Foo {

public String executeFinal(FinalClass finalClass){
    return finalClass.hello();
}

}

FooTest.java

public class FooTest {

@Test
public void testFinalClass(){
    // Instantiate the class under test.
    Foo foo = new Foo();

    // Instantiate the external dependency
    FinalClass realFinalClass = new FinalClass();

    // Create mock object for the final class. 
    FinalClass mockedFinalClass = mock(FinalClass.class);

    // Provide stub for mocked object.
    when(mockedFinalClass.hello()).thenReturn("1");

    // assert
    assertEquals("0", foo.executeFinal(realFinalClass));
    assertEquals("1", foo.executeFinal(mockedFinalClass));

}

}

Hope it helps.

Complete article present here mocking-the-unmockable.

Repeat each row of data.frame the number of times specified in a column

old question, new verb in tidyverse:

library(tidyr) # version >= 0.8.0
df <- data.frame(var1=c('a', 'b', 'c'), var2=c('d', 'e', 'f'), freq=1:3)
df %>% 
  uncount(freq)

    var1 var2
1      a    d
2      b    e
2.1    b    e
3      c    f
3.1    c    f
3.2    c    f

Number of occurrences of a character in a string

Because LINQ can do everything...:

string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();

Or if you like, you can use the Count overload that takes a predicate :

var count = test.Count(x => x == '&');

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I updated Xcode to v8 and the error was resolved.

JS how to cache a variable

I have written a generic caching func() which will cache any variable easily and very readable format. Caching function:

function calculateSomethingMaybe(args){
  return args;
}

function caching(fn){
  const cache = {};
  return function(){
    const string = arguments[0];
    if(!cache[string]){
      const result = fn.apply(this, arguments);
      cache[string] = result;
      return result;
    }
    return cache[string];
  }
}

const letsCache = caching(calculateSomethingMaybe);

console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

If you are trying to configure this on 64bit, you have to do your DCOMconfig configuration (see other answers above) in:

C:\WINDOWS\SysWOW64>mmc comexp.msc /32

according to Setting Process-Wide Security Using DCOMCNFG.

After this, I was able to configure this for IIS_IUSRS without administrator privileges.

Copying text to the clipboard using Java

This is the accepted answer written in a decorative way:

Toolkit.getDefaultToolkit()
        .getSystemClipboard()
        .setContents(
                new StringSelection(txtMySQLScript.getText()),
                null
        );

How to change Maven local repository in eclipse

In Eclipse Photon navigate to Windows > Preferences > Maven > User Settings > User Setting

For "User settings" Browse to the settings.xml of the maven. ex. in my case maven it is located on the path C:\Program Files\Apache Software Distribution\apache-maven-3.5.4\conf\Settings.xml

Depending on the Settings.xml the Local Repository gets automatically configured to the specified location. Click here for screenshot

What is exactly the base pointer and stack pointer? To what do they point?

Long time since I've done Assembly programming, but this link might be useful...

The processor has a collection of registers which are used to store data. Some of these are direct values while others are pointing to an area within RAM. Registers do tend to be used for certain specific actions and every operand in assembly will require a certain amount of data in specific registers.

The stack pointer is mostly used when you're calling other procedures. With modern compilers, a bunch of data will be dumped first on the stack, followed by the return address so the system will know where to return once it's told to return. The stack pointer will point at the next location where new data can be pushed to the stack, where it will stay until it's popped back again.

Base registers or segment registers just point to the address space of a large amount of data. Combined with a second regiser, the Base pointer will divide the memory in huge blocks while the second register will point at an item within this block. Base pointers therefor point to the base of blocks of data.

Do keep in mind that Assembly is very CPU specific. The page I've linked to provides information about different types of CPU's.

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

It should be MM for months. You are asking for minutes.

DateTime.Now.ToString("dd/MM/yyyy");

See Custom Date and Time Format Strings on MSDN for details.

How to implement common bash idioms in Python?

If your textfile manipulation usually is one-time, possibly done on the shell-prompt, you will not get anything better from python.

On the other hand, if you usually have to do the same (or similar) task over and over, and you have to write your scripts for doing that, then python is great - and you can easily create your own libraries (you can do that with shell scripts too, but it's more cumbersome).

A very simple example to get a feeling.

import popen2
stdout_text, stdin_text=popen2.popen2("your-shell-command-here")
for line in stdout_text:
  if line.startswith("#"):
    pass
  else
    jobID=int(line.split(",")[0].split()[1].lstrip("<").rstrip(">"))
    # do something with jobID

Check also sys and getopt module, they are the first you will need.

How do I start an activity from within a Fragment?

I done it, below code is working for me....

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);

        Button newPage = (Button)v.findViewById(R.id.click);
        newPage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HomeActivity.class);
                startActivity(intent);
            }
        });
        return v;
    }

and Please make sure that your destination activity should be register in Manifest.xml file,

but in my case all tabs are not shown in HomeActivity, is any solution for that ?

docker container ssl certificates

I am trying to do something similar to this. As commented above, I think you would want to build a new image with a custom Dockerfile (using the image you pulled as a base image), ADD your certificate, then RUN update-ca-certificates. This way you will have a consistent state each time you start a container from this new image.

# Dockerfile
FROM some-base-image:0.1
ADD you_certificate.crt:/container/cert/path
RUN update-ca-certificates

Let's say a docker build against that Dockerfile produced IMAGE_ID. On the next docker run -d [any other options] IMAGE_ID, the container started by that command will have your certificate info. Simple and reproducible.

node.js: cannot find module 'request'

ReferenceError: Can't find variable: require.

You have installed "npm", you can run as normal the script to a "localhost" "127.0.0.1".

When you use the http.clientRequest() with "options" in a "npm" you need to install "RequireJS" inside of the module.

A module is any file or directory in the node_modules directory that can be loaded by the Node. Install "RequiereJS" for to make work the http.clientRequest(options).

Rendering HTML in a WebView with custom CSS

here is the solution

Put your html and css in your /assets/ folder, then load the html file like so:

    WebView wv = new WebView(this);

    wv.loadUrl("file:///android_asset/yourHtml.html");

then in your html you can reference your css in the usual way

<link rel="stylesheet" type="text/css" href="main.css" />

Convert UTC to local time in Rails 3

It is easy to configure it using your system local zone, Just in your application.rb add this

config.time_zone = Time.now.zone

Then, rails should show you timestamps in your localtime or you can use something like this instruction to get the localtime

Post.created_at.localtime

How to display scroll bar onto a html table

If you get to the point where all the mentioned solutions don't work (as it got for me), do this:

  • Create two tables. One for the header and another for the body
  • Give the two tables different parent containers/divs
  • Style the second table's div to allow vertical scroll of its contents.

Like this, in your HTML

<div class="table-header-class">
    <table>
       <thead>
          <tr>
            <th>Ava</th>
            <th>Alexis</th>
            <th>Mcclure</th>
          </tr>
       </thead>
    </table>
</div>
<div class="table-content-class">
   <table>
       <tbody>
          <tr>
            <td>I am the boss</td>
            <td>No, da-da is not the boss!</td>
            <td>Alexis, I am the boss, right?</td>
          </tr>
       </tbody>
    </table>
</div>

Then style the second table's parent to allow vertical scroll, in your CSS

    .table-content-class {
        overflow-y: scroll;    // use auto; or scroll; to allow vertical scrolling; 
        overflow-x: hidden;    // disable horizontal scroll 
    }

Parse query string in JavaScript

I wanted a simple function that took a URL as an input and returned a map of the query params. If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.

This should work back and for with the jQuery.param( qparams ) function.

function getQueryParams(url){
    var qparams = {},
        parts = (url||'').split('?'),
        qparts, qpart,
        i=0;

    if(parts.length <= 1 ){
        return qparams;
    }else{
        qparts = parts[1].split('&');
        for(i in qparts){

            qpart = qparts[i].split('=');
            qparams[decodeURIComponent(qpart[0])] = 
                           decodeURIComponent(qpart[1] || '');
        }
    }

    return qparams;
};

onSaveInstanceState () and onRestoreInstanceState ()

As a workaround, you could store a bundle with the data you want to maintain in the Intent you use to start activity A.

Intent intent = new Intent(this, ActivityA.class);
intent.putExtra("bundle", theBundledData);
startActivity(intent);

Activity A would have to pass this back to Activity B. You would retrieve the intent in Activity B's onCreate method.

Intent intent = getIntent();
Bundle intentBundle;
if (intent != null)
    intentBundle = intent.getBundleExtra("bundle");
// Do something with the data.

Another idea is to create a repository class to store activity state and have each of your activities reference that class (possible using a singleton structure.) Though, doing so is probably more trouble than it's worth.

How do I align views at the bottom of the screen?

The answer above (by Janusz) is quite correct, but I personnally don't feel 100% confortable with RelativeLayouts, so I prefer to introduce a 'filler', empty TextView, like this:

<!-- filler -->
<TextView android:layout_height="0dip" 
          android:layout_width="fill_parent"
          android:layout_weight="1" />

before the element that should be at the bottom of the screen.

Prevent HTML5 video from being downloaded (right-click saved)?

This is a simple solution for those wishing to simply remove the right-click "save" option from the html5 videos

$(document).ready(function(){
   $('#videoElementID').bind('contextmenu',function() { return false; });
});

Good tool for testing socket connections?

Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It's not directly a test server. It is placed in-between a client and a server but allow to see what is going through the "tube" and also to change what is going through.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

Importing data from a JSON file into R

First install the RJSONIO and RCurl package:

_x000D_
_x000D_
install.packages("RJSONIO")_x000D_
install.packages("(RCurl")
_x000D_
_x000D_
_x000D_

Try below code using RJSONIO in console

_x000D_
_x000D_
library(RJSONIO)_x000D_
library(RCurl)_x000D_
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")_x000D_
json_file2 = RJSONIO::fromJSON(json_file)_x000D_
head(json_file2)
_x000D_
_x000D_
_x000D_

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

How exactly does the android:onClick XML attribute differ from setOnClickListener?

I am Write this code in xml file ...

<Button
    android:id="@+id/btn_register"
    android:layout_margin="1dp"
    android:layout_marginLeft="3dp"
    android:layout_marginTop="10dp"
    android:layout_weight="2"
    android:onClick="register"
    android:text="Register"
    android:textColor="#000000"/>

And write this code in fragment...

public void register(View view) {
}

sorting dictionary python 3

Dictionaries are unordered by definition, What would be the main reason for ordering by key? A list of tuples created by the sort method can be used for whatever the need may have been, but changing the list of tuples back into a dictionary will return a random order

>>> myDic
{10: 'b', 3: 'a', 5: 'c'}
>>> sorted(myDic.items())
[(3, 'a'), (5, 'c'), (10, 'b')]
>>> print(dict(myDic.items()))
{10: 'b', 3: 'a', 5: 'c'}

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

Setting readonly on a widget only makes the input in the browser read-only. Adding a clean_sku which returns instance.sku ensures the field value will not change on form level.

def clean_sku(self):
    if self.instance: 
        return self.instance.sku
    else: 
        return self.fields['sku']

This way you can use model's (unmodified save) and avoid getting the field required error.

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

The dispatcher-servlet.xml file contains all of your configuration for Spring MVC. So in it you will find beans such as ViewHandlerResolvers, ConverterFactories, Interceptors and so forth. All of these beans are part of Spring MVC which is a framework that structures how you handle web requests, providing useful features such as databinding, view resolution and request mapping.

The application-context.xml can optionally be included when using Spring MVC or any other framework for that matter. This gives you a container that may be used to configure other types of spring beans that provide support for things like data persistence. Basically, in this configuration file is where you pull in all of the other goodies Spring offers.

These configuration files are configured in the web.xml file as shown:

Dispatcher Config

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Application Config

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/application-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

To configure controllers, annotate them with @Controller then include the following in the dispatcher-context.xml file:

<mvc:annotation-driven/>
<context:component-scan base-package="package.with.controllers.**" />

To get specific part of a string in c#

Something like this?

string b = a.Split(',')[0];

Using Font Awesome icon for bullet points, with a single list item element

In Font Awesome 5 it can be done using pure CSS as in some of the above answers with some modifications.

ul {
  list-style-type: none;
}

li:before {
  position: absolute;
  font-family: 'Font Awesome 5 free';
          /*  Use the Name of the Font Awesome free font, e.g.:
           - 'Font Awesome 5 Free' for Regular and Solid symbols;
           - 'Font Awesome 5 Brand' for Brands symbols.
           - 'Font Awesome 5 Pro' for Regular and Solid symbols (Professional License);
          */
  content: "\f1fc"; /* Unicode value of the icon to use: */
  font-weight: 900; /* This is important, change the value according to the font family name
                       used above. See the link below  */
  color: red;
}

Without the correct font-weight, it will only show a blank square.

https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements#define

Limiting the number of characters per line with CSS

A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.

p {
word-wrap: break-word;
}

ResultSet exception - before start of result set

Every answer uses .next() or uses .beforeFirst() and then .next(). But why not this:

result.first();

So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet exists of one specific record.

How do I find the PublicKeyToken for a particular dll?

Using sn.exe utility:

sn -T YourAssembly.dll

or loading the assembly in Reflector.

Static methods - How to call a method from another method?

class.method should work.

class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()

What's the best way to limit text length of EditText in Android

For anyone else wondering how to achieve this, here is my extended EditText class EditTextNumeric.

.setMaxLength(int) - sets maximum number of digits

.setMaxValue(int) - limit maximum integer value

.setMin(int) - limit minimum integer value

.getValue() - get integer value

import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;

public class EditTextNumeric extends EditText {
    protected int max_value = Integer.MAX_VALUE;
    protected int min_value = Integer.MIN_VALUE;

    // constructor
    public EditTextNumeric(Context context) {
        super(context);
        this.setInputType(InputType.TYPE_CLASS_NUMBER);
    }

    // checks whether the limits are set and corrects them if not within limits
    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        if (max_value != Integer.MAX_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) > max_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(max_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        if (min_value != Integer.MIN_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) < min_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(min_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        super.onTextChanged(text, start, before, after);
    }

    // set the max number of digits the user can enter
    public void setMaxLength(int length) {
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(length);
        this.setFilters(FilterArray);
    }

    // set the maximum integer value the user can enter.
    // if exeeded, input value will become equal to the set limit
    public void setMaxValue(int value) {
        max_value = value;
    }
    // set the minimum integer value the user can enter.
    // if entered value is inferior, input value will become equal to the set limit
    public void setMinValue(int value) {
        min_value = value;
    }

    // returns integer value or 0 if errorous value
    public int getValue() {
        try {
            return Integer.parseInt(this.getText().toString());
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}

Example usage:

final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);

All other methods and attributes that apply to EditText, of course work too.

How to embed a PDF viewer in a page?

You could consider using PDFObject by Philip Hutchison.

Alternatively, if you're looking for a non-Javascript solution, you could use markup like this:

<object data="myfile.pdf" type="application/pdf" width="100%" height="100%">
  <p>Alternative text - include a link <a href="myfile.pdf">to the PDF!</a></p>
</object>

Socket.IO - how do I get a list of connected sockets/clients?

For anyone that just wants a COUNT of the connected clients I believe this will do it:

io.sockets.manager.server.connections

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

   IEnumerable<Control> Ctrls = from Control ctrl in Me.Controls where ctrl is TextBox | ctrl is GroupBox select ctr;

Lambda Expressions

IEnumerable<Control> Ctrls = Me.Controls.Cast<Control>().Where(c => c is Button | c is GroupBox);

How to test whether a service is running from the command line

Try

sc query state= all 

for a list of services and whether they are running or not.

get an element's id

Super Easy Way is

  $('.CheckBxMSG').each(function () {
            var ChkBxMsgId;
            ChkBxMsgId = $(this).attr('id');
            alert(ChkBxMsgId);
        });

Tell me if this helps

What is the difference between background and background-color

You can do some pretty neat stuff once you understand that you can play with inheritance with this. However first let's understand something from this doc on background:

With CSS3, you can apply multiple backgrounds to elements. These are layered atop one another with the first background you provide on top and the last background listed in the back. Only the last background can include a background color.

So when one do:

background: red;

He is setting the background-color to red because red is the last value listed.

When one do:

background: linear-gradient(to right, grey 50%, yellow 2%) red;

Red is the background color once again BUT you will see a gradient.

_x000D_
_x000D_
    .box{_x000D_
        border-radius: 50%;_x000D_
        width: 200px;_x000D_
        height: 200px;_x000D_
        background: linear-gradient(to right, grey 50%, yellow 2%) red;_x000D_
    }_x000D_
_x000D_
    .box::before{_x000D_
       content: "";_x000D_
       display: block;_x000D_
       margin-left: 50%;_x000D_
       height: 50%;_x000D_
       border-radius: 0 100% 100% 0 / 50%;_x000D_
       transform: translateX(70px) translateY(-26px) rotate(325deg);_x000D_
       background: inherit;_x000D_
    }
_x000D_
    <div class="box">_x000D_
      _x000D_
     </div>
_x000D_
_x000D_
_x000D_

Now the same thing with background-color:

_x000D_
_x000D_
    .box{_x000D_
        border-radius: 50%;_x000D_
        width: 200px;_x000D_
        height: 200px;_x000D_
        background: linear-gradient(to right, grey 50%, yellow 2%) red;_x000D_
    }_x000D_
_x000D_
    .box::before{_x000D_
       content: "";_x000D_
       display: block;_x000D_
       margin-left: 50%;_x000D_
       height: 50%;_x000D_
       border-radius: 0 100% 100% 0 / 50%;_x000D_
       transform: translateX(70px) translateY(-26px) rotate(325deg);_x000D_
       background-color: inherit;_x000D_
    }
_x000D_
    <div class="box">_x000D_
      _x000D_
     </div>
_x000D_
_x000D_
_x000D_

The reason this happens is because when we are doing this :

background: linear-gradient(to right, grey 50%, yellow 2%) #red;

The last number sets the background-color.

Then in the before we are inheriting from background (then we get the gradient) or background color, then we get red.

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Reference excel worksheet by name?

To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below. screenshot of predictive text in VBE

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.

Why can't I call a public method in another class?

You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example

class Example {
  public static string NonInstanceMethod() {
    return "static";
  }
  public string InstanceMethod() { 
    return "non-static";
  }
}

static void SomeMethod() {
  Console.WriteLine(Example.NonInstanceMethod());
  Console.WriteLine(Example.InstanceMethod());  // Does not compile
  Example v1 = new Example();
  Console.WriteLine(v1.InstanceMethod());
}

Check if string ends with one of the strings from a list

another way which can return the list of matching strings is

sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

Running multiple async tasks and waiting for them all to complete

Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:

var cats = new List<Cat>();
var dog = new Dog();

var loadDataTasks = new Task[]
{
    Task.Run(async () => cats = await LoadCatsAsync()),
    Task.Run(async () => dog = await LoadDogAsync())
};

try
{
    await Task.WhenAll(loadDataTasks);
}
catch (Exception ex)
{
    // handle exception
}

Calling stored procedure with return value

I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah

Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;

How to know the size of the string in bytes?

You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding class.

or try this

  System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
  System.Text.ASCIIEncoding.ASCII.GetByteCount(string);

How to use Simple Ajax Beginform in Asp.net MVC 4?

Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Disable button in WPF?

I know this isn't as elegant as the other posts, but it's a more straightforward xaml/codebehind example of how to accomplish the same thing.

Xaml:

<StackPanel Orientation="Horizontal">
   <TextBox Name="TextBox01" VerticalAlignment="Top" HorizontalAlignment="Left" Width="70" />
   <Button Name="Button01" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,0" />
</StackPanel>

CodeBehind:

Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        Button01.IsEnabled = False
        Button01.Content = "I am Disabled"

End Sub

Private Sub TextBox01_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox01.TextChanged

        If TextBox01.Text.Trim.Length > 0 Then
            Button01.IsEnabled = True
            Button01.Content = "I am Enabled"
        Else
            Button01.IsEnabled = False
            Button01.Content = "I am Disabled"
        End If

End Sub

Is it possible to use "return" in stored procedure?

In Stored procedure, you return the values using OUT parameter ONLY. As you have defined two variables in your example:

   outstaticip OUT VARCHAR2, outcount OUT NUMBER

Just assign the return values to the out parameters i.e. outstaticip and outcount and access them back from calling location. What I mean here is: when you call the stored procedure, you will be passing those two variables as well. After the stored procedure call, the variables will be populated with return values.

If you want to have RETURN value as return from the PL/SQL call, then use FUNCTION. Please note that in case, you would be able to return only one variable as return variable.

PUT vs. POST in REST

Short Answer:

Simple rule of thumb: Use POST to create, use PUT to update.

Long Answer:

POST:

  • POST is used to send data to server.
  • Useful when the resource's URL is unknown

PUT:

  • PUT is used to transfer state to the server
  • Useful when a resource's URL is known

Longer Answer:

To understand it we need to question why PUT was required, what were the problems PUT was trying to solve that POST couldn't.

From a REST architecture's point of view there is none that matters. We could have lived without PUT as well. But from a client developer's point of view it made his/her life a lot simpler.

Prior to PUT, clients couldn't directly know the URL that the server generated or if all it had generated any or whether the data to be sent to the server is already updated or not. PUT relieved the developer of all these headaches. PUT is idempotent, PUT handles race conditions, and PUT lets the client choose the URL.

SQL Order By Count

Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.

event_id show_id event_name judge_id
0101    01  Dressage        01
0102    01  Jumping         02
0103    01  Led in          01
0201    02  Led in          02
0301    03  Led in          01
0401    04  Dressage        04
0501    05  Dressage        01
0502    05  Flag and Pole   02

Ans:

select event_name, count(show_id) as held_times from event 
group by event_name 
order by count(show_id) desc

Multiple line code example in Javadoc comment

You need the <pre></pre> tags for the line breaks, and the {@code ... } inside them for generics. But then it's not allowed to place the opening brace on the same line as the <generic> tag, because then everything will be displayed on 1 line again.

Displays on one line:

* ..
* <pre>
* {@code
* public List<Object> getObjects() {
*    return objects;
* }
* </pre>
* ..

Displays with line breaks:

* ..
* <pre>
* {@code
* public List<Object> getObjects() 
* {
*    return objects;
* }
* </pre>
* ..

Another weird thing is when you paste the closing brace of {@code, it gets displayed:

* ..
* <pre>
* {@code
*   public List<Object> getObjects() 
*   {
*     return objects;
*   }
* }
* </pre>
* ..

Output:

public List<Object> getObjects() 
{
   return objects;
}
}

Revert to a commit by a SHA hash in Git?

Should be as simple as:

git reset --hard 56e05f

That'll get you back to that specific point in time.

Install .ipa to iPad with or without iTunes

There were 3 ways to do this:

Method 1: Using iTunes. Yes, you can install .ipa in iPad, first you have to import that .ipa to your iTunes. Connect your iPad to iTunes then install application just by click on Install and then Sync.

Method 2: iFunbox

Method 3: Diawi

Spring .properties file: get element as an Array

And incase you a different delimiter other than comma, you can use that as well.

@Value("#{'${my.config.values}'.split(',')}")
private String[] myValues;   // could also be a List<String>

and

in your application properties you could have

my.config.values=value1, value2, value3

Can I embed a custom font in an iPhone application?

Maybe the author forgot to give the font a Mac FOND name?

  1. Open the font in FontForge then go to Element>Font Info
  2. There is a "Mac" Option where you can set the FOND name.
  3. Under File>Export Font you can create a new ttf

You could also give the "Apple" option in the export dialog a try.

DISCLAIMER: I'm not a IPhone developer!

What is the purpose of XSD files?

Also questions is: What is the purpose of giving the relationships in xsd.

Suppose you want to generate some XML for an external party's tool, or similar - how would you know what structure it is allowed to follow to be used correctly for their tool? you write to a schema. Likewise if you want other people to use your tool, you would write a schema for them to follow. It may also be useful for validating your own XML.

What is *.o file?

It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.

Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.

These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.

You can use the nm tool on an object file to list the symbols defined in a .o file.

How do I update zsh to the latest version?

If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):

  1. Get the latest version of the ZSH sourcecode

  2. Untar the download into its own directory then install: ./configure && make && make test && sudo make install

  3. This installs the the zsh binary at /usr/local/bin/zsh.

  4. You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...

  5. To make it your default shell you must first edit /etc/shells and add the new path. Then you can either run chsh -s /usr/local/bin/zsh or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".

  6. Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).

C++, How to determine if a Windows Process is running?

While writing a monitoring tool, i took a slightly different approach.

It felt a bit wasteful to spin up an extra thread just to use WaitForSingleObject or even the RegisterWaitForSingleObject (which does that for you). Since in my case i don't need to know the exact instant a process has closed, just that it indeed HAS closed.

I'm using the GetProcessTimes() instead:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx

GetProcessTimes() will return a FILETIME struct for the process's ExitTime only if the process has actually exited. So is just a matter of checking if the ExitTime struct is populated and if the time isn't 0;

This solution SHOULD account the case where a process has been killed but it's PID was reused by another process. GetProcessTimes needs a handle to the process, not the PID. So the OS should know that the handle is to a process that was running at some point, but not any more, and give you the exit time.

Relying on the ExitCode felt dirty :/

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

A much more simple solution (thanks to http://daniel.fone.net.nz/blog/2014/12/01/fixing-connection-errors-after-upgrading-postgres/) . I had upgraded to postgres 9.4. In my case, all I needed to do (after a day of googling and not succeeding)

gem uninstall pg
gem uninstall activerecord-postgresql-adapter
bundle install

Restart webrick, and done!

pass JSON to HTTP POST Request

Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)

Using library: https://github.com/request/request-promise

npm install --save request
npm install --save request-promise

client:

//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');

rp({
    method: 'POST',
    uri: 'http://localhost:3000/',
    body: {
        val1 : 1,
        val2 : 2
    },
    json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
        console.log(parsedBody);
        // POST succeeded...
    })
    .catch(function (err) {
        console.log(parsedBody);
        // POST failed...
    });

server:

var express = require('express')
    , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
    console.log(request.body);      // your JSON

    var jsonRequest = request.body;
    var jsonResponse = {};

    jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;

    response.send(jsonResponse);
});


app.listen(3000);

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc();

main.cpp

#include "other.h"
int main() {
    MyFunc();
}

other.cpp

#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

Select a date from date picker using Selenium webdriver

Please use this code for selecting date from Two Jquery calendar like Flight Booking site.

    Hashtable h=new Hashtable();
    h.put("January",0 );
    h.put("February",1);
    h.put("March",2);
    h.put("April",3);
    h.put("May",4);
    h.put("June",5);
    h.put("July",6);
    h.put("August",7);
    h.put("September",8);
    h.put("October",9);
    h.put("November",10);
    h.put("December",11);


    int expMonth;
    int expYear;

    // Calendar Month and Year
    String calMonth = null;
    String calYear = null;
    boolean dateNotFound;
    dateNotFound = true;
    expMonth= 5;
    expYear = 2014;

    while(dateNotFound)
    {

        calMonth = driver.findElement(By.className("ui-datepicker-month")).getText(); // get the text of month
        calYear = driver.findElement(By.className("ui-datepicker-year")).getText();




        if(((Integer)h.get(calMonth))+1 == expMonth && (expYear == Integer.parseInt(calYear)))
        {
            String block="//div[@class='monthBlock first']/table/tbody/tr/td";  // THIS IS FIRST CALENDAR
            selectDate(expDate,block); 
            dateNotFound = false; 
        }
        // parseInt - Converts String to integer and indexof( It will return the index position of String)
        else if(((Integer)h.get(calMonth))+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
        {
            String block="//div[@class='monthBlock last']/table/tbody/tr/td"; // THIS IS SECOND CALENDAR


                            selectDate(expDate,block); // PASSING DATE AND CALENDAR
                            dateNotFound = false; // Otherwise it will rotate continuously 
        }
        else if((Integer)h.get(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
        {
            System.out.println(" Please enter the date greater than Current date");
            dateNotFound = false;

        }
    }

    }
    //Thread.sleep(3000);


    public static void selectDate(String date,String block) throws IOException
    {

                    String monthblock=block;

        List<WebElement> dateWidget = driver.findElements(By.xpath(monthblock));    

        for (WebElement cell: dateWidget)
        {
            //Selects Date
            if (cell.getText().equals(date))
            {
                cell.findElement(By.linkText(date)).click();
                break;
            }

        }

        //Doubt : How to verify the expected results and how to sort the program



        driver.findElement(By.id("SearchBtn")).submit();

        //driver.quit();
    }

Remove the title bar in Windows Forms

Set FormsBorderStyle of the Form to None.

If you do, it's up to you how to implement the dragging and closing functionality of the window.

How to set connection timeout with OkHttp

It's changed now. Replace .Builder() with .newBuilder()

As of okhttp:3.9.0 the code goes as follows:

OkHttpClient okHttpClient = new OkHttpClient()
    .newBuilder()
    .connectTimeout(10,TimeUnit.SECONDS)
    .writeTimeout(10,TimeUnit.SECONDS)
    .readTimeout(30,TimeUnit.SECONDS)
    .build();

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

How to sparsely checkout only one single file from a git repository?

Two variants on what's already been given:

git archive --format=tar --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | tar -O -xf -

and:

git archive --format=zip --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | funzip

These write the file to standard output.

How to remove focus from input field in jQuery?

$(':text').attr("disabled", "disabled"); sets all textbox to disabled mode. You can do in another way like giving each textbox id. By doing this code weight will be more and performance issue will be there.

So better have $(':text').attr("disabled", "disabled"); approach.

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

Querying a linked sql server

SELECT * FROM [server].[database].[schema].[table]

This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.

How to calculate mean, median, mode and range from a set of numbers

If you only care about unimodal distributions, consider sth. like this.

public static Optional<Integer> mode(Stream<Integer> stream) {
    Map<Integer, Long> frequencies = stream
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    return frequencies.entrySet().stream()
        .max(Comparator.comparingLong(Map.Entry::getValue))
        .map(Map.Entry::getKey);
}

Node.js - Find home directory in platform agnostic way

Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.

function getUserHome() {
  return process.env.HOME || process.env.USERPROFILE;
}

EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()).

Combine Points with lines with ggplot2

You may find that using the `group' aes will help you get the result you want. For example:

tu <- expand.grid(Land       = gl(2, 1, labels = c("DE", "BB")),
                  Altersgr   = gl(5, 1, labels = letters[1:5]),
                  Geschlecht = gl(2, 1, labels = c('m', 'w')),
                  Jahr       = 2000:2009)

set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)

ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) + 
  geom_point() + geom_line() + 
  facet_grid(Geschlecht ~ Land)

Which produces the plot found here:

enter image description here

Object spread vs. Object.assign

This isn't necessarily exhaustive.

Spread syntax

options = {...optionsDefault, ...options};

Advantages:

  • If authoring code for execution in environments without native support, you may be able to just compile this syntax (as opposed to using a polyfill). (With Babel, for example.)

  • Less verbose.

Disadvantages:

  • When this answer was originally written, this was a proposal, not standardized. When using proposals consider what you'd do if you write code with it now and it doesn't get standardized or changes as it moves toward standardization. This has since been standardized in ES2018.

  • Literal, not dynamic.


Object.assign()

options = Object.assign({}, optionsDefault, options);

Advantages:

  • Standardized.

  • Dynamic. Example:

    var sources = [{a: "A"}, {b: "B"}, {c: "C"}];
    options = Object.assign.apply(Object, [{}].concat(sources));
    // or
    options = Object.assign({}, ...sources);
    

Disadvantages:

  • More verbose.
  • If authoring code for execution in environments without native support you need to polyfill.

This is the commit that made me wonder.

That's not directly related to what you're asking. That code wasn't using Object.assign(), it was using user code (object-assign) that does the same thing. They appear to be compiling that code with Babel (and bundling it with Webpack), which is what I was talking about: the syntax you can just compile. They apparently preferred that to having to include object-assign as a dependency that would go into their build.

use regular expression in if-condition in bash

Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

# GLOB matching
gg=svm-grid-ch    
case "$gg" in
   *grid*) echo $gg ;;
esac

# REGEXP    
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    

# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
  echo $gg
fi    

Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

How can I set multiple CSS styles in JavaScript?

This is old thread, so I figured for anyone looking for a modern answer, I would suggest using Object.keys();

var myDiv = document.getElementById("myDiv");
var css = {
    "font-size": "14px",
    "color": "#447",
    "font-family": "Arial",
    "text-decoration": "underline"
};

function applyInlineStyles(obj) {
    var result = "";
    Object.keys(obj).forEach(function (prop) {
        result += prop + ": " + obj[prop] + "; ";
    });
    return result;
}

myDiv.style = applyInlineStyles(css);

How do I fix a NoSuchMethodError?

If using Maven or another framework, and you get this error almost randomly, try a clean install like...

clean install

This is especially likely to work if you wrote the object and you know it has the method.

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

SQLAlchemy upsert for Postgres >=9.5

Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.

Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)

SQLAlchemy supports ON CONFLICT now with two methods on_conflict_do_update() and on_conflict_do_nothing():

Copying from the documentation:

from sqlalchemy.dialects.postgresql import insert

stmt = insert(my_table).values(user_email='[email protected]', data='inserted data')
stmt = stmt.on_conflict_do_update(
    index_elements=[my_table.c.user_email],
    index_where=my_table.c.user_email.like('%@gmail.com'),
    set_=dict(data=stmt.excluded.data)
    )
conn.execute(stmt)

http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html?highlight=conflict#insert-on-conflict-upsert

How can I confirm a database is Oracle & what version it is using SQL?

There are different ways to check Oracle Database Version. Easiest way is to run the below SQL query to check Oracle Version.

SQL> SELECT * FROM PRODUCT_COMPONENT_VERSION;
SQL> SELECT * FROM v$version;

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

It's a long time since the question was posted, but I experienced the same issue in a similar scenario. I have a console application and I was consuming a web service and our IIS server where the webservice was placed has windows authentication (NTLM) enabled.

I followed this link and that fixed my problem. Here's the sample code for App.config:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="Service1Soap">
                <security mode="TransportCredentialOnly">
                    <transport clientCredentialType="Ntlm" proxyCredentialType="None"
                        realm=""/>
                    <message clientCredentialType="UserName" algorithmSuite="Default"/>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost/servicename/service1.asmx" 
            binding="basicHttpBinding" bindingConfiguration="ListsSoap"/>
    </client>
</system.serviceModel>

How to change the button color when it is active using bootstrap?

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

Material Design not styling alert dialogs

For some reason the android:textColor only seems to update the title color. You can change the message text color by using a

SpannableString.AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.MyDialogTheme));

AlertDialog dialog = builder.create();
                Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
                wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                dialog.setMessage(wordtoSpan);
                dialog.show();

How can I keep Bootstrap popovers alive while being hovered?

Vikas answer works perfectly for me, here I also add support for the delay (show / hide).

var popover = $('#example');
var options = {
    animation : true,
    html: true,
    trigger: 'manual',
    placement: 'right',
    delay: {show: 500, hide: 100}
};   
popover
    .popover(options)
    .on("mouseenter", function () {

        var t = this;
        var popover = $(this);    
        setTimeout(function () {

            if (popover.is(":hover")) {

                popover.popover("show");
                popover.siblings(".popover").on("mouseleave", function () {
                    $(t).popover('hide');
                });
            }
        }, options.delay.show);
    })
    .on("mouseleave", function () {
        var t = this;
        var popover = $(this);

        setTimeout(function () {
            if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
                $(t).popover("hide")
            }
        }, options.delay.hide);
    });     

Also please pay attention I changed:

if (!$(".popover:hover").length) {

with:

if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {

so that it references exactly at that opened popover, and not any other (since now, through the delay, more than 1 could be open at the same time)

size of uint8, uint16 and uint32?

It's quite unclear how you are computing the size ("the size in debug mode"?").

Use printf():

printf("the size of c is %u\n", (unsigned int) sizeof c);

Normally you'd print a size_t value (which is the type sizeof returns) with %zu, but if you're using a pre-C99 compiler like Visual Studio that won't work.

You need to find the typedef statements in your code that define the custom names like uint8 and so on; those are not standard so nobody here can know how they're defined in your code.

New C code should use <stdint.h> which gives you uint8_t and so on.

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Simply difference between Forward(ServletRequest request, ServletResponse response) and sendRedirect(String url) is

forward():

  1. The forward() method is executed in the server side.
  2. The request is transfer to other resource within same server.
  3. It does not depend on the client’s request protocol since the forward () method is provided by the servlet container.
  4. The request is shared by the target resource.
  5. Only one call is consumed in this method.
  6. It can be used within server.
  7. We cannot see forwarded message, it is transparent.
  8. The forward() method is faster than sendRedirect() method.
  9. It is declared in RequestDispatcher interface.

sendRedirect():

  1. The sendRedirect() method is executed in the client side.
  2. The request is transfer to other resource to different server.
  3. The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
  4. New request is created for the destination resource.
  5. Two request and response calls are consumed.
  6. It can be used within and outside the server.
  7. We can see redirected address, it is not transparent.
  8. The sendRedirect() method is slower because when new request is created old request object is lost.
  9. It is declared in HttpServletResponse.

Environment variable to control java.io.tmpdir?

According to the java.io.File Java Docs

The default temporary-file directory is specified by the system property java.io.tmpdir. On UNIX systems the default value of this property is typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "c:\temp". A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the the temporary directory used by this method.

To specify the java.io.tmpdir System property, you can invoke the JVM as follows:

java -Djava.io.tmpdir=/path/to/tmpdir

By default this value should come from the TMP environment variable on Windows systems

Copy/Paste from Excel to a web page

On OSX and Windows , there are multiple types of clipboards for different types of content. When you copy content in Excel, data is stored in the plaintext and in the html clipboard.

The right way (that doesn't get tripped up by delimiter issues) is to parse the HTML. http://jsbin.com/uwuvan/5 is a simple demo that shows how to get the HTML clipboard. The key is to bind to the onpaste event and read

event.clipboardData.getData('text/html')

Problem in running .net framework 4.0 website on iis 7.0

If you are running Delphi, or other native compiled CGI, this solution will work:

  1. As other pointed, go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header.

  2. If you have everything allowed, it will still not work. You need to click on "Edit Feature Settings" in Actions (on the right side), and check "Allow unspecified CGI modules", or "Allow unspecified ISAPI modules" respectively.

  3. Click OK

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Python: PIP install path, what is the correct location for this and other addons?

Also, when you uninstall the package, the first item listed is the directory to the executable.

Adding an image to a PDF using iTextSharp and scale it properly

image.ScaleToFit(500f,30f);

this method keeps the aspect ratio of the image

CSS background-image-opacity?

Try this trick .. use css shadow with (inset) option and make the deep 200px for example

Code:

box-shadow: inset 0px 0px 277px 3px #4c3f37;

.

Also for all browsers:

-moz-box-shadow: inset 0px 0px 47px 3px #4c3f37;
-webkit-box-shadow: inset 0px 0px 47px 3px #4c3f37;
box-shadow: inset 0px 0px 277px 3px #4c3f37;

and increase number to make fill your box :)

Enjoy!

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

In my case the problem was:

define ('DB_PASSWORD', "MyPassw0rd!'");

(the odd single ' before the double ")

Stretch horizontal ul to fit width of div

I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.

#horizontal-style {
  padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line 
  justify-content: space-around;
  display: flex;
}

#horizontal-style a {
    text-align: center;
    color: white;
    text-decoration: none;
}

What does "collect2: error: ld returned 1 exit status" mean?

The ld returned 1 exit status error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr' - and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0 means success, and exit status > 0 means errors.

When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld, which first reports the error it found (clrscr reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.

In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Try

$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ")or die(mysql_error());

and check if this throw any error.

Then use while($rows = mysql_fetch_assoc($query)):

And finally display it as

echo $name . "<br/>" . $address . "<br/>" . $email . "<br/>" . $subject . "<br/>" . $comment . "<br/><br/>" . ;

Do not user mysql_* as its deprecated.

error: expected declaration or statement at end of input in c

For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.

How can I start InternetExplorerDriver using Selenium WebDriver

static WebDriver driver;
System.setProperty("webdriver.ie.driver","C:\\(Path)\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("EnterURLHere");          
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);

When I catch an exception, how do I get the type, file, and line number?

You could achieve this without having to import traceback:

try:
    func1()
except Exception as ex:
    trace = []
    tb = ex.__traceback__
    while tb is not None:
        trace.append({
            "filename": tb.tb_frame.f_code.co_filename,
            "name": tb.tb_frame.f_code.co_name,
            "lineno": tb.tb_lineno
        })
        tb = tb.tb_next
    print(str({
        'type': type(ex).__name__,
        'message': str(ex),
        'trace': trace
    }))

Output:

{

  'type': 'ZeroDivisionError',
  'message': 'division by zero',
  'trace': [
    {
      'filename': '/var/playground/main.py',
      'name': '<module>',
      'lineno': 16
    },
    {
      'filename': '/var/playground/main.py',
      'name': 'func1',
      'lineno': 11
    },
    {
      'filename': '/var/playground/main.py',
      'name': 'func2',
      'lineno': 7
    },
    {
      'filename': '/var/playground/my.py',
      'name': 'test',
      'lineno': 2
    }
  ]
}

Docker: How to use bash with an Alpine based docker image?

Try using RUN /bin/sh instead of bash.

error CS0103: The name ' ' does not exist in the current context

Simply move the declaration outside of the if block.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store2_logo.gif";
    }
}

<a href="@Url.RouteUrl("HomePage")" class="logo"><img  alt="" src="@imgsrc"></a>

You could make it a bit cleaner.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    }
}

Best way to convert string to bytes in Python 3?

Answer for a slightly different problem:

You have a sequence of raw unicode that was saved into a str variable:

s_str: str = "\x00\x01\x00\xc0\x01\x00\x00\x00\x04"

You need to be able to get the byte literal of that unicode (for struct.unpack(), etc.)

s_bytes: bytes = b'\x00\x01\x00\xc0\x01\x00\x00\x00\x04'

Solution:

s_new: bytes = bytes(s, encoding="raw_unicode_escape")

Reference (scroll up for standard encodings):

Python Specific Encodings

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

You can use the getters of java.time.LocalDateTime for that.

LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.

System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

Or, when you're not on Java 8 yet, make use of java.util.Calendar.

Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);

System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

Either way, this prints as of now:

2010-04-16 15:15:17.816

To convert an int to String, make use of String#valueOf().


If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter (tutorial here),

LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));

System.out.println(format1);
System.out.println(format2);
System.out.println(format3);

or when you're not on Java 8 yet, use java.text.SimpleDateFormat:

Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);

System.out.println(format1);
System.out.println(format2);
System.out.println(format3);

Either way, this yields:

2010-04-16T15:15:17.816
Fri, 16 Apr 2010 15:15:17 GMT
20100416151517

See also:

Check if number is prime number

I've implemented a different method to check for primes because:

  • Most of these solutions keep iterating through the same multiple unnecessarily (for example, they check 5, 10, and then 15, something that a single % by 5 will test for).
  • A % by 2 will handle all even numbers (all integers ending in 0, 2, 4, 6, or 8).
  • A % by 5 will handle all multiples of 5 (all integers ending in 5).
  • What's left is to test for even divisions by integers ending in 1, 3, 7, or 9. But the beauty is that we can increment by 10 at a time, instead of going up by 2, and I will demonstrate a solution that is threaded out.
  • The other algorithms are not threaded out, so they don't take advantage of your cores as much as I would have hoped.
  • I also needed support for really large primes, so I needed to use the BigInteger data-type instead of int, long, etc.

Here is my implementation:

public static BigInteger IntegerSquareRoot(BigInteger value)
{
    if (value > 0)
    {
        int bitLength = value.ToByteArray().Length * 8;
        BigInteger root = BigInteger.One << (bitLength / 2);
        while (!IsSquareRoot(value, root))
        {
            root += value / root;
            root /= 2;
        }
        return root;
    }
    else return 0;
}

private static Boolean IsSquareRoot(BigInteger n, BigInteger root)
{
    BigInteger lowerBound = root * root;
    BigInteger upperBound = (root + 1) * (root + 1);
    return (n >= lowerBound && n < upperBound);
}

static bool IsPrime(BigInteger value)
{
    Console.WriteLine("Checking if {0} is a prime number.", value);
    if (value < 3)
    {
        if (value == 2)
        {
            Console.WriteLine("{0} is a prime number.", value);
            return true;
        }
        else
        {
            Console.WriteLine("{0} is not a prime number because it is below 2.", value);
            return false;
        }
    }
    else
    {
        if (value % 2 == 0)
        {
            Console.WriteLine("{0} is not a prime number because it is divisible by 2.", value);
            return false;
        }
        else if (value == 5)
        {
            Console.WriteLine("{0} is a prime number.", value);
            return true;
        }
        else if (value % 5 == 0)
        {
            Console.WriteLine("{0} is not a prime number because it is divisible by 5.", value);
            return false;
        }
        else
        {
            // The only way this number is a prime number at this point is if it is divisible by numbers ending with 1, 3, 7, and 9.
            AutoResetEvent success = new AutoResetEvent(false);
            AutoResetEvent failure = new AutoResetEvent(false);
            AutoResetEvent onesSucceeded = new AutoResetEvent(false);
            AutoResetEvent threesSucceeded = new AutoResetEvent(false);
            AutoResetEvent sevensSucceeded = new AutoResetEvent(false);
            AutoResetEvent ninesSucceeded = new AutoResetEvent(false);
            BigInteger squareRootedValue = IntegerSquareRoot(value);
            Thread ones = new Thread(() =>
            {
                for (BigInteger i = 11; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                onesSucceeded.Set();
            });
            ones.Start();
            Thread threes = new Thread(() =>
            {
                for (BigInteger i = 3; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                threesSucceeded.Set();
            });
            threes.Start();
            Thread sevens = new Thread(() =>
            {
                for (BigInteger i = 7; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                sevensSucceeded.Set();
            });
            sevens.Start();
            Thread nines = new Thread(() =>
            {
                for (BigInteger i = 9; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                ninesSucceeded.Set();
            });
            nines.Start();
            Thread successWaiter = new Thread(() =>
            {
                AutoResetEvent.WaitAll(new WaitHandle[] { onesSucceeded, threesSucceeded, sevensSucceeded, ninesSucceeded });
                success.Set();
            });
            successWaiter.Start();
            int result = AutoResetEvent.WaitAny(new WaitHandle[] { success, failure });
            try
            {
                successWaiter.Abort();
            }
            catch { }
            try
            {
                ones.Abort();
            }
            catch { }
            try
            {
                threes.Abort();
            }
            catch { }
            try
            {
                sevens.Abort();
            }
            catch { }
            try
            {
                nines.Abort();
            }
            catch { }
            if (result == 1)
            {
                return false;
            }
            else
            {
                Console.WriteLine("{0} is a prime number.", value);
                return true;
            }
        }
    }
}

Update: If you want to implement a solution with trial division more rapidly, you might consider having a cache of prime numbers. A number is only prime if it is not divisible by other prime numbers that are up to the value of its square root. Other than that, you might consider using the probabilistic version of the Miller-Rabin primality test to check for a number's primality if you are dealing with large enough values (taken from Rosetta Code in case the site ever goes down):

// Miller-Rabin primality test as an extension method on the BigInteger type.
// Based on the Ruby implementation on this page.
public static class BigIntegerExtensions
{
  public static bool IsProbablePrime(this BigInteger source, int certainty)
  {
    if(source == 2 || source == 3)
      return true;
    if(source < 2 || source % 2 == 0)
      return false;

    BigInteger d = source - 1;
    int s = 0;

    while(d % 2 == 0)
    {
      d /= 2;
      s += 1;
    }

    // There is no built-in method for generating random BigInteger values.
    // Instead, random BigIntegers are constructed from randomly generated
    // byte arrays of the same length as the source.
    RandomNumberGenerator rng = RandomNumberGenerator.Create();
    byte[] bytes = new byte[source.ToByteArray().LongLength];
    BigInteger a;

    for(int i = 0; i < certainty; i++)
    {
      do
      {
        // This may raise an exception in Mono 2.10.8 and earlier.
        // http://bugzilla.xamarin.com/show_bug.cgi?id=2761
        rng.GetBytes(bytes);
        a = new BigInteger(bytes);
      }
      while(a < 2 || a >= source - 2);

      BigInteger x = BigInteger.ModPow(a, d, source);
      if(x == 1 || x == source - 1)
        continue;

      for(int r = 1; r < s; r++)
      {
        x = BigInteger.ModPow(x, 2, source);
        if(x == 1)
          return false;
        if(x == source - 1)
          break;
      }

      if(x != source - 1)
        return false;
    }

    return true;
  }
}

Set Response Status Code

Since PHP 5.4 you can use http_response_code.

http_response_code(404);

This will take care of setting the proper HTTP headers.

If you are running PHP < 5.4 then you have two options:

  1. Upgrade.
  2. Use this http_response_code function implemented in PHP.

Using jQuery to see if a div has a child with a certain class

There is a hasClass function

if($('#popup p').hasClass('filled-text'))

How to use requirements.txt to install all dependencies in a python project

If you are using Linux OS:

  1. Remove matplotlib==1.3.1 from requirements.txt
  2. Try to install with sudo apt-get install python-matplotlib
  3. Run pip install -r requirements.txt (Python 2), or pip3 install -r requirements.txt (Python 3)
  4. pip freeze > requirements.txt

If you are using Windows OS:

  1. python -m pip install -U pip setuptools
  2. python -m pip install matplotlib

Resize Cross Domain Iframe Height

If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe container anytime the height of the framed content changes.

Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).

window.addEventListener("load", function(){
    if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe 
    send_height_to_parent_function = function(){
        var height = document.getElementsByTagName("html")[0].clientHeight;
        //console.log("Sending height as " + height + "px");
        parent.postMessage({"height" : height }, "*");
    }
    // send message to parent about height updates
    send_height_to_parent_function(); //whenever the page is loaded
    window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
    var observer = new MutationObserver(send_height_to_parent_function);           // whenever DOM changes PT1
    var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
    observer.observe(window.document, config);                                            // PT3 
});

Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.

<script>
window.addEventListener("message", function(e){
    var this_frame = document.getElementById("healthy_behavior_iframe");
    if (this_frame.contentWindow === e.source) {
        this_frame.height = e.data.height + "px";
        this_frame.style.height = e.data.height + "px";
    }
})
</script>

How to validate a date?

function isValidDate(year, month, day) {
        var d = new Date(year, month - 1, day, 0, 0, 0, 0);
        return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
    }

Casting to string in JavaScript

According to this JSPerf test, they differ in speed. But unless you're going to use them in huge amounts, any of them should perform fine.

For completeness: As asawyer already mentioned, you can also use the .toString() method.

How to find the maximum value in an array?

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

Where to place and how to read configuration resource files in servlet based application?

Assume your code is looking for the file say app.properties. Copy this file to any dir and add this dir to classpath, by creating a setenv.sh in the bin dir of tomcat.

In your setenv.sh of tomcat( if this file is not existing, create one , tomcat will load this setenv.sh file. #!/bin/sh CLASSPATH="$CLASSPATH:/home/user/config_my_prod/"

You should not have your properties files in ./webapps//WEB-INF/classes/app.properties

Tomcat class loader will override the with the one from WEB-INF/classes/

A good read: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

You are single quoting your SQL statement which is making the variables text instead of variables.

$sql = "SELECT * 
    FROM $usertable 
    WHERE PartNumber = $partid";

Android, How to read QR code in my application?

In android studio, You can use bellow process to create & Read QR Code &image look like bellw enter image description here

  1. Create a android studio empty project
  2. Add library in app.gradle

    compile 'com.google.zxing:core:3.2.1'
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    
  3. In activity.main xml use bellow..

     <?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:layout_height="match_parent"
     tools:context="com.example.enamul.qrcode.MainActivity">
    
    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_margin="20dp"
      android:orientation="vertical">
    
    
    <EditText
        android:id="@+id/editText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="Enter Text Here" />
    
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/editText"
        android:text="Click Here TO generate qr code"
        android:textAllCaps="false"
        android:textSize="16sp" />
    
    
    <Button
        android:id="@+id/btnScan"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/editText"
        android:text="Scan Your QR Code"
        android:textAllCaps="false"
        android:textSize="16sp" />
    
    <TextView
        android:id="@+id/tv_qr_readTxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    
    
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@+id/button"
        android:src="@android:drawable/ic_dialog_email" />
    
    
    </LinearLayout>
    
    </LinearLayout>
    
  4. In MainActivity you can use bellow code

    public class MainActivity extends AppCompatActivity {
      ImageView imageView;
      Button button;
      Button btnScan;
      EditText editText;
      String EditTextValue ;
      Thread thread ;
      public final static int QRcodeWidth = 350 ;
      Bitmap bitmap ;
    
      TextView tv_qr_readTxt;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
    
        imageView = (ImageView)findViewById(R.id.imageView);
        editText = (EditText)findViewById(R.id.editText);
        button = (Button)findViewById(R.id.button);
        btnScan = (Button)findViewById(R.id.btnScan);
         tv_qr_readTxt = (TextView) findViewById(R.id.tv_qr_readTxt);
    
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    
    
    
            if(!editText.getText().toString().isEmpty()){
                EditTextValue = editText.getText().toString();
    
                try {
                    bitmap = TextToImageEncode(EditTextValue);
    
                    imageView.setImageBitmap(bitmap);
    
                } catch (WriterException e) {
                    e.printStackTrace();
                }
            }
            else{
                editText.requestFocus();
                Toast.makeText(MainActivity.this, "Please Enter Your Scanned Test" , Toast.LENGTH_LONG).show();
            }
    
          }
      });
    
    
    btnScan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    
            IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
            integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
            integrator.setPrompt("Scan");
            integrator.setCameraId(0);
            integrator.setBeepEnabled(false);
            integrator.setBarcodeImageEnabled(false);
            integrator.initiateScan();
    
         }
       });
        }
    
    
     Bitmap TextToImageEncode(String Value) throws WriterException {
       BitMatrix bitMatrix;
        try {
        bitMatrix = new MultiFormatWriter().encode(
                Value,
                BarcodeFormat.DATA_MATRIX.QR_CODE,
                QRcodeWidth, QRcodeWidth, null
        );
    
        } catch (IllegalArgumentException Illegalargumentexception) {
    
         return null;
       }
      int bitMatrixWidth = bitMatrix.getWidth();
    
      int bitMatrixHeight = bitMatrix.getHeight();
    
      int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];
    
      for (int y = 0; y < bitMatrixHeight; y++) {
          int offset = y * bitMatrixWidth;
    
         for (int x = 0; x < bitMatrixWidth; x++) {
    
             pixels[offset + x] = bitMatrix.get(x, y) ?
                    getResources().getColor(R.color.QRCodeBlackColor):getResources().getColor(R.color.QRCodeWhiteColor);
          }
        }
        Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);
    
       bitmap.setPixels(pixels, 0, 350, 0, 0, bitMatrixWidth, bitMatrixHeight);
       return bitmap;
    }
    
    
    
    
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
      if(result != null) {
        if(result.getContents() == null) {
            Log.e("Scan*******", "Cancelled scan");
    
         } else {
            Log.e("Scan", "Scanned");
    
            tv_qr_readTxt.setText(result.getContents());
            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
         }
      } else {
          // This is important, otherwise the result will not be passed to the fragment
        super.onActivityResult(requestCode, resultCode, data);
         }
       }
     }
    
  5. You can download full source code from GitHub. GitHub link is : https://github.com/enamul95/QRCode

Why does cURL return error "(23) Failed writing body"?

For me, it was permission issue. Docker run is called with a user profile but root is the user inside the container. The solution was to make curl write to /tmp since that has write permission for all users , not just root.

I used the -o option.

-o /tmp/file_to_download

How do you exit from a void function in C++?

Use a return statement!

return;

or

if (condition) return;

You don't need to (and can't) specify any values, if your method returns void.

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

As I have noticed this error occurs under two circumstances,

  1. If you have used train_test_split() to split your data, you have to make sure that you reset the index of the data (specially when taken using a pandas series object): y_train, y_test indices should be resetted. The problem is when you try to use one of the scores from sklearn.metrics such as; precision_score, this will try to match the shuffled indices of the y_test that you got from train_test_split().

so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)

  1. Then again you can still have this error if your predicted 'True Positives' is 0, which is used for precision, recall and f1_scores. You can visualize this using a confusion_matrix. If the classification is multilabel and you set param: average='weighted'/micro/macro you will get an answer as long as the diagonal line in the matrix is not 0

Hope this helps.

How to delete a workspace in Perforce (using p4v)?

In P4V click View > Workspaces

If the workspace to be deleted is not visible in the list you may have to uncheck the box Show only workspaces available for use on this computer

Right-click the workspace to be deleted and choose Edit Workspace 'My_workspace'

On the Advanced tab uncheck the box Locked: only the owner can edit workspace settings > then click OK

Now back on the Workspaces tab of Perforce right-click the workspace to be deleted and choose Delete Workspace 'My_workspace'

P4V should remove the item from the drop-down list when clicking on it.

There is a case where a previously deleted workspace remains in the drop-down list, and P4V displays the following error:

P4V Workspace Switch Error. This workspace cannot be used on this computer either because the host field does not match your computer name or the workspace root cannot be used on this computer.

If this error occurs, the workspace(possibly on another host) may have only been unloaded. Click the P4V Workspaces Recycle bin

P4V Recycle

In the resulting Unloaded Workspaces window right-click the offending workspace and choose Delete Workspace 'My_workspace'. P4V should now remove the workspace item from the drop-down list.

Bootstrap Carousel : Remove auto slide

$(document).ready(function() {
  $('#media').carousel({
    pause: true,
    interval: 40000,
  });
});

By using the above script, you will be able to move the images automaticaly

$(document).ready(function() {
  $('#media').carousel({
    pause: true,
    interval: false,
  });
});

By using the above script, auto-rotation will be blocked because interval is false

Redirect From Action Filter Attribute

Here is a solution that also takes in account if you are using Ajax requests.

using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace YourNamespace{        
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizeCustom : ActionFilterAttribute {
        public override void OnActionExecuting(ActionExecutingContext context) {
            if (YourAuthorizationCheckGoesHere) {               
                string area = "";// leave empty if not using area's
                string controller = "ControllerName";
                string action = "ActionName";
                var urlHelper = new UrlHelper(context.RequestContext);                  
                if (context.HttpContext.Request.IsAjaxRequest()){ // Check if Ajax
                    if(area == string.Empty)
                        context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(controller, action))}');</script>");
                    else
                        context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(area, controller, action))}');</script>");
                } else   // Non Ajax Request                      
                    context.Result = new RedirectToRouteResult(new RouteValueDictionary( new{ area, controller, action }));             
            }
            base.OnActionExecuting(context);
        }
    }
}

How do I run git log to see changes only for a specific branch?

Use:

git log --graph --abbrev-commit --decorate  --first-parent <branch_name>

It is only for the target branch (of course --graph, --abbrev-commit --decorate are more polishing).

The key option is --first-parent: "Follow only the first parent commit upon seeing a merge commit" (https://git-scm.com/docs/git-log)

It prevents the commit forks from being displayed.

href="file://" doesn't work

Share your folder for "everyone" or some specific group and try this:

_x000D_
_x000D_
<a href="file://YOURSERVERNAME/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf"> Download PDF </a> 
_x000D_
_x000D_
_x000D_

height: 100% for <div> inside <div> with display: table-cell

When you use % for setting heights or widths, always set the widths/heights of parent elements as well:

_x000D_
_x000D_
.table {_x000D_
    display: table;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
    border: 2px solid black;_x000D_
    vertical-align: top;_x000D_
    display: table-cell;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    height: 100%;_x000D_
    border: 2px solid green;_x000D_
    -moz-box-sizing: border-box;_x000D_
}
_x000D_
<div class="table">_x000D_
    <div class="cell">_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
    </div>_x000D_
    <div class="cell">_x000D_
        <div class="container">Text</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

@ variables in Ruby on Rails

title is a local variable. They only exists within its scope (current block)

@title is an instance variable - and is available to all methods within the class.

You can read more here: http://strugglingwithruby.blogspot.dk/2010/03/variables.html

In Ruby on Rails - declaring your variables in your controller as instance variables (@title) makes them available to your view.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

span with onclick event inside a tag

When you click on hide me, both a and span clicks are triggering. Since the page is redirecting to another, you cannot see the working of hide()

You can see this for more clarification

http://jsfiddle.net/jzn82/

Get line number while using grep

grep -A20 -B20 pattern file.txt

Search pattern and show 20 lines after and before pattern

How to resolve Unneccessary Stubbing exception

For me neither the @Rule nor the @RunWith(MockitoJUnitRunner.Silent.class) suggestions worked. It was a legacy project where we upgraded to mockito-core 2.23.0.

We could get rid of the UnnecessaryStubbingException by using:

Mockito.lenient().when(mockedService.getUserById(any())).thenReturn(new User());

instead of:

when(mockedService.getUserById(any())).thenReturn(new User());

Needless to say that you should rather look at the test code, but we needed to get the stuff compiled and the tests running first of all ;)

Which is a better way to check if an array has more than one element?

if(is_array($arr) && count($arr) > 1)

Just to be sure that $arr is indeed an array.

sizeof is an alias of count, I prefer to use count because:

  1. 1 less character to type
  2. sizeof at a quick glance might mean a size of an array in terms of memory, too technical :(

Android/Java - Date Difference in days

All of these solutions suffer from one of two problems. Either the solution isn't perfectly accurate due to rounding errors, leap days and seconds, etc. or you end up looping over the number of days in between your two unknown dates.

This solution solves the first problem, and improves the second by a factor of roughly 365, better if you know what your max range is.

/**
 * @param thisDate
 * @param thatDate
 * @param maxDays
 *            set to -1 to not set a max
 * @returns number of days covered between thisDate and thatDate, inclusive, i.e., counting both
 *          thisDate and thatDate as an entire day. Will short out if the number of days exceeds
 *          or meets maxDays
 */
public static int daysCoveredByDates(Date thisDate, Date thatDate, int maxDays) {
    //Check inputs
    if (thisDate == null || thatDate == null) {
        return -1;
    }

    //Set calendar objects
    Calendar startCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();
    if (thisDate.before(thatDate)) {
        startCal.setTime(thisDate);
        endCal.setTime(thatDate);
    }
    else {
        startCal.setTime(thatDate);
        endCal.setTime(thisDate);
    }

    //Get years and dates of our times.
    int startYear = startCal.get(Calendar.YEAR);
    int endYear = endCal.get(Calendar.YEAR);
    int startDay = startCal.get(Calendar.DAY_OF_YEAR);
    int endDay = endCal.get(Calendar.DAY_OF_YEAR);

    //Calculate the number of days between dates.  Add up each year going by until we catch up to endDate.
    while (startYear < endYear && maxDays >= 0 && endDay - startDay + 1 < maxDays) {
        endDay += startCal.getActualMaximum(Calendar.DAY_OF_YEAR); //adds the number of days in the year startDate is currently in
        ++startYear;
        startCal.set(Calendar.YEAR, startYear); //reup the year
    }
    int days = endDay - startDay + 1;

    //Honor the maximum, if set
    if (maxDays >= 0) {
        days = Math.min(days, maxDays);
    }
    return days;
}

If you need days between dates (uninclusive of the latter date), just get rid of the + 1 when you see endDay - startDay + 1.

Writing data into CSV file in C#

You can use AppendAllText instead:

File.AppendAllText(filePath, csv);

As the documentation of WriteAllText says:

If the target file already exists, it is overwritten

Also, note that your current code is not using proper new lines, for example in Notepad you'll see it all as one long line. Change the code to this to have proper new lines:

string csv = string.Format("{0},{1}{2}", first, image, Environment.NewLine);

Maven: The packaging for this project did not assign a file to the build artifact

I have seen this error occur when the plugins that are needed are not specifically mentioned in the pom. So

mvn clean install

will give the exception if this is not added:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.5.2</version>
 </plugin>

Likewise,

mvn clean install deploy

will fail on the same exception if something like this is not added:

<plugin>
   <artifactId>maven-deploy-plugin</artifactId>
   <version>2.8.1</version>
   <executions>
      <execution>
         <id>default-deploy</id>
         <phase>deploy</phase>
         <goals>
            <goal>deploy</goal>
         </goals>
      </execution>
   </executions>
</plugin>

It makes sense, but a clearer error message would be welcome

How to add a TextView to a LinearLayout dynamically in Android?

LayoutParams lparams = new LayoutParams(
   LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);

You can change lparams according to your needs

Android Crop Center of Bitmap

Have you considered doing this from the layout.xml ? You could set for your ImageView the ScaleType to android:scaleType="centerCrop" and set the dimensions of the image in the ImageView inside the layout.xml.

Clicking submit button of an HTML form by a Javascript code

document.getElementById('loginSubmit').submit();

or, use the same code as the onclick handler:

changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();

(Though that onclick handler is kind of stupidly-written: document.forms['loginForm'] could be replaced with this.)

Array slices in C#

If you want IEnumerable<byte>, then just

IEnumerable<byte> data = foo.Take(x);

How to add List<> to a List<> in asp.net

Use List.AddRange(collection As IEnumerable(Of T)) method.

It allows you to append at the end of your list another collection/list.

Example:

List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);

Can I have multiple primary keys in a single table?

Yes, Its possible in SQL, but we can't set more than one primary keys in MsAccess. Then, I don't know about the other databases.

CREATE TABLE CHAPTER (
    BOOK_ISBN VARCHAR(50) NOT NULL,
    IDX INT NOT NULL,
    TITLE VARCHAR(100) NOT NULL,
    NUM_OF_PAGES INT,
    PRIMARY KEY (BOOK_ISBN, IDX)
);

What is the difference between JDK and JRE?

jdk is necessary to compile to code and convert java code to byte codes while jre is necessary for executing the byte codes.

How do I check in JavaScript if a value exists at a certain array index?

when you create empty array values ARE NOT undefined, they are EMPTY

var arr = new Array(10); // (10) [empty × 10]

but when you get item by index receive undefined

arr[0]; // undefined

so you can't know by === comparing if they are undefined or empty

we can make it by using JSON.stringify, converting whole array it replaces empty values with null

JSON.stringify(arr); // "[null,null,null,null,null,null,null,null,null,null]"
JSON.stringify(arr[0]); // but for single item it returns undefined

so real check for empty value:

arr[0] !== null && JSON.stringify(arr.map(item => !item)).slice(1, -1).split(',')[0] === 'null'
  1. compare item with null (should be not equal)
  2. map array removing false instead existing values (ensure stringified structure to be comma-separated without redundant commas)
  3. JSON.stringify array
  4. remove brackets from string
  5. split into array by comma
  6. compare with null

VBA Count cells in column containing specified value

Not what you asked but may be useful nevertheless.

Of course you can do the same thing with matrix formulas. Just read the result of the cell that contains:

Cell A1="Text to search"
Cells A2:C20=Range to search for

=COUNT(SEARCH(A1;A2:C20;1))

Remember that entering matrix formulas needs CTRL+SHIFT+ENTER, not just ENTER. After, it should look like :

{=COUNT(SEARCH(A1;A2:C20;1))}

Matplotlib - How to plot a high resolution graph?

At the end of your for() loop, you can use the savefig() function instead of plt.show() and set the name, dpi and format of your figure.

E.g. 1000 dpi and eps format are quite a good quality, and if you want to save every picture at folder ./ with names 'Sample1.eps', 'Sample2.eps', etc. you can just add the following code:

for fname in glob("./*.txt"):
    # Your previous code goes here
    [...]

    plt.savefig("./{}.eps".format(fname), bbox_inches='tight', format='eps', dpi=1000)

Wait for a process to finish

I found "kill -0" does not work if the process is owned by root (or other), so I used pgrep and came up with:

while pgrep -u root process_name > /dev/null; do sleep 1; done

This would have the disadvantage of probably matching zombie processes.

how to delete files from amazon s3 bucket?

Below is code snippet you can use to delete the bucket,

import boto3, botocore
from botocore.exceptions import ClientError

s3 = boto3.resource("s3",aws_access_key_id='Your-Access-Key',aws_secret_access_key='Your-Secret-Key')
s3.Object('Bucket-Name', 'file-name as key').delete()

find if an integer exists in a list of integers

bool vExist = false;
int vSelectValue = 1;

List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);

IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
    vExist = true;
}

Exact difference between CharSequence and String in java

CharSequence is a contract (interface), and String is an implementation of this contract.

public final class String extends Object 
    implements Serializable, Comparable<String>, CharSequence

The documentation for CharSequence is:

A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.

Change the current directory from a Bash script

Add below cd line in your shellscript this:

exec $SHELL

Is there a way to include commas in CSV columns without breaking the formatting?

The problem with the CSV format, is there's not one spec, there are several accepted methods, with no way of distinguishing which should be used (for generate/interpret). I discussed all the methods to escape characters (newlines in that case, but same basic premise) in another post. Basically it comes down to using a CSV generation/escaping process for the intended users, and hoping the rest don't mind.

Reference spec document.

Keep CMD open after BAT file executes

start cmd /k did the magic for me. I actually used it for preparing cordova phonegap app it runs the command, shows the result and waits for the user to close it. Below is the simple example

start cmd /k echo Hello, World!

What I did use in my case

start cmd /k cordova prepare

Update

You could even have a title for this by using

start "My Title" echo Hello, World!

How do I find the difference between two values without knowing which is larger?

abs(x-y) will do exactly what you're looking for:

In [1]: abs(1-2)
Out[1]: 1

In [2]: abs(2-1)
Out[2]: 1

How to create and handle composite primary key in JPA

The MyKey class must implement Serializable if you are using @IdClass

Jquery, set value of td in a table?

From:

it could be:

.html()

In an HTML document, .html() can be used to get the contents of any element.

.text()

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements.

.val()

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

How to print exact sql query in zend framework ?

$db->getProfiler()->setEnabled(true);

// your code    
$this->update('table', $data, $where);    
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQuery());    
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQueryParams());    
$db->getProfiler()->setEnabled(false);

"Fade" borders in CSS

You could also use box-shadow property with higher value of blur and rgba() color to set opacity level. Sounds like a better choice in your case.

box-shadow: 0 30px 40px rgba(0,0,0,.1);

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

How to check if a network port is open on linux?

Please check Michael answer and vote for it. It is the right way to check open ports. Netstat and other tools are not any use if you are developing services or daemons. For instance, I am crating modbus TCP server and client services for an industrial network. The services can listen to any port, but the question is whether that port is open? The program is going to be used in different places, and I cannot check them all manually, so this is what I did:

from contextlib import closing
import socket
class example:
    def __init__():

       self.machine_ip = socket.gethostbyname(socket.gethostname())
       self.ready:bool = self.check_socket()

    def check_socket(self)->bool:
        result:bool = True
        with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        modbus_tcp_port:int = 502
        if not sock.connect_ex((self.machine_ip, modbus_tcp_port)) == 0:
            result = False
        return result

Embed HTML5 YouTube video without iframe?

Yes. Youtube API is the best resource for this.

There are 3 way to embed a video:

  • IFrame embeds using <iframe> tags
  • IFrame embeds using the IFrame Player API
  • AS3 (and AS2*) object embeds DEPRECATED

I think you are looking for the second one of them:

IFrame embeds using the IFrame Player API

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

<div id="ytplayer"></div>

<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE'
    });
  }
</script>

Here are some instructions where you may take a look when starting using the API.


An embed example without using iframe is to use <object> tag:

<object width="640" height="360">
    <param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3"/
    <param name="allowFullScreen" value="true"/>
    <param name="allowscriptaccess" value="always"/>
    <embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>

(replace yt-video-id with your video id)

JSFIDDLE

How to decode HTML entities using jQuery?

encode:

_x000D_
_x000D_
$("<textarea/>").html('<a>').html(); // return '&lt;a&gt'
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea/>
_x000D_
_x000D_
_x000D_

decode:

_x000D_
_x000D_
$("<textarea/>").html('&lt;a&gt').val() // return '<a>'
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea/>
_x000D_
_x000D_
_x000D_

Force an Android activity to always use landscape mode

In the manifest:

<activity  android:name=".YourActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|screenSize">

In your activity:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.your_activity_layout);

Java; String replace (using regular expressions)?

private String removeScript(String content) {
    Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
            Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    return p.matcher(content).replaceAll("");
}

Replacing column values in a pandas DataFrame

w.replace({'female':{'female':1, 'male':0}}, inplace = True)

The above code will replace 'female' with 1 and 'male' with 0, only in the column 'female'

Maximum length of HTTP GET request

Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.

How do I deal with corrupted Git object files?

For anyone stumbling across the same issue:

I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

How to convert a date to milliseconds

The SimpleDateFormat class allows you to parse a String into a java.util.Date object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime().

The full example:

String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();

Note that this gives you a long and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat class has tons on information on how to set it up to parse different formats.

Read Excel sheet in Powershell

Sorry I know this is an old one but still felt like helping out ^_^

Maybe it's the way I read this but assuming the excel sheet 1 is called "London" and has this information; B5="Marleybone" B6="Paddington" B7="Victoria" B8="Hammersmith". And the excel sheet 2 is called "Nottingham" and has this information; C5="Alverton" C6="Annesley" C7="Arnold" C8="Askham". Then I think this code below would work. ^_^

$xlCellTypeLastCell = 11 
$startRow = 5

$excel = new-object -com excel.application
$wb = $excel.workbooks.open("C:\users\administrator\my_test.xls")

for ($i = 1; $i -le $wb.sheets.count; $i++)
    {
        $sh = $wb.Sheets.Item($i)
        $endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
        $col = $col + $i - 1
        $city = $wb.Sheets.Item($i).name
        $rangeAddress = $sh.Cells.Item($startRow, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
        $sh.Range($rangeAddress).Value2 | foreach{
            New-Object PSObject -Property @{City = $city; Area=$_}
        }
    }

$excel.Workbooks.Close()

This should be the output (without the commas):

City, Area
---- ----
London, Marleybone
London, Paddington
London, Victoria
London, Hammersmith
Nottingham, Alverton
Nottingham, Annesley
Nottingham, Arnold
Nottingham, Askham

Does Hive have a String split function?

Another interesting usecase for split in Hive is when, for example, a column ipname in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:

SELECT split(ipname,'[\.]')[0] FROM tablename;

Show message box in case of exception

There are many ways, for example:

Method one:

public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

Method two:

public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}

Can I force a page break in HTML printing?

Just wanted to put an update. page-break-after is a legacy property now.

Official page states

This property has been replaced by the break-after property.

Saving a Excel File into .txt format without quotes

PRN solution works only for simple data in the cells, for me it cuts only first 6 signs from 200 characters cell.

These are the main file formats in Excel 2007-2016, Note: In Excel for the Mac the values are +1

51 = xlOpenXMLWorkbook (without macro's in 2007-2016, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2016, xlsm)
50 = xlExcel12 (Excel Binary Workbook in 2007-2016 with or without macro's, xlsb)
56 = xlExcel8 (97-2003 format in Excel 2007-2016, xls)

From XlFileFormat FileFormat Property

Keep in mind others FileFormatNumbers for SaveAs method:

FileExtStr = ".csv": FileFormatNum = 6
FileExtStr = ".txt": FileFormatNum = -4158
FileExtStr = ".prn": FileFormatNum = 36

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Straight from the ECMA-262, Fifth Edition ECMAScript Specification:

7.9.1 Rules of Automatic Semicolon Insertion

There are three basic rules of semicolon insertion:

  1. When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
    • The offending token is separated from the previous token by at least one LineTerminator.
    • The offending token is }.
  2. When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
  3. When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation "[no LineTerminator here]" within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (see 12.6.3).

String Array object in Java

First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:

class Athlete {

    private String name;
    private String country;

    private List<Dive> dives;

    public Athlete(String name, String country){
       this.name = name;
       this.country = country;
    }

    public String getName(){
        return this.name;
    }

    public String getCountry(){
        return this.country;
    }

    public String getDives(){
        return this.dives;
    }

    public void addDive(Dive dive){
        this.dives.add(dive);
    }
}

Then for the Dive class:

class Dive {

    private Athlete athlete;
    private Date date;
    private double score;

    public Dive(Athlete athlete, double score){
        this.athlete = athlete;
        this.score = score;
        this.date = new Date();
    }

    public Athlete getAthlete(){
        return this.athlete;
    }

    public Athlete getAthlete(){
        return this.athlete;
    }

    public Athlete getAthlete(){
        return this.athlete;
    }

}

Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:

@Test
public void testThatDivesRetainInformation(){
    Athlete art = new Athlete("Art", "Canada");
    Dive art1 = new Dive(art, 8.5);
    Dive art2 = new Dive(art, 8.0);
    Dive art3 = new Dive(art, 8.8);
    Dive art4 = new Dive(art, 9.2);

    assertThat(art.getDives().size(), is(5));
    }

Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.

You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.

The role of #ifdef and #ifndef

Someone should mention that in the question there is a little trap. #ifdef will only check if the following symbol has been defined via #define or by command line, but its value (its substitution in fact) is irrelevant. You could even write

#define one

precompilers accept that. But if you use #if it's another thing.

#define one 0
#if one
    printf("one evaluates to a truth ");
#endif
#if !one
    printf("one does not evaluate to truth ");
#endif

will give one does not evaluate to truth. The keyword defined allows to get the desired behaviour.

#if defined(one) 

is therefore equivalent to #ifdef

The advantage of the #if construct is to allow a better handling of code paths, try to do something like that with the old #ifdef/#ifndef pair.

#if defined(ORA_PROC) || defined(__GNUC) && __GNUC_VERSION > 300

Django - how to create a file and save it to a model's FileField?

Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.

Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).

Django 1.4.1

Python 2.7.3

#Model
class MonthEnd(models.Model):
    report = models.FileField(db_index=True, upload_to='not_used')

import csv
from os.path import join

#build and store the file
def write_csv():
    path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
    f = open(path, "w+b")

    #wipe the existing content
    f.truncate()

    csv_writer = csv.writer(f)
    csv_writer.writerow(('col1'))

    for num in range(3):
        csv_writer.writerow((num, ))

    month_end_file = MonthEnd()
    month_end_file.report.name = path
    month_end_file.save()

from my_app.models import MonthEnd

#serve it up as a download
def get_report(request):
    month_end = MonthEnd.objects.get(file_criteria=criteria)

    response = HttpResponse(month_end.report, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=report.csv'

    return response

How to skip to next iteration in jQuery.each() util?

What they mean by non-false is:

return true;

So this code:

_x000D_
_x000D_
var arr = ["one", "two", "three", "four", "five"];_x000D_
$.each(arr, function(i) {_x000D_
  if (arr[i] == 'three') {_x000D_
    return true;_x000D_
  }_x000D_
  console.log(arr[i]);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

will log one, two, four, five.

See changes to a specific file using git

You can use gitk [filename] to see the changes log