Programs & Examples On #Linfu

LinFu is a framework that adds mixins, inversion of control, DbC, and other language features to the Common Language Runtime.

How to import a csv file into MySQL workbench?

I guess you're missing the ENCLOSED BY clause

LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv'
INTO TABLE test.dummy FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n';

And specify the csv file full path

Load Data Infile - MySQL documentation

setTimeout / clearTimeout problems

The problem is that the timer variable is local, and its value is lost after each function call.

You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:

var endAndStartTimer = (function () {
  var timer; // variable persisted here
  return function () {
    window.clearTimeout(timer);
    //var millisecBeforeRedirect = 10000; 
    timer = window.setTimeout(function(){alert('Hello!');},10000); 
  };
})();

How can I get the status code from an http error in Axios?

In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

This way, every http response resolves the promise returned from axios.

https://github.com/axios/axios#handling-errors

Environment variables in Jenkins

The environment variables displayed in Jenkins (Manage Jenkins -> System information) are inherited from the system (i.e. inherited environment variables)

If you run env command in a shell you should see the same environment variables as Jenkins shows.

These variables are either set by the shell/system or by you in ~/.bashrc, ~/.bash_profile.

There are also environment variables set by Jenkins when a job executes, but these are not displayed in the System Information.

How to share data between different threads In C# using AOP?

Look at the following example code:

public class MyWorker
{
    public SharedData state;
    public void DoWork(SharedData someData)
    {
        this.state = someData;
        while (true) ;
    }

}

public class SharedData {
    X myX;
    public getX() { etc
    public setX(anX) { etc

}

public class Program
{
    public static void Main()
    {
        SharedData data = new SharedDate()
        MyWorker work1 = new MyWorker(data);
        MyWorker work2 = new MyWorker(data);
        Thread thread = new Thread(new ThreadStart(work1.DoWork));
        thread.Start();
        Thread thread2 = new Thread(new ThreadStart(work2.DoWork));
        thread2.Start();
    }
}

In this case, the thread class MyWorker has a variable state. We initialise it with the same object. Now you can see that the two workers access the same SharedData object. Changes made by one worker are visible to the other.

You have quite a few remaining issues. How does worker 2 know when changes have been made by worker 1 and vice-versa? How do you prevent conflicting changes? Maybe read: this tutorial.

JavaScript/jQuery to download file via POST with JSON data

Another approach instead of saving the file on the server and retrieving it, is to use .NET 4.0+ ObjectCache with a short expiration until the second Action (at which time it can be definitively dumped). The reason that I want to use JQuery Ajax to do the call, is that it is asynchronous. Building my dynamic PDF file takes quite a bit of time, and I display a busy spinner dialog during that time (it also allows other work to be done). The approach of using the data returned in the "success:" to create a Blob does not work reliably. It depends on the content of the PDF file. It is easily corrupted by data in the response, if it is not completely textual which is all that Ajax can handle.

Dynamically create Bootstrap alerts box through JavaScript

FWIW I created a JavaScript class that can be used at run-time.
It's over on GitHub, here.

There is a readme there with a more in-depth explanation, but I'll do a quick example below:

var ba = new BootstrapAlert();
ba.addP("Some content here");
$("body").append(ba.render());

The above would create a simple primary alert with a paragraph element inside containing the text "Some content here".

There are also options that can be set on initialisation.
For your requirement you'd do:

var ba = new BootstrapAlert({
    dismissible: true,
    background: 'warning'
});
ba.addP("Invalid Credentials");
$("body").append(ba.render());

The render method will return an HTML element, which can then be inserted into the DOM. In this case, we append it to the bottom of the body tag.

This is a work in progress library, but it still is in a very good working order.

Cannot open output file, permission denied

I just had the same issue. And i experienced that it always happens when i run the programm and change some code without finishing the programm still running. After that the "cannot open ..." message appears.

However i got rid of it by clicking the "Terminate" button at the very top-right side of the console window (red button) and after that "remove all terminated launches" (two x'es right next to the terminate button). This seems to close the running programm and everything works fine after :) hope this may help anyone

get next and previous day with PHP

Very easy with the dateTime() object, too.

$tomorrow = new DateTime('tomorrow');
echo $tomorrow->format("Y-m-d"); // Tomorrow's date

$yesterday = new DateTime('yesterday');
echo $yesterday->format("Y-m-d"); // Yesterday's date

Go: panic: runtime error: invalid memory address or nil pointer dereference

According to the docs for func (*Client) Do:

"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.

When err is nil, resp always contains a non-nil resp.Body."

Then looking at this code:

res, err := client.Do(req)
defer res.Body.Close()

if err != nil {
    return nil, err
}

I'm guessing that err is not nil. You're accessing the .Close() method on res.Body before you check for the err.

The defer only defers the function call. The field and method are accessed immediately.


So instead, try checking the error immediately.

res, err := client.Do(req)

if err != nil {
    return nil, err
}
defer res.Body.Close()

What is the difference between Tomcat, JBoss and Glassfish?

Tomcat is merely an HTTP server and Java servlet container. JBoss and GlassFish are full-blown Java EE application servers, including an EJB container and all the other features of that stack. On the other hand, Tomcat has a lighter memory footprint (~60-70 MB), while those Java EE servers weigh in at hundreds of megs. Tomcat is very popular for simple web applications, or applications using frameworks such as Spring that do not require a full Java EE server. Administration of a Tomcat server is arguably easier, as there are fewer moving parts.

However, for applications that do require a full Java EE stack (or at least more pieces that could easily be bolted-on to Tomcat)... JBoss and GlassFish are two of the most popular open source offerings (the third one is Apache Geronimo, upon which the free version of IBM WebSphere is built). JBoss has a larger and deeper user community, and a more mature codebase. However, JBoss lags significantly behind GlassFish in implementing the current Java EE specs. Also, for those who prefer a GUI-based admin system... GlassFish's admin console is extremely slick, whereas most administration in JBoss is done with a command-line and text editor. GlassFish comes straight from Sun/Oracle, with all the advantages that can offer. JBoss is NOT under the control of Sun/Oracle, with all the advantages THAT can offer.

Run Java Code Online

Compilr is an online java compiler. It provides syntax highlighting and reports any errors back to you. It's a project I'm working on, so if you have any feedback please leave a comment!

Eclipse Build Path Nesting Errors

I had the same issue and correct answer above did not work for me. What I did to resolve it was to go to Build Path->Configure Build Path and under the source tab I removed all the sources (which only had one source) and reconfigured them from there. I ended up removing the project from eclipse and import the maven project again in order to clear up the error.

When to use margin vs padding in CSS

It's good to know the differences between margin and padding. Here are some differences:

  • Margin is outer space of an element, while padding is inner space of an element.

  • Margin is the space outside the border of an element, while padding is the space inside the border of it.

  • Margin accepts the value of auto: margin: auto, but you can't set padding to auto.

  • Margin can be set to any number, but padding must be non-negative.

  • When you style an element, padding will also be affected (e.g. background color), but not margin.

How to use greater than operator with date?

you have enlosed start_date with single quote causing it to become string, use backtick instead

SELECT * FROM `la_schedule` WHERE `start_date` > '2012-11-18';

ssl_error_rx_record_too_long and Apache SSL

Old question, but first result in Google for me, so here's what I had to do.

Ubuntu 12.04 Desktop with Apache installed

All the configuration and mod_ssl was installed when I installed Apache, but it just wasn't linked in the right spots yet. Note: all paths below are relative to /etc/apache2/

mod_ssl is stored in ./mods-available, and the SSL site configuration is in ./sites-available, you just have to link these to their correct places in ./mods-enabled and ./sites-enabled

cd /etc/apache2
cd ./mods-enabled
sudo ln -s ../mods-available/ssl.* ./
cd ../sites-enabled
sudo ln -s ../sites-available/default-ssl ./

Restart Apache and it should work. I was trying to access https://localhost, so your results may vary for external access, but this worked for me.

Parsing arguments to a Java command line program

You could use https://github.com/jankroken/commandline , here's how to do that:

To make this example work, I must make assumptions about what the arguments means - just picking something here...

-r opt1 => replyAddress=opt1
-S opt2 arg1 arg2 arg3 arg4 => subjects=[opt2,arg1,arg2,arg3,arg4]
--test = test=true (default false)
-A opt3 => address=opt3

this can then be set up this way:

public class MyProgramOptions {
  private String replyAddress;
  private String address;
  private List<String> subjects;
  private boolean test = false;

  @ShortSwitch("r")
  @LongSwitch("replyAddress") // if you also want a long variant. This can be skipped
  @SingleArgument
  public void setReplyAddress(String replyAddress) {
    this.replyAddress = replyAddress;
  }

  @ShortSwitch("S")
  @AllAvailableArguments
  public void setSubjects(List<String> subjects) {
    this.subjects = subjects;
  }

  @LongSwitch("test")
  @Toggle(true)
  public void setTest(boolean test) {
    this.test = test;
  }

  @ShortSwitch("A")
  @SingleArgument
  public void setAddress(String address) {
    this.address = address;
  }

  // getters...
}

and then in the main method, you can just do:

public final static void main(String[] args) {
  try {
    MyProgramOptions options = CommandLineParser.parse(MyProgramOptions.class, args, OptionStyle.SIMPLE);

    // and then you can pass options to your application logic...

  } catch
    ...
  }
}

how to read value from string.xml in android?

String myString = getResources().getString(R.string.here_your_string_name);

Now your string is copied into myString. I hope it will work for you.

Oracle: Import CSV file

An alternative solution is using an external table: http://www.orafaq.com/node/848

Use this when you have to do this import very often and very fast.

How to call VS Code Editor from terminal / command line

A simple way is to go to your Project where you want to open it and type

code.cmd D:\PathTo\yourProject\MyProject

enter image description here

That's it. It will open your project in Visual Studio Code.

Serializing enums with Jackson

In Spring Boot 2, the easiest way is to declare in your application.properties:

spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true

and define the toString() method of your enums.

C# Encoding a text string with line breaks

Try this :

string myStr = ...
myStr = myStr.Replace("\n", Environment.NewLine)

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Best Java obfuscator?

If a computer can run it, a suitably motivated human can reverse-engineer it.

How to get document height and width without using jquery

If you want to get the full width of the page, including overflow, use document.body.scrollWidth.

How to calculate modulus of large numbers?

Jason's answer in Java (note i < exp).

private static void testModulus() {
    int bse = 5, exp = 55, mod = 221;

    int a1 = bse % mod;
    int p = 1;

    System.out.println("1. " + (p % mod) + " * " + bse + " = " + (p % mod) * bse + " mod " + mod);

    for (int i = 1; i < exp; i++) {
        p *= a1;
        System.out.println((i + 1) + ". " + (p % mod) + " * " + bse + " = " + ((p % mod) * bse) % mod + " mod " + mod);
        p = (p % mod);
    }

}

UTF-8: General? Bin? Unicode?

You should also be aware of the fact, that with utf8_general_ci when using a varchar field as unique or primary index inserting 2 values like 'a' and 'á' would give a duplicate key error.

How to make a stable two column layout in HTML/CSS

I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5

This makes me happy.

Try this: Live Demo

display: table is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>.

CSS:

#container {
    background: #ccc;
    display: table
}
#left, #right {
    display: table-cell
}
#left {
    width: 150px;
    background: #f0f;
    border: 5px dotted blue;
}
#right {
    background: #aaa;
    border: 3px solid #000
}

MySQL Query - Records between Today and Last 30 Days

You need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

Also note that CURDATE() returns only the DATE portion of the date, so if you store create_date as a DATETIME with the time portion filled, this query will not select the today's records.

In this case, you'll need to use NOW instead:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

There are a few options:

  • Nest the AsyncTask class within your Activity class. Assuming you don't use the same task in multiple activities, this is the easiest way. All your code stays the same, you just move the existing task class to be a nested class inside your activity's class.

    public class MyActivity extends Activity {
        // existing Activity code
        ...
    
        private class MyAsyncTask extends AsyncTask<String, Void, String> {
            // existing AsyncTask code
            ...
        }
    }
    
  • Create a custom constructor for your AsyncTask that takes a reference to your Activity. You would instantiate the task with something like new MyAsyncTask(this).execute(param1, param2).

    public class MyAsyncTask extends AsyncTask<String, Void, String> {
        private Activity activity;
    
        public MyAsyncTask(Activity activity) {
            this.activity = activity;
        }
    
        // existing AsyncTask code
        ...
    }
    

How to restore/reset npm configuration to default values?

npm config edit

Opens the config file in an editor. Use the --global flag to edit the global config. now you can delete what ever the registry's you don't want and save file.

npm config list will display the list of available now.

Use JavaScript to place cursor at end of text in text input element

I've tried the following with quite great success in chrome

$("input.focus").focus(function () {
    var val = this.value,
        $this = $(this);
    $this.val("");

    setTimeout(function () {
        $this.val(val);
    }, 1);
});

Quick rundown:

It takes every input field with the class focus on it, then stores the old value of the input field in a variable, afterwards it applies the empty string to the input field.

Then it waits 1 milisecond and puts in the old value again.

How to select only the records with the highest date in LINQ

If you want the whole record,here is a lambda way:

var q = _context
             .lasttraces
             .GroupBy(s => s.AccountId)
             .Select(s => s.OrderByDescending(x => x.Date).FirstOrDefault());

How to position three divs in html horizontally?

Get rid of the position:relative; and replace it with float:left; and float:right;.

Example in jsfiddle: http://jsfiddle.net/d9fHP/1/

        <html>
<title>
Website Title </title>
<div id="the whole thing" style="float:left; height:100%; width:100%">
    <div id="leftThing" style="float:left; width:25%; background-color:blue;">
         Left Side Menu
    </div>
    <div id="content" style="float:left; width:50%; background-color:green;">
         Random Content
    </div>
    <div id="rightThing" style="float:right; width:25%; background-color:yellow;">
         Right Side Menu
    </div>
</div>
</html>?

Method List in Visual Studio Code

There's no such feature today, the CTRL+SHIFT+O == CTRL+P @ doesn't work for all languages.

As a last resort you can use the search panel - although it is not so fast an easy to use as you'd like - you can enter this regex in the search panel to find all functions:

function\s([_A-Za-z0-9]+)\s*\(

How to assert two list contain the same elements in Python?

Slightly faster version of the implementation (If you know that most couples lists will have different lengths):

def checkEqual(L1, L2):
    return len(L1) == len(L2) and sorted(L1) == sorted(L2)

Comparing:

>>> timeit(lambda: sorting([1,2,3], [3,2,1]))
2.42745304107666
>>> timeit(lambda: lensorting([1,2,3], [3,2,1]))
2.5644469261169434 # speed down not much (for large lists the difference tends to 0)

>>> timeit(lambda: sorting([1,2,3], [3,2,1,0]))
2.4570400714874268
>>> timeit(lambda: lensorting([1,2,3], [3,2,1,0]))
0.9596951007843018 # speed up

Open S3 object as a string with Boto3

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))

How to install lxml on Ubuntu

For Ubuntu 14.04

sudo apt-get install python-lxml

worked for me.

How to get list of all installed packages along with version in composer?

The behaviour of this command as been modified so you don't have to pass the -i option:

[10:19:05] coil@coil:~/workspace/api$ composer show -i
You are using the deprecated option "installed". 
Only installed packages are shown by default now. 
The --all option can be used to show all packages.

.autocomplete is not a function Error

You are calling the function before the page loads jQuery. It is always advisable to use jQuery inside

$(document).ready(function(){ //Your code here });

In your case:

$(document).ready(function(){
   $(function(){
      $( "#searcharea" ).autocomplete({
         source: "suggestions.php"
      });
      $( "#searchcat" ).autocomplete({
         source: "suggestions1.php"
      });
   });
});

Change background image opacity

What I did is:

<div id="bg-image"></div>
<div class="container">
    <h1>Hello World!</h1>
</div>

CSS:

html {
    height: 100%;
    width: 100%;
}
body {
    height: 100%;
    width: 100%;
}
#bg-image {
    height: 100%;
    width: 100%;
    position: absolute;
    background-image: url(images/background.jpg);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    opacity: 0.3;
}

What's wrong with using == to compare floats in Java?

As mentioned in other answers, doubles can have small deviations. And you could write your own method to compare them using an "acceptable" deviation. However ...

There is an apache class for comparing doubles: org.apache.commons.math3.util.Precision

It contains some interesting constants: SAFE_MIN and EPSILON, which are the maximum possible deviations of simple arithmetic operations.

It also provides the necessary methods to compare, equal or round doubles. (using ulps or absolute deviation)

Activate a virtualenv with a Python script

The child process environment is lost in the moment it ceases to exist, and moving the environment content from there to the parent is somewhat tricky.

You probably need to spawn a shell script (you can generate one dynamically to /tmp) which will output the virtualenv environment variables to a file, which you then read in the parent Python process and put in os.environ.

Or you simply parse the activate script in using for the line in open("bin/activate"), manually extract stuff, and put in os.environ. It is tricky, but not impossible.

How to import an Excel file into SQL Server?

There are many articles about writing code to import an excel file, but this is a manual/shortcut version:

If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.

The quickest way to get your Excel file into SQL is by using the import wizard:

  1. Open SSMS (Sql Server Management Studio) and connect to the database where you want to import your file into.
  2. Import Data: in SSMS in Object Explorer under 'Databases' right-click the destination database, select Tasks, Import Data. An import wizard will pop up (you can usually just click 'Next' on the first screen).

enter image description here

  1. The next window is 'Choose a Data Source', select Excel:

    • In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).

    • Click the 'Browse' button to select the path to the Excel file you want to import.

    • Select the version of the excel file (97-2003 is usually fine for files with a .XLS extension, or use 2007 for newer files with a .XLSX extension)
    • Tick the 'First Row has headers' checkbox if your excel file contains headers.
    • Click next.

enter image description here

  1. On the 'Choose a Destination' screen, select destination database:
    • Select the 'Server name', Authentication (typically your sql username & password) and select a Database as destination. Click Next.

enter image description here

  1. On the 'Specify Table Copy or Query' window:

    • For simplicity just select 'Copy data from one or more tables or views', click Next.
  2. 'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.

enter image description here

  1. Click Finish.

How do I trim whitespace?

You can also use very simple, and basic function: str.replace(), works with the whitespaces and tabs:

>>> whitespaces = "   abcd ef gh ijkl       "
>>> tabs = "        abcde       fgh        ijkl"

>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl

Simple and easy.

Get each line from textarea

Old tread...? Well, someone may bump into this...

Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you

Rather than using:

$values = explode("\n", $value_string);

Use a safer method like:

$values = preg_split('/[\n\r]+/', $value_string);

Concatenate a vector of strings/character

You can use stri_paste function with collapse parameter from stringi package like this:

stri_paste(letters, collapse='')
## [1] "abcdefghijklmnopqrstuvwxyz" 

And some benchmarks:

require(microbenchmark)
test <- stri_rand_lipsum(100)
microbenchmark(stri_paste(test, collapse=''), paste(test,collapse=''), do.call(paste, c(as.list(test), sep="")))
Unit: microseconds
                                      expr     min       lq     mean   median       uq     max neval
           stri_paste(test, collapse = "") 137.477 139.6040 155.8157 148.5810 163.5375 226.171   100
                paste(test, collapse = "") 404.139 406.4100 446.0270 432.3250 442.9825 723.793   100
do.call(paste, c(as.list(test), sep = "")) 216.937 226.0265 251.6779 237.3945 264.8935 405.989   100

How do I get information about an index and table owner in Oracle?

According to the docs, you can just do:

select INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS from USER_INDEXES

or

select INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS from ALL_INDEXES

if you want all indexes...

How to detect the OS from a Bash script?

You can use the following:

OS=$(uname -s)

then you can use OS variable in your script.

Revert to a commit by a SHA hash in Git?

If your changes have already been pushed to a public, shared remote, and you want to revert all commits between HEAD and <sha-id>, then you can pass a commit range to git revert,

git revert 56e05f..HEAD

and it will revert all commits between 56e05f and HEAD (excluding the start point of the range, 56e05f).

What is the difference between window, screen, and document in Javascript?

Briefly, with more detail below,

  • window is the execution context and global object for that context's JavaScript
  • document contains the DOM, initialized by parsing HTML
  • screen describes the physical display's full screen

See W3C and Mozilla references for details about these objects. The most basic relationship among the three is that each browser tab has its own window, and a window has window.document and window.screen properties. The browser tab's window is the global context, so document and screen refer to window.document and window.screen. More details about the three objects are below, following Flanagan's JavaScript: Definitive Guide.

window

Each browser tab has its own top-level window object. Each <iframe> (and deprecated <frame>) element has its own window object too, nested within a parent window. Each of these windows gets its own separate global object. window.window always refers to window, but window.parent and window.top might refer to enclosing windows, giving access to other execution contexts. In addition to document and screen described below, window properties include

  • setTimeout() and setInterval() binding event handlers to a timer
  • location giving the current URL
  • history with methods back() and forward() giving the tab's mutable history
  • navigator describing the browser software

document

Each window object has a document object to be rendered. These objects get confused in part because HTML elements are added to the global object when assigned a unique id. E.g., in the HTML snippet

<body>
  <p id="holyCow"> This is the first paragraph.</p>
</body>

the paragraph element can be referenced by any of the following:

  • window.holyCow or window["holyCow"]
  • document.getElementById("holyCow")
  • document.querySelector("#holyCow")
  • document.body.firstChild
  • document.body.children[0]

screen

The window object also has a screen object with properties describing the physical display:

  • screen properties width and height are the full screen

  • screen properties availWidth and availHeight omit the toolbar

The portion of a screen displaying the rendered document is the viewport in JavaScript, which is potentially confusing because we call an application's portion of the screen a window when talking about interactions with the operating system. The getBoundingClientRect() method of any document element will return an object with top, left, bottom, and right properties describing the location of the element in the viewport.

System.BadImageFormatException: Could not load file or assembly

I found a different solution to this issue. Apparently my IIS 7 did not have 32bit mode enabled in my Application Pool by default.

To enable 32bit mode, open IIS and select your Application Pool. Mine was named "ASP.NET v4.0".
Right click, go to "Advanced Settings" and change the section named: "Enabled 32-bit Applications" to true.

Restart your web server and try again.

I found the fix from this blog reference: http://darrell.mozingo.net/2009/01/17/running-iis-7-in-32-bit-mode/

Additionally, you can change the settings on Visual Studio. In my case, I went to Tools > Options > Projects and Solutions > Web Projects and checked Use the 64 bit version of IIS Express for web sites and projects - This was on VS Pro 2015. Nothing else fixed it but this.

How to use fetch in typescript

Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.

That being said, the following works...

 fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then((res: Actor) => {
          // res is now an Actor
      });

I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...

callBack: (response: any) => void

But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...

fetch(`http://swapi.co/api/people/1/`)
  .then(res => res.json())
  .then(res => {
      if (callback) {
        callback(res);    // Client receives the response as desired type.  
      }
  });

So that a client can call it with a callback like...

(response: IApigeeResponse) => {
    // Process response as an IApigeeResponse
}

Can you do greater than comparison on a date in a Rails 3 search?

If you hit problems where column names are ambiguous, you can do:

date_field = Note.arel_table[:date]
Note.where(user_id: current_user.id, notetype: p[:note_type]).
     where(date_field.gt(p[:date])).
     order(date_field.asc(), Note.arel_table[:created_at].asc())

Calling one Activity from another in Android

First question:

Use the Intent to call another Activity. In the Manifest, you should add

<activity android:name="ListViewImage"></activity>
<activity android:name="com.company.listview.ListViewImage">
</activity>

And in your current activity,

btListe = (ImageButton)findViewById(R.id.Button_Liste);
    btListe.setOnClickListener(new OnClickListener()
    {    public void onClick(View v)
        {
            intent = new Intent(main.this, ListViewImage.class);
            startActivity(intent);
            finish();
        }
    });

Second question:

sendButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            String valueString = editValue.getText().toString();
            long value;
            if (valueString != null) {
                value = Long.parseLong(valueString);
            }
            else {
                value = 0;
            }

            Bundle sendBundle = new Bundle();
            sendBundle.putLong("value", value);

            Intent i = new Intent(Activity1.this, Activity2.class);
            i.putExtras(sendBundle);
            startActivity(i);

            finish();
        }
    });

and in Activity2:

 Bundle receiveBundle = this.getIntent().getExtras();
    final long receiveValue = receiveBundle.getLong("value");
    receiveValueEdit.setText(String.valueOf(receiveValue));
    callReceiverButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent(Activity2.this, Receiver.class);
            i.putExtra("new value", receiveValue - 10);
        }
    });

How can I escape a single quote?

Represent it as a text entity (ASCII 39):

<input type='text' id='abc' value='hel&#39;lo'>

What does <T> (angle brackets) mean in Java?

<T> is a generic and can usually be read as "of type T". It depends on the type to the left of the <> what it actually means.

I don't know what a Pool or PoolFactory is, but you also mention ArrayList<T>, which is a standard Java class, so I'll talk to that.

Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer> for example, that means "An ArrayList of Integers." Many classes use generics to constrain the type of the elements in a container, for example. Another example is HashMap<String, Integer>, which means "a map with String keys and Integer values."

Your Pool example is a bit different, because there you are defining a class. So in that case, you are creating a class that somebody else could instantiate with a particular type in place of T. For example, I could create an object of type Pool<String> using your class definition. That would mean two things:

  • My Pool<String> would have an interface PoolFactory<String> with a createObject method that returns Strings.
  • Internally, the Pool<String> would contain an ArrayList of Strings.

This is great news, because at another time, I could come along and create a Pool<Integer> which would use the same code, but have Integer wherever you see T in the source.

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

.success { background-color: #cffccc; overflow: scroll; min-width: 100%; }

You can try scroll or auto.

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

regex for zip-code

For the listed three conditions only, these expressions might work also:

^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$

Please see this demo for additional explanation.

If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:

123451234
12345 1234
12345  1234

this expression for instance would be a secondary option with less constraints:

^\d{5}([-]|\s*)?(\d{4})?$

Please see this demo for additional explanation.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Test

_x000D_
_x000D_
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345  1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
    // This is necessary to avoid infinite loops with zero-width matches_x000D_
    if (m.index === regex.lastIndex) {_x000D_
        regex.lastIndex++;_x000D_
    }_x000D_
    _x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

jQuery: checking if the value of a field is null (empty)

_helpers: {
        //Check is string null or empty
        isStringNullOrEmpty: function (val) {
            switch (val) {
                case "":
                case 0:
                case "0":
                case null:
                case false:
                case undefined:
                case typeof this === 'undefined':
                    return true;
                default: return false;
            }
        },

        //Check is string null or whitespace
        isStringNullOrWhiteSpace: function (val) {
            return this.isStringNullOrEmpty(val) || val.replace(/\s/g, "") === '';
        },

        //If string is null or empty then return Null or else original value
        nullIfStringNullOrEmpty: function (val) {
            if (this.isStringNullOrEmpty(val)) {
                return null;
            }
            return val;
        }
    },

Utilize this helpers to achieve that.

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

I have created a jQuery plugin to add css-pseudo rules like using .css() for specific elements.

  • plugin code and test case is here
  • use case as simple css image popup here

usage:

$('body')
  .css({
    backgroundColor: 'white'
  })
  .cssPseudo('after', {
    content: 'attr(title) ", you should try to hover the picture, then click it."',
    position: 'absolute',
    top: 20, left: 20  
  })
  .cssPseudo('hover:after', {
    content: '"Now hover the picture, then click it!"'
  });

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

Create a list with initial capacity in Python

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

Results. (evaluate each function 144 times and average the duration)

simple append 0.0102
pre-allocate  0.0098

Conclusion. It barely matters.

Premature optimization is the root of all evil.

How to avoid "RuntimeError: dictionary changed size during iteration" error?

You cannot iterate through a dictionary while its changing during for loop. Make a casting to list and iterate over that list, it works for me.

    for key in list(d):
        if not d[key]: 
            d.pop(key)

What is a "callback" in C and how are they implemented?

A simple call back program. Hope it answers your question.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"

typedef void (*call_back) (S32, S32);

void test_call_back(S32 a, S32 b)
{
    printf("In call back function, a:%d \t b:%d \n", a, b);
}

void call_callback_func(call_back back)
{
    S32 a = 5;
    S32 b = 7;

    back(a, b);
}

S32 main(S32 argc, S8 *argv[])
{
    S32 ret = SUCCESS;

    call_back back;

    back = test_call_back;

    call_callback_func(back);

    return ret;
}

How to convert a column of DataTable to a List

Here you go.

           DataTable defaultDataTable = defaultDataSet.Tables[0];
           var list = (from x in defaultDataTable.AsEnumerable()
                    where x.Field<string>("column1") == something
                    select x.Field<string>("column2")).ToList();

If you need the first column

           var list = (from x in defaultDataTable.AsEnumerable()
                    where x.Field<string>(1) == something
                    select x.Field<string>(1)).ToList();

How to convert DateTime to a number with a precision greater than days in T-SQL?

Well, I would do it like this:

select datediff(minute,'1990-1-1',datetime)

where '1990-1-1' is an arbitrary base datetime.

Making a flex item float right

You don't need floats. In fact, they're useless because floats are ignored in flexbox.

You also don't need CSS positioning.

There are several flex methods available. auto margins have been mentioned in another answer.

Here are two other options:

  • Use justify-content: space-between and the order property.
  • Use justify-content: space-between and reverse the order of the divs.

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
    justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
    <div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
             divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div>another child </div>_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Split and join C# string

You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.

string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');

if (lnSpace > -1)
{
    string lcFirst = lcStart.Substring(0, lnSpace);
    string lcRest = lcStart.Substring(lnSpace + 1);
}

Gaussian fit for Python

Actually, you do not need to do a first guess. Simply doing

import matplotlib.pyplot as plt  
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y)
#popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

works fine. This is simpler because making a guess is not trivial. I had more complex data and did not manage to do a proper first guess, but simply removing the first guess worked fine :)

P.S.: use numpy.exp() better, says a warning of scipy

Get viewport/window height in ReactJS

Answers by @speckledcarp and @Jamesl are both brilliant. In my case, however, I needed a component whose height could extend the full window height, conditional at render time.... but calling a HOC within render() re-renders the entire subtree. BAAAD.

Plus, I wasn't interested in getting the values as props but simply wanted a parent div that would occupy the entire screen height (or width, or both).

So I wrote a Parent component providing a full height (and/or width) div. Boom.

A use case:

class MyPage extends React.Component {
  render() {
    const { data, ...rest } = this.props

    return data ? (
      // My app uses templates which misbehave badly if you manually mess around with the container height, so leave the height alone here.
      <div>Yay! render a page with some data. </div>
    ) : (
      <FullArea vertical>
        // You're now in a full height div, so containers will vertically justify properly
        <GridContainer justify="center" alignItems="center" style={{ height: "inherit" }}>
          <GridItem xs={12} sm={6}>
            Page loading!
          </GridItem>
        </GridContainer>
      </FullArea>
    )

Here's the component:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class FullArea extends Component {
  constructor(props) {
    super(props)
    this.state = {
      width: 0,
      height: 0,
    }
    this.getStyles = this.getStyles.bind(this)
    this.updateWindowDimensions = this.updateWindowDimensions.bind(this)
  }

  componentDidMount() {
    this.updateWindowDimensions()
    window.addEventListener('resize', this.updateWindowDimensions)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateWindowDimensions)
  }

  getStyles(vertical, horizontal) {
    const styles = {}
    if (vertical) {
      styles.height = `${this.state.height}px`
    }
    if (horizontal) {
      styles.width = `${this.state.width}px`
    }
    return styles
  }

  updateWindowDimensions() {
    this.setState({ width: window.innerWidth, height: window.innerHeight })
  }

  render() {
    const { vertical, horizontal } = this.props
    return (
      <div style={this.getStyles(vertical, horizontal)} >
        {this.props.children}
      </div>
    )
  }
}

FullArea.defaultProps = {
  horizontal: false,
  vertical: false,
}

FullArea.propTypes = {
  horizontal: PropTypes.bool,
  vertical: PropTypes.bool,
}

export default FullArea

Check if process returns 0 with batch file

The project I'm working on, we do something like this. We use the errorlevel keyword so it kind of looks like:

call myExe.exe
if errorlevel 1 (
  goto build_fail
)

That seems to work for us. Note that you can put in multiple commands in the parens like an echo or whatever. Also note that build_fail is defined as:

:build_fail
echo ********** BUILD FAILURE **********
exit /b 1

Node.js spawn child process and get terminal output live

Here is the cleanest approach I've found:

require("child_process").spawn('bash', ['./script.sh'], {
  cwd: process.cwd(),
  detached: true,
  stdio: "inherit"
});

Random strings in Python

Generating strings from (for example) lowercase characters:

import random, string

def randomword(length):
   letters = string.ascii_lowercase
   return ''.join(random.choice(letters) for i in range(length))

Results:

>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'

How to get only the last part of a path in Python?

With python 3 you can use the pathlib module (pathlib.PurePath for example):

>>> import pathlib

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/')
>>> path.name
'folderD'

If you want the last folder name where a file is located:

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/file.py')
>>> path.parent.name
'folderD'

How to check whether an array is empty using PHP?

$status = "";

$new_array = array();

if(!empty($new_array)){
  $status = "1";   // not a blank array
}
else{
  $status = "0";   // blank array
}

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

TCPDF ERROR: Some data has already been output, can't send PDF file

This problem is when apache/php show errors.

This data(html) destroy pdf output.

You must off display errors in php.ini.

How to read data from excel file using c#

Save the Excel file to CSV, and read the resulting file with C# using a CSV reader library like FileHelpers.

How do I make the scrollbar on a div only visible when necessary?

I found that there is height of div still showing, when it have text or not. So you can use this for best results.

<div style=" overflow:auto;max-height:300px; max-width:300px;"></div>

Cocoa: What's the difference between the frame and the bounds?

Frame its relative to its SuperView whereas Bounds relative to its NSView.

Example:X=40,Y=60.Also contains 3 Views.This Diagram shows you clear idea.

FRAME

BOUNDS

Regular Expression to select everything before and up to a particular text

This matches everything up to ".txt" (without including it):

^.*(?=(\.txt))

How to make a WPF window be on top of all other windows of my app (not system wide)?

Just learning C# and ran across similar situation. but found a solution that I think may help. You may have figured this a long time ago. this will be from starting a new project but you can use it in any.

1) Start new project.

2) go to Project, then New Windows form, then select Windows Form and name Splash.

3) set size, background, text, etc as desired.

4) Under Properties of the Splash.cs form set Start Position: CenterScreen and TopMost: true

5) form1 add "using System.Threading;"

6) form1 under class add "Splash splashscreen = new Splash();"

7) form1 add "splashscreen.Show();" and "Application.DoEvents();"

8) form1 Under Events>>Focus>>Activated add "Thread.Sleep(4000); splashscreen.Close();"

9) Splash.cs add under "Public Splash" add "this.BackColor = Color.Aqua;" /can use any color

10) This is the code for Form1.cs

public partial class Form1 : Form
{
    Splash splashscreen = new Splash();
    public Form1()
    {
        InitializeComponent();
        splashscreen.Show();
        Application.DoEvents();

    }

    private void Form1_Activated(object sender, EventArgs e)
    {
        Thread.Sleep(4000);
        splashscreen.Close();
    }
}

11) this is the code on Splash.cs

public partial class Splash : Form
{
    public Splash()
    {
        InitializeComponent();
        this.BackColor = Color.Aqua;
    }
}

12) I found that if you do NOT do something in the splash then the screen will not stay on the top for the time the first form needs to activate. The Thread count will disappear the splash after x seconds, so your program is normal.

Fastest method to replace all instances of a character in a string

var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");

newString now is 'Thas as a strang'

How to negate specific word in regex?

I had a list of file names, and I wanted to exclude certain ones, with this sort of behavior (Ruby):

files = [
  'mydir/states.rb',      # don't match these
  'countries.rb',
  'mydir/states_bkp.rb',  # match these
  'mydir/city_states.rb' 
]
excluded = ['states', 'countries']

# set my_rgx here

result = WankyAPI.filter(files, my_rgx)  # I didn't write WankyAPI...
assert result == ['mydir/city_states.rb', 'mydir/states_bkp.rb']

Here's my solution:

excluded_rgx = excluded.map{|e| e+'\.'}.join('|')
my_rgx = /(^|\/)((?!#{excluded_rgx})[^\.\/]*)\.rb$/

My assumptions for this application:

  • The string to be excluded is at the beginning of the input, or immediately following a slash.
  • The permitted strings end with .rb.
  • Permitted filenames don't have a . character before the .rb.

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

How to get selected value of a html select with asp.net

You need to add a name to your <select> element:

<select id="testSelect" name="testSelect">

It will be posted to the server, and you can see it using:

Request.Form["testSelect"]

SQL Greater than, Equal to AND Less Than

declare @starttime datetime = '2012-03-07 22:58:00'

SELECT BookingId, StartTime
FROM Booking
WHERE ABS( DATEDIFF( minute, StartTime, @starttime ) ) <= 60

UICollectionView - Horizontal scroll, horizontal layout?

We can do same Springboard behavior using UICollectionView and for that we need to write code for custom layout.

I have achieved it with my custom layout class implementation with "SMCollectionViewFillLayout"

Code repository:

https://github.com/smindia1988/SMCollectionViewFillLayout

Output as below:

1.png

First.png

2_Code_H-Scroll_V-Fill.png

enter image description here

3_Output_H-Scroll_V-Fill.png enter image description here

4_Code_H-Scroll_H-Fill.png enter image description here

5_Output_H-Scroll_H-Fill.png enter image description here

Missing artifact com.sun:tools:jar

None of the other answers did it for me. What did it was to check for "Dependency hierarchy" of the pom.xml in eclipse, where giving a filter 'tools' revealed that I had a real dependency to tools.jar:

Eclipse View

So the culprit for me was this:

<dependency>
    <groupId>com.github.markusbernhardt</groupId>
    <artifactId>robotframework-selenium2library-java</artifactId>
    <version>1.4.0.7</version>
    <scope>test</scope>
</dependency>

Adding an exclusion fixed it:

<dependency>
    <groupId>com.github.markusbernhardt</groupId>
    <artifactId>robotframework-selenium2library-java</artifactId>
    <version>1.4.0.7</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <artifactId>tools</artifactId>
            <groupId>com.sun</groupId>
        </exclusion>
    </exclusions>  
</dependency>

The exclusion doesn't seem to have any downsides to it.

jQuery Event : Detect changes to the html/text of a div

If you don't want use timer and check innerHTML you can try this event

$('mydiv').bind('DOMSubtreeModified', function(){
  console.log('changed');
});

More details and browser support datas are Here.

Attention: in newer jQuery versions bind() is deprecated, so you should use on() instead:

$('body').on('DOMSubtreeModified', 'mydiv', function(){
  console.log('changed');
});

How to define a circle shape in an Android XML drawable file?

Code for Simple circle

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
        <solid android:color="#9F2200"/>
        <stroke android:width="2dp" android:color="#fff" />
        <size android:width="80dp" android:height="80dp"/>
</shape>

Jupyter notebook not running code. Stuck on In [*]

I had the same issue now:

Solved it by:

Just reloading the local weblink in which the Python is running

http://localhost:8888/notebooks/sec%201/Untitled.ipynb

Setting default permissions for newly created files and sub-directories under a directory in Linux?

in your shell script (or .bashrc) you may use somthing like:

umask 022

umask is a command that determines the settings of a mask that controls how file permissions are set for newly created files.

Transaction marked as rollback only: How do I find the cause

disable the transactionmanager in your Bean.xml

<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager"/>
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

comment out these lines, and you'll see the exception causing the rollback ;)

Java error: Implicit super constructor is undefined for default constructor

It is possible but not the way you have it.

You have to add a no-args constructor to the base class and that's it!

public abstract class A {
    private String name;
    public A(){
        this.name = getName();
    }
    public abstract String getName();


    public String toString(){
        return "simple class name: " + this.getClass().getSimpleName() + " name:\"" + this.name + "\"";
    }
}
class B extends A {
    public String getName(){
        return "my name is B";
    }
    public static void main( String [] args ) {
        System.out.println( new C() );
    }
}
class C extends A {
    public String getName() {
        return "Zee";
    }
}

When you don't add a constructor ( any ) to a class the compiler add the default no arg contructor for you.

When the defualt no arg calls to super(); and since you don't have it in the super class you get that error message.

That's about the question it self.

Now, expanding the answer:

Are you aware that creating a subclass ( behavior ) to specify different a different value ( data ) makes no sense??!!! I hope you do.

If the only thing that is changes is the "name" then a single class parametrized is enough!

So you don't need this:

MyClass a = new A("A");
MyClass b = new B("B");
MyClass c = new C("C");
MyClass d = new D("D");

or

MyClass a = new A(); // internally setting "A" "B", "C" etc.
MyClass b = new B();
MyClass c = new C();
MyClass d = new D();

When you can write this:

MyClass a = new MyClass("A");
MyClass b = new MyClass("B");
MyClass c = new MyClass("C");
MyClass d = new MyClass("D");

If I were to change the method signature of the BaseClass constructor, I would have to change all the subclasses.

Well that's why inheritance is the artifact that creates HIGH coupling, which is undesirable in OO systems. It should be avoided and perhaps replaced with composition.

Think if you really really need them as subclass. That's why you see very often interfaces used insted:

 public interface NameAware {
     public String getName();
 }



 class A implements NameAware ...
 class B implements NameAware ...
 class C ... etc. 

Here B and C could have inherited from A which would have created a very HIGH coupling among them, by using interfaces the coupling is reduced, if A decides it will no longer be "NameAware" the other classes won't broke.

Of course, if you want to reuse behavior this won't work.

How to get Node.JS Express to listen only on localhost?

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.

How to reload apache configuration for a site without restarting apache?

Late answer here, but if you search /etc/init.d/apache2 for 'reload', you'll find something like this:

do_reload() {
        if apache_conftest; then
                if ! pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
                        APACHE2_INIT_MESSAGE="Apache2 is not running"
                        return 2
                fi
                $APACHE2CTL graceful > /dev/null 2>&1
                return $?
        else
                APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest failed. Not doing anything."
                return 2
        fi
}

Basically, what the answers that suggest using init.d, systemctl, etc are invoking is a thin wrapper that says:

  • check the apache config
  • if it's good, run apachectl graceful (swallowing the output, and forwarding the exit code)

This suggests that @Aruman's answer is also correct, provided you are confident there are no errors in your configuration or have already run apachctl configtest manually.

The apache documentation also supplies the same command for a graceful restart (apachectl -k graceful), and some more color on the behavior thereof.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

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

not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

The native lib is expected in one of the following locations

/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib

and not in

tomcat/lib

The files in tomcat/lib are all jar file and are added by tomcat to the classpath so that they are available to your application.

The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar, for linux it could be a .so file, for windows it could be a .dll file.

Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.

Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.

org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms

EDIT

The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.

If you are troubling with running your servlet then after the run on sever command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.

It should be something like that

http://localhost:8080/<your-context-name>/<your-servlet-name>

EDIT 2

Try to call your servlet using the following url

http://localhost:8080/com.filecounter/FileCounter

Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF.

It is better to configure your servlets there using servlet-name servlet-class and url-mapping. It could look like that:

  <servlet>
    <description></description>
    <display-name>File counter - My first servlet</display-name>
    <servlet-name>file_counter</servlet-name>
    <servlet-class>com.filecounter.FileCounter</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>file_counter</servlet-name>
    <url-pattern>/FileFounter</url-pattern>
  </servlet-mapping>

In eclipse dynamic web project the default context name is the same as your project name.

http://localhost:8080/<your-context-name>/FileCounter

will work too.

Code snippet or shortcut to create a constructor in Visual Studio

If you use ReSharper, you can quickly generate constructors by typing:

  • 'ctor' + Tab + Tab (without parameters),
  • 'ctorf' + Tab + Tab (with parameters that initialize all fields) or
  • 'ctorp' + Tab + Tab (with parameters that initialize all properties).

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

How can I load storyboard programmatically from class?

In attribute inspector give the identifier for that view controller and the below code works for me

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailViewController *detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
[self.navigationController pushViewController:detailViewController animated:YES];

How to add image in a TextView text?

This might Help You

  SpannableStringBuilder ssBuilder;

        ssBuilder = new SpannableStringBuilder(" ");
        // working code ImageSpan image = new ImageSpan(textView.getContext(), R.drawable.image);
        Drawable image = ContextCompat.getDrawable(textView.getContext(), R.drawable.image);
        float scale = textView.getContext().getResources().getDisplayMetrics().density;
        int width = (int) (12 * scale + 0.5f);
        int height = (int) (18 * scale + 0.5f);
        image.setBounds(0, 0, width, height);
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BASELINE);
        ssBuilder.setSpan(
                imageSpan, // Span to add
                0, // Start of the span (inclusive)
                1, // End of the span (exclusive)
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);// Do not extend the span when text add later

        ssBuilder.append(" " + text);
        ssBuilder = new SpannableStringBuilder(text);
        textView.setText(ssBuilder);

An array of List in c#

use

List<int>[] a = new List<int>[100];

node.js + mysql connection pooling

I am using this base class connection with mysql:

"base.js"

var mysql   = require("mysql");

var pool = mysql.createPool({
    connectionLimit : 10,
    host: Config.appSettings().database.host,
    user: Config.appSettings().database.username,
    password: Config.appSettings().database.password,
    database: Config.appSettings().database.database
});


var DB = (function () {

    function _query(query, params, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                connection.release();
                callback(null, err);
                throw err;
            }

            connection.query(query, params, function (err, rows) {
                connection.release();
                if (!err) {
                    callback(rows);
                }
                else {
                    callback(null, err);
                }

            });

            connection.on('error', function (err) {
                connection.release();
                callback(null, err);
                throw err;
            });
        });
    };

    return {
        query: _query
    };
})();

module.exports = DB;

Just use it like that:

var DB = require('../dal/base.js');

DB.query("select * from tasks", null, function (data, error) {
   callback(data, error);
});

How to tell if a string contains a certain character in JavaScript?

To find "hello" in your_string

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}

For the alpha numeric you can use a regular expression:

http://www.regular-expressions.info/javascript.html

Alpha Numeric Regular Expression

Execute multiple command lines with the same process using .NET

I prefer to do it by using a BAT file.

With BAT file you have more control and can do whatever you want.

string batFileName = path + @"\" + Guid.NewGuid() + ".bat";

using (StreamWriter batFile = new StreamWriter(batFileName))
{
    batFile.WriteLine($"YOUR COMMAND");
    batFile.WriteLine($"YOUR COMMAND");
    batFile.WriteLine($"YOUR COMMAND");
}

ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c " + batFileName);
processStartInfo.UseShellExecute = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Normal;

Process p = new Process();
p.StartInfo = processStartInfo;
p.Start();
p.WaitForExit();

File.Delete(batFileName);

get dataframe row count based on conditions

You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking

In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))

In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]: 
           A         B         C         D
12  0.491683  0.137766  0.859753 -1.041487
13  0.376200  0.575667  1.534179  1.247358
14  0.428739  1.539973  1.057848 -1.254489

In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]: 
A    3
B    3
C    3
D    3
dtype: int64

In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3

Read a text file in R line by line

Here is the solution with a for loop. Importantly, it takes the one call to readLines out of the for loop so that it is not improperly called again and again. Here it is:

fileName <- "up_down.txt"
conn <- file(fileName,open="r")
linn <-readLines(conn)
for (i in 1:length(linn)){
   print(linn[i])
}
close(conn)

jQuery datepicker set selected date, on the fly

or you can simply have

$('.date-pick').datePicker().val(new Date()).trigger('change')

Docker Error bind: address already in use

Changing network_mode: "bridge" to "host" did it for me.

This with

version: '2.2'
services:
  bind:
    image: sameersbn/bind:latest
    dns: 127.0.0.1
    ports:
      - 172.17.42.1:53:53/udp
      - 172.17.42.1:10000:10000
    volumes:
        - "/srv/docker/bind:/data"
    environment:
      - 'ROOT_PASSWORD=secret'
    network_mode: "host"

Selenium WebDriver: Wait for complex page with JavaScript to load

If anyone actually knew a general and always-applicable answer, it would have been implemented everywhere ages ago and would make our lives SO much easier.

There are many things you can do, but every single one of them has a problem:

  1. As Ashwin Prabhu said, if you know the script well, you can observe its behaviour and track some of its variables on window or document etc. This solution, however, is not for everyone and can be used only by you and only on a limited set of pages.

  2. Your solution by observing the HTML code and whether it has or hasn't been changed for some time is not bad (also, there is a method to get the original and not-edited HTML directly by WebDriver), but:

    • It takes a long time to actually assert a page and could prolong the test significantly.
    • You never know what the right interval is. The script might be downloading something big that takes more than 500 ms. There are several scripts on our company's internal page that take several seconds in IE. Your computer may be temporarily short on resources - say that an antivirus will make your CPU work fully, then 500 ms may be too short even for a noncomplex scripts.
    • Some scripts are never done. They call themselves with some delay (setTimeout()) and work again and again and could possibly change the HTML every time they run. Seriously, every "Web 2.0" page does it. Even Stack Overflow. You could overwrite the most common methods used and consider the scripts that use them as completed, but ... you can't be sure.
    • What if the script does something other than changing the HTML? It could do thousands of things, not just some innerHTML fun.
  3. There are tools to help you on this. Namely Progress Listeners together with nsIWebProgressListener and some others. The browser support for this, however, is horrible. Firefox began to try to support it from FF4 onwards (still evolving), IE has basic support in IE9.

And I guess I could come up with another flawed solution soon. The fact is - there's no definite answer on when to say "now the page is complete" because of the everlasting scripts doing their work. Pick the one that serves you best, but beware of its shortcomings.

How to merge a specific commit in Git

I used to cherry pick, but found I had some mysterious issues from time to time. I came across a blog by Raymond Chen, a 25 year veteran at Microsoft, that describes some scenarios where cherry picking can cause issues in certain cases.

One of the rules of thumb is, if you cherry pick from one branch into another, then later merge between those branches, you're likely sooner or later going to experience issues.

Here's a reference to Raymond Chen's blogs on this topic: https://devblogs.microsoft.com/oldnewthing/20180312-00/?p=98215

The only issue I had with Raymond's blog is he did not provide a full working example. So I will attempt to provide one here.

The question above asks how to merge only the commit pointed to by the HEAD in the a-good-feature branch over to master.

Here is how that would be done:

  1. Find the common ancestor between the master and a-good-feature branches.
  2. Create a new branch from that ancestor, we'll call this new branch patch.
  3. Cherry pick one or more commits into this new patch branch.
  4. Merge the patch branch into both the master and a-good-feature branches.
  5. The master branch will now contain the commits, and both master and a-good-feature branches will also have a new common ancestor, which will resolve any future issues if further merging is performed later on.

Here is an example of those commands:

git checkout master...a-good-feature  [checkout the common ancestor]
git checkout -b patch
git cherry-pick a-good-feature  [this is not only the branch name, but also the commit we want]
git checkout master
git merge patch
git checkout a-good-feature
git merge -s ours patch

It might be worth noting that the last line that merged into the a-good-feature branch used the "-s ours" merge strategy. The reason for this is because we simply need to create a commit in the a-good-feature branch that points to a new common ancestor, and since the code is already in that branch, we want to make sure there isn't any chance of a merge conflict. This becomes more important if the commit(s) you are merging are not the most recent.

The scenarios and details surrounding partial merges can get pretty deep, so I recommend reading through all 10 parts of Raymond Chen's blog to gain a full understanding of what can go wrong, how to avoid it, and why this works.

Copy files without overwrite

You can try this:

echo n | copy /-y <SOURCE> <DESTINATION>

-y simply prompts before overwriting and we can pipe n to all those questions. So this would in essence just copy non-existing files. :)

jquery get height of iframe content when loaded

simple one-liner starts with a default min-height and increases to contents size.

_x000D_
_x000D_
<iframe src="http://url.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
_x000D_
_x000D_
_x000D_

How to call webmethod in Asp.net C#

There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.

Script example:

$.ajax({
    type: "POST",
    url: '/Default.aspx/TestMethod',
    data: '{message: "HAI" }',
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        console.log(data);
    },
    failure: function (response) {
        alert(response.d);
    }
});

WebMethod example:

[WebMethod]
public static string TestMethod(string message)
{
     return "The message" + message;
}

Display more Text in fullcalendar

Well i found a simpler solution for me:

I changed fullcalendar.css

and added the following:

float: left;
clear: none;
margin-right: 10px;

Resulting in:

.fc-event-time,
.fc-event-title {
    padding: 0 1px;
    float: left;
    clear: none;
    margin-right: 10px;
}

now it only wraps when it needs to.

Single quotes vs. double quotes in C or C++

Double quotes are for string literals, e.g.:

char str[] = "Hello world";

Single quotes are for single character literals, e.g.:

char c = 'x';

EDIT As David stated in another answer, the type of a character literal is int.

How to gracefully handle the SIGKILL signal in Java

You can use Runtime.getRuntime().addShutdownHook(...), but you cannot be guaranteed that it will be called in any case.

Jackson how to transform JsonNode to ArrayNode without casting?

Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?

It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException.

But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException, the old version will throw JSONException. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)

ERROR Android emulator gets killed

Please check your free space on your disk also. I had a same problem and finally I got I need to free up space to fix this.

How can I get the behavior of GNU's readlink -f on a Mac?

MacPorts and Homebrew provide a coreutils package containing greadlink (GNU readlink). Credit to Michael Kallweitt post in mackb.com.

brew install coreutils

greadlink -f file.txt

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

Library functions like "pow" are usually carefully crafted to yield the minimum possible error (in generic case). This is usually achieved approximating functions with splines (according to Pascal's comment the most common implementation seems to be using Remez algorithm)

fundamentally the following operation:

pow(x,y);

has a inherent error of approximately the same magnitude as the error in any single multiplication or division.

While the following operation:

float a=someValue;
float b=a*a*a*a*a*a;

has a inherent error that is greater more than 5 times the error of a single multiplication or division (because you are combining 5 multiplications).

The compiler should be really carefull to the kind of optimization it is doing:

  1. if optimizing pow(a,6) to a*a*a*a*a*a it may improve performance, but drastically reduce the accuracy for floating point numbers.
  2. if optimizing a*a*a*a*a*a to pow(a,6) it may actually reduce the accuracy because "a" was some special value that allows multiplication without error (a power of 2 or some small integer number)
  3. if optimizing pow(a,6) to (a*a*a)*(a*a*a) or (a*a)*(a*a)*(a*a) there still can be a loss of accuracy compared to pow function.

In general you know that for arbitrary floating point values "pow" has better accuracy than any function you could eventually write, but in some special cases multiple multiplications may have better accuracy and performance, it is up to the developer choosing what is more appropriate, eventually commenting the code so that noone else would "optimize" that code.

The only thing that make sense (personal opinion, and apparently a choice in GCC wichout any particular optimization or compiler flag) to optimize should be replacing "pow(a,2)" with "a*a". That would be the only sane thing a compiler vendor should do.

$(document).on("click"... not working?

This works:

<div id="start-element">Click Me</div>

$(document).on("click","#test-element",function() {
    alert("click");
});

$(document).on("click","#start-element",function() {
    $(this).attr("id", "test-element");
});

Here is the Fiddle

Daylight saving time and time zone best practices

Actually, kernel32.dll does not export SystemTimeToTzSpecificLocation. It does however export the following two: SystemTimeToTzSpecificLocalTime and TzSpecificLocalTimeToSystemTime...

Pass multiple values with onClick in HTML link

Please try this

for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

Per http://msdn.microsoft.com/en-us/library/aa302291.aspx

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

C# using streams

To expand a little on other answers here, and help explain a lot of the example code you'll see dotted about, most of the time you don't read and write to a stream directly. Streams are a low-level means to transfer data.

You'll notice that the functions for reading and writing are all byte orientated, e.g. WriteByte(). There are no functions for dealing with integers, strings etc. This makes the stream very general-purpose, but less simple to work with if, say, you just want to transfer text.

However, .NET provides classes that convert between native types and the low-level stream interface, and transfers the data to or from the stream for you. Some notable such classes are:

StreamWriter // Badly named. Should be TextWriter.
StreamReader // Badly named. Should be TextReader.
BinaryWriter
BinaryReader

To use these, first you acquire your stream, then you create one of the above classes and associate it with the stream. E.g.

MemoryStream memoryStream = new MemoryStream();
StreamWriter myStreamWriter = new StreamWriter(memoryStream);

StreamReader and StreamWriter convert between native types and their string representations then transfer the strings to and from the stream as bytes. So

myStreamWriter.Write(123);

will write "123" (three characters '1', '2' then '3') to the stream. If you're dealing with text files (e.g. html), StreamReader and StreamWriter are the classes you would use.

Whereas

myBinaryWriter.Write(123);

will write four bytes representing the 32-bit integer value 123 (0x7B, 0x00, 0x00, 0x00). If you're dealing with binary files or network protocols BinaryReader and BinaryWriter are what you might use. (If you're exchanging data with networks or other systems, you need to be mindful of endianness, but that's another post.)

How do you make websites with Java?

Read the tutorial on Java Web applications.

Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.

All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).

Here is a Tomcat tutorial.

How to check if another instance of my shell script is running

Here's one trick you'll see in various places:

status=`ps -efww | grep -w "[a]bc.sh" | awk -vpid=$$ '$2 != pid { print $2 }'`
if [ ! -z "$status" ]; then
    echo "[`date`] : abc.sh : Process is already running"
    exit 1;
fi

The brackets around the [a] (or pick a different letter) prevent grep from finding itself. This makes the grep -v grep bit unnecessary. I also removed the grep -v $$ and fixed the awk part to accomplish the same thing.

Is there a printf converter to print in binary format?

Here's how I did it for an unsigned int

void printb(unsigned int v) {
    unsigned int i, s = 1<<((sizeof(v)<<3)-1); // s = only most significant bit at 1
    for (i = s; i; i>>=1) printf("%d", v & i || 0 );
}

Setting equal heights for div's with jQuery

You need imagesLoaded if the container have images inside. This works for responsive too.

$(document).ready(function () { 
     equalHeight('.column');
});
$(window).resize(function(){equalHeight('.column');});

function equalHeight(columnClass){
    $('.eq-height-wrap').imagesLoaded(function(){
        $('.eq-height-wrap').each(function(){  

            var maxHeight = Math.max.apply(null, $(this).find(columnClass).map(function ()
            {
                return $(this).innerHeight();
            }).get());

            $(columnClass,this).height(maxHeight);
        });
    });
}

How to check if smtp is working from commandline (Linux)

Syntax for establishing a raw network connection using telnet is this:

telnet {domain_name} {port_number}

So telnet to your smtp server like

telnet smtp.mydomain.com 25

And copy and paste the below

helo client.mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
From: [email protected]
Subject: test mail from command line

this is test number 1
sent from linux box
.
quit

Note : Do not forgot the "." at the end which represents the end of the message. The "quit" line exits ends the session.

How to make ng-repeat filter out duplicate results

I decided to extend @thethakuri's answer to allow any depth for the unique member. Here's the code. This is for those who don't want to include the entire AngularUI module just for this functionality. If you're already using AngularUI, ignore this answer:

app.filter('unique', function() {
    return function(collection, primaryKey) { //no need for secondary key
      var output = [], 
          keys = [];
          var splitKeys = primaryKey.split('.'); //split by period


      angular.forEach(collection, function(item) {
            var key = {};
            angular.copy(item, key);
            for(var i=0; i<splitKeys.length; i++){
                key = key[splitKeys[i]];    //the beauty of loosely typed js :)
            }

            if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
            }
      });

      return output;
    };
});

Example

<div ng-repeat="item in items | unique : 'subitem.subitem.subitem.value'"></div>

How can I view the allocation unit size of a NTFS partition in Vista?

I know this is an old thread, but there's a newer way then having to use fsutil or diskpart.

Run this powershell command.

Get-Volume | Format-List AllocationUnitSize, FileSystemLabel

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

Difference between e.target and e.currentTarget

e.currentTarget would always return the component onto which the event listener is added.

On the other hand, e.target can be the component itself or any direct child or grand child or grand-grand-child and so on who received the event. In other words, e.target returns the component which is on top in the Display List hierarchy and must be in the child hierarchy or the component itself.

One use can be when you have several Image in Canvas and you want to drag Images inside the component but Canvas. You can add a listener on Canvas and in that listener you can write the following code to make sure that Canvas wouldn't get dragged.

function dragImageOnly(e:MouseEvent):void
{
    if(e.target==e.currentTarget)
    {
        return;
     }
     else
     {
        Image(e.target).startDrag();
     }
}

SQL grammar for SELECT MIN(DATE)

To get the titles for dates greater than a week ago today, use this:

SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7

Convert pyQt UI to python

Quickest way to convert .ui to .py is from terminal:

pyuic4 -x input.ui -o output.py

Make sure you have pyqt4-dev-tools installed.

jQuery set radio button

I found the answer here:
https://web.archive.org/web/20160421163524/http://vijayt.com/Post/Set-RadioButton-value-using-jQuery

Basically, if you want to check one radio button, you MUST pass the value as an array:

$('input:radio[name=cols]').val(['Site']);
$('input:radio[name=rows]').val(['Site']);

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

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

So this should work:

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

MySQL foreach alternative for procedure

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: mysql-storedprocedures.pdf

SQL: How to properly check if a record exists

I'm using this way:

IIF(EXISTS (SELECT TOP 1 1 
                FROM Users 
                WHERE FirstName = 'John'), 1, 0) AS DoesJohnExist

Making LaTeX tables smaller?

if it's too long for one page, use the longtable package. and if it's too wide for the page, use p{width} in place of l,r, or c for the column specifier. you can also go smaller than \small, i.e. \footnotesize and \tiny. I would consult the setspace package for options on how to remove the double space, though it's probably \singlespace or something like that.

DateTime2 vs DateTime in SQL Server

datetime2 wins in most aspects except (old apps Compatibility)

  1. larger range of values
  2. better Accuracy
  3. smaller storage space (if optional user-specified precision is specified)

SQL Date and time data types compare - datetime,datetime2,date,TIME

please note the following points

  • Syntax
    • datetime2[(fractional seconds precision=> Look Below Storage Size)]
  • Precision, scale
    • 0 to 7 digits, with an accuracy of 100ns.
    • The default precision is 7 digits.
  • Storage Size
    • 6 bytes for precision less than 3;
    • 7 bytes for precision 3 and 4.
    • All other precision require 8 bytes.
  • DateTime2(3) have the same number of digits as DateTime but uses 7 bytes of storage instead of 8 byte (SQLHINTS- DateTime Vs DateTime2)
  • Find more on datetime2(Transact-SQL MSDN article)

image source : MCTS Self-Paced Training Kit (Exam 70-432): Microsoft® SQL Server® 2008 - Implementation and Maintenance Chapter 3:Tables -> Lesson 1: Creating Tables -> page 66

Creating a blocking Queue<T> in .NET?

Use .net 4 BlockingCollection, to enqueue use Add(), to dequeue use Take(). It internally uses non-blocking ConcurrentQueue. More info here Fast and Best Producer/consumer queue technique BlockingCollection vs concurrent Queue

How to set text size in a button in html

Without using inline CSS you could set the text size of all your buttons using:

input[type="submit"], input[type="button"] {
  font-size: 14px;
}

Which browser has the best support for HTML 5 currently?

http://wiki.whatwg.org/wiki/Implementations_in_Web_browsers has information maintained by the WHATWG community (and everyone who drops by and edits it).

Disclaimer: I'm a member of that community.

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

Here is the content of the file MessageBoxManager.cs

#pragma warning disable 0618

using System;

using System.Text;

using System.Runtime.InteropServices;

using System.Security.Permissions;

[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]

namespace System.Windows.Forms

{

    public class MessageBoxManager
    {
        private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
        private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);

        private const int WH_CALLWNDPROCRET = 12;
        private const int WM_DESTROY = 0x0002;
        private const int WM_INITDIALOG = 0x0110;
        private const int WM_TIMER = 0x0113;
        private const int WM_USER = 0x400;
        private const int DM_GETDEFID = WM_USER + 0;

        private const int MBOK = 1;
        private const int MBCancel = 2;
        private const int MBAbort = 3;
        private const int MBRetry = 4;
        private const int MBIgnore = 5;
        private const int MBYes = 6;
        private const int MBNo = 7;


        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

        [DllImport("user32.dll")]
        private static extern int UnhookWindowsHookEx(IntPtr idHook);

        [DllImport("user32.dll")]
        private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", CharSet = CharSet.Unicode)]
        private static extern int GetWindowTextLength(IntPtr hWnd);

        [DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

        [DllImport("user32.dll")]
        private static extern int EndDialog(IntPtr hDlg, IntPtr nResult);

        [DllImport("user32.dll")]
        private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
        private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll")]
        private static extern int GetDlgCtrlID(IntPtr hwndCtl);

        [DllImport("user32.dll")]
        private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);

        [DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)]
        private static extern bool SetWindowText(IntPtr hWnd, string lpString);


        [StructLayout(LayoutKind.Sequential)]
        public struct CWPRETSTRUCT
        {
            public IntPtr lResult;
            public IntPtr lParam;
            public IntPtr wParam;
            public uint   message;
            public IntPtr hwnd;
        };

        private static HookProc hookProc;
        private static EnumChildProc enumProc;
        [ThreadStatic]
        private static IntPtr hHook;
        [ThreadStatic]
        private static int nButton;

        /// <summary>
        /// OK text
        /// </summary>
        public static string OK = "&OK";
        /// <summary>
        /// Cancel text
        /// </summary>
        public static string Cancel = "&Cancel";
        /// <summary>
        /// Abort text
        /// </summary>
        public static string Abort = "&Abort";
        /// <summary>
        /// Retry text
        /// </summary>
        public static string Retry = "&Retry";
        /// <summary>
        /// Ignore text
        /// </summary>
        public static string Ignore = "&Ignore";
        /// <summary>
        /// Yes text
        /// </summary>
        public static string Yes = "&Yes";
        /// <summary>
        /// No text
        /// </summary>
        public static string No = "&No";

        static MessageBoxManager()
        {
            hookProc = new HookProc(MessageBoxHookProc);
            enumProc = new EnumChildProc(MessageBoxEnumProc);
            hHook = IntPtr.Zero;
        }

        /// <summary>
        /// Enables MessageBoxManager functionality
        /// </summary>
        /// <remarks>
        /// MessageBoxManager functionality is enabled on current thread only.
        /// Each thread that needs MessageBoxManager functionality has to call this method.
        /// </remarks>
        public static void Register()
        {
            if (hHook != IntPtr.Zero)
                throw new NotSupportedException("One hook per thread allowed.");
            hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
        }

        /// <summary>
        /// Disables MessageBoxManager functionality
        /// </summary>
        /// <remarks>
        /// Disables MessageBoxManager functionality on current thread only.
        /// </remarks>
        public static void Unregister()
        {
            if (hHook != IntPtr.Zero)
            {
                UnhookWindowsHookEx(hHook);
                hHook = IntPtr.Zero;
            }
        }

        private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode < 0)
                return CallNextHookEx(hHook, nCode, wParam, lParam);

            CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
            IntPtr hook = hHook;

            if (msg.message == WM_INITDIALOG)
            {
                int nLength = GetWindowTextLength(msg.hwnd);
                StringBuilder className = new StringBuilder(10);
                GetClassName(msg.hwnd, className, className.Capacity);
                if (className.ToString() == "#32770")
                {
                    nButton = 0;
                    EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero);
                    if (nButton == 1)
                    {
                        IntPtr hButton = GetDlgItem(msg.hwnd, MBCancel);
                        if (hButton != IntPtr.Zero)
                            SetWindowText(hButton, OK);
                    }
                }
            }

            return CallNextHookEx(hook, nCode, wParam, lParam);
        }

        private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam)
        {
            StringBuilder className = new StringBuilder(10);
            GetClassName(hWnd, className, className.Capacity);
            if (className.ToString() == "Button")
            {
                int ctlId = GetDlgCtrlID(hWnd);
                switch (ctlId)
                {
                    case MBOK:
                        SetWindowText(hWnd, OK);
                        break;
                    case MBCancel:
                        SetWindowText(hWnd, Cancel);
                        break;
                    case MBAbort:
                        SetWindowText(hWnd, Abort);
                        break;
                    case MBRetry:
                        SetWindowText(hWnd, Retry);
                        break;
                    case MBIgnore:
                        SetWindowText(hWnd, Ignore);
                        break;
                    case MBYes:
                        SetWindowText(hWnd, Yes);
                        break;
                    case MBNo:
                        SetWindowText(hWnd, No);
                        break;

                }
                nButton++;
            }

            return true;
        }


    }
}

How to write to a file, using the logging Python module?

An example of using logging.basicConfig rather than logging.fileHandler()

logging.basicConfig(filename=logname,
                            filemode='a',
                            format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                            datefmt='%H:%M:%S',
                            level=logging.DEBUG)

logging.info("Running Urban Planning")

self.logger = logging.getLogger('urbanGUI')

In order, the five parts do the following:

  1. set the output file (filename=logname)
  2. set it to append rather than overwrite (filemode='a')
  3. determine the format of the output message (format=...)
  4. determine the format of the output time (datefmt='%H:%M:%S')
  5. and determine the minimum message level it will accept (level=logging.DEBUG).

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

nginx- duplicate default server error

You likely have other files (such as the default configuration) located in /etc/nginx/sites-enabled that needs to be removed.

This issue is caused by a repeat of the default_server parameter supplied to one or more listen directives in your files. You'll likely find this conflicting directive reads something similar to:

listen 80 default_server;

As the nginx core module documentation for listen states:

The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair.

This means that there must be another file or server block defined in your configuration with default_server set for port 80. nginx is encountering that first before your mysite.com file so try removing or adjusting that other configuration.

If you are struggling to find where these directives and parameters are set, try a search like so:

grep -R default_server /etc/nginx

'printf' vs. 'cout' in C++

And I quote:

In high level terms, the main differences are type safety (cstdio doesn't have it), performance (most iostreams implementations are slower than the cstdio ones) and extensibility (iostreams allows custom output targets and seamless output of user defined types).

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

CSS pseudo elements in React

Got a reply from @Vjeux over at the React team:

Normal HTML/CSS:

<div class="something"><span>Something</span></div>
<style>
    .something::after {
    content: '';
    position: absolute;
    -webkit-filter: blur(10px) saturate(2);
}
</style>

React with inline style:

render: function() {
    return (
        <div>
          <span>Something</span>
          <div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
        </div>
    );
},

The trick is that instead of using ::after in CSS in order to create a new element, you should instead create a new element via React. If you don't want to have to add this element everywhere, then make a component that does it for you.

For special attributes like -webkit-filter, the way to encode them is by removing dashes - and capitalizing the next letter. So it turns into WebkitFilter. Note that doing {'-webkit-filter': ...} should also work.

How to check if the request is an AJAX request with PHP

You could try using a $_SESSION variable to make sure that a request was made from a browser. Otherwise, you could have the request sent through a database or file [server-side].

Jquery-How to grey out the background while showing the loading icon over it

I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/

Step 1 :

I renamed your container div to overlay, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.

The resulting html is :

<div class="overlay">
    <div id="loading-img"></div>
</div>


<div class="content">
    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
    <button id="button">Submit</button>
</div>

The css of the overlay is the following

.overlay {
    background: #e9e9e9;  <- I left your 'gray' background
    display: none;        <- Not displayed by default
    position: absolute;   <- This and the following properties will
    top: 0;                  make the overlay, the element will expand
    right: 0;                so as to cover the whole body of the page
    bottom: 0;
    left: 0;
    opacity: 0.5;
}

Step 2 :

I added some dummy text so as to have something to overlay.

Step 3 :

Then, in the click handler we just need to show the overlay :

$("#button").click(function () {
    $(".overlay").show();
});

Getting "conflicting types for function" in C, why?

You are trying to call do_something before you declare it. You need to add a function prototype before your printf line:

char* do_something(char*, const char*);

Or you need to move the function definition above the printf line. You can't use a function before it is declared.

How do you use https / SSL on localhost?

This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:

install webpack-dev-server

npm i -g webpack-dev-server

start webpack-dev-server with https

webpack-dev-server --https

Using OR & AND in COUNTIFS

There is probably a more efficient solution to your question, but following formula should do the trick:

=SUM(COUNTIFS(J1:J196,"agree",A1:A196,"yes"),COUNTIFS(J1:J196,"agree",A1:A196,"no"))

java.net.BindException: Address already in use: JVM_Bind <null>:80

The error:

Tomcat: java.net.BindException: Address already in use: JVM_Bind :80

suggests that the port 80 is already in use.
You may either:

  • Try searching for that process and stop it OR
  • Make your tomcat to run on different (free) port

See also: Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Add and Remove Views in Android Dynamically?

Kotlin Extension Solution

Add removeSelf to directly call on a view. If attached to a parent, it will be removed. This makes your code more declarative, and thus readable.

myView.removeSelf()

fun View?.removeSelf() {
    this ?: return
    val parent = parent as? ViewGroup ?: return
    parent.removeView(this)
}

Here are 3 options for how to programmatically add a view to a ViewGroup.

// Built-in
myViewGroup.addView(myView)

// Reverse addition
myView.addTo(myViewGroup)

fun View?.addTo(parent: ViewGroup?) {
    this ?: return
    parent ?: return
    parent.addView(this)
}

// Null-safe extension
fun ViewGroup?.addView(view: View?) {
    this ?: return
    view ?: return
    addView(view)
}

Comparing two dataframes and getting the differences

Since pandas >= 1.1.0 we have DataFrame.compare and Series.compare.

Note: the method can only compare identically-labeled DataFrame objects, this means DataFrames with identical row and column labels.

df1 = pd.DataFrame({'A': [1, 2, 3],
                    'B': [4, 5, 6],
                    'C': [7, np.NaN, 9]})

df2 = pd.DataFrame({'A': [1, 99, 3],
                    'B': [4, 5, 81],
                    'C': [7, 8, 9]})

   A  B    C
0  1  4  7.0
1  2  5  NaN
2  3  6  9.0 

    A   B  C
0   1   4  7
1  99   5  8
2   3  81  9
df1.compare(df2)

     A          B          C      
  self other self other self other
1  2.0  99.0  NaN   NaN  NaN   8.0
2  NaN   NaN  6.0  81.0  NaN   NaN

https connection using CURL from command line

having dignosed the problem I was able to use the existing system default CA file, on debian6 this is:

/etc/ssl/certs/ca-certificates.crt

as root this can be done like:

echo curl.cainfo=/etc/ssl/certs/ca-certificates.crt >> /etc/php5/mods-available/curl.ini

then re-start the web-server.

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

Convert string to int array using LINQ

Here's code that filters out invalid fields:

    var ints = from field in s1.Split(';').Where((x) => { int dummy; return Int32.TryParse(x, out dummy); })
               select Int32.Parse(field);

How to use pip with Python 3.x alongside Python 2.x

First, install Python 3 pip using:

sudo apt-get install python3-pip

Then, to use Python 3 pip use:

pip3 install <module-name>

For Python 2 pip use:

pip install <module-name>

How to add new line in Markdown presentation?

MarkDown file in three way to Break a Line

<br /> Tag Using

paragraph First Line <br /> Second Line

\ Using

First Line sentence \
Second Line sentence 

space keypress two times Using

First Line sentence??
Second Line sentence

Paragraphs in use <br /> tag.

Multiple sentences in using \ or two times press space key then Enter and write a new sentence.

How to find my realm file?

The correct lldb command for Xcode 7, Swift 2.2+ is po Realm.Configuration.defaultConfiguration.path!

Jquery onclick on div

Nothing.

$('#content').click(function(e) {  
    alert(1);
});

Will bind to an existing HTML element with the ID set to content, and will show a message box on click.

  • Make sure that #content exists before using that code
  • That the ID is unique
  • Check your Javascript console for any errors or issues

How to push to History in React Router v4?

step one wrap your app in Router

import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));

Now my entire App will have access to BrowserRouter. Step two I import Route and then pass down those props. Probably in one of your main files.

import { Route } from "react-router-dom";

//lots of code here

//somewhere in my render function

    <Route
      exact
      path="/" //put what your file path is here
      render={props => (
      <div>
        <NameOfComponent
          {...props} //this will pass down your match, history, location objects
        />
      </div>
      )}
    />

Now if I run console.log(this.props) in my component js file that I should get something that looks like this

{match: {…}, location: {…}, history: {…}, //other stuff }

Step 2 I can access the history object to change my location

//lots of code here relating to my whatever request I just ran delete, put so on

this.props.history.push("/") // then put in whatever url you want to go to

Also I'm just a coding bootcamp student, so I'm no expert, but I know you can also you use

window.location = "/" //wherever you want to go

Correct me if I'm wrong, but when I tested that out it reloaded the entire page which I thought defeated the entire point of using React.

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

How to sort a list of strings?

It is simple: https://trinket.io/library/trinkets/5db81676e4

scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'

scores = scores.split(',') for x in sorted(scores): print(x)

div inside php echo

You can do the following:

echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';

If you want to have it inside your statement, do this:

if($cart->count_product > 0) 
{
    echo '<div class="my_class">'.$cart->count_product.'</div>';
}

You don't need the else statement, since you're only going to output the above when it's truthy anyway.

Notification Icon with the new Firebase Cloud Messaging system

My solution is similar to ATom's one, but easier to implement. You don't need to create a class that shadows FirebaseMessagingService completely, you can just override the method that receives the Intent (which is public, at least in version 9.6.1) and take the information to be displayed from the extras. The "hacky" part is that the method name is indeed obfuscated and is gonna change every time you update the Firebase sdk to a new version, but you can look it up quickly by inspecting FirebaseMessagingService with Android Studio and looking for a public method that takes an Intent as the only parameter. In version 9.6.1 it's called zzm. Here's how my service looks like:

public class MyNotificationService extends FirebaseMessagingService {

    public void onMessageReceived(RemoteMessage remoteMessage) {
        // do nothing
    }

    @Override
    public void zzm(Intent intent) {
        Intent launchIntent = new Intent(this, SplashScreenActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R    equest code */, launchIntent,
                PendingIntent.FLAG_ONE_SHOT);
        Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setLargeIcon(rawBitmap)
                .setContentTitle(intent.getStringExtra("gcm.notification.title"))
                .setContentText(intent.getStringExtra("gcm.notification.body"))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager)     getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Set scroll position

You can use window.scrollTo(), like this:

window.scrollTo(0, 0); // values are x,y-offset

HTML5 form required attribute. Set custom validation message?

Try this one, its better and tested:

HTML:

<form id="myform">
    <input id="email" 
           oninvalid="InvalidMsg(this);" 
           oninput="InvalidMsg(this);"
           name="email"  
           type="email" 
           required="required" />
    <input type="submit" />
</form>

JAVASCRIPT:

function InvalidMsg(textbox) {
    if (textbox.value === '') {
        textbox.setCustomValidity('Required email address');
    } else if (textbox.validity.typeMismatch){
        textbox.setCustomValidity('please enter a valid email address');
    } else {
       textbox.setCustomValidity('');
    }

    return true;
}

Demo:

http://jsfiddle.net/patelriki13/Sqq8e/

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

ggplot combining two plots from different data.frames

As Baptiste said, you need to specify the data argument at the geom level. Either

#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) + 
    geom_point() +
    geom_step(data = df2)
)

or

#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) + 
      geom_point(data = df1) +
      geom_step(data = df2)
)

How to close IPython Notebook properly?

I am copy pasting from the Jupyter/IPython Notebook Quick Start Guide Documentation, released on Feb 13, 2018. http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html

1.3.3 Close a notebook: kernel shut down When a notebook is opened, its “computational engine” (called the kernel) is automatically started. Closing the notebook browser tab, will not shut down the kernel, instead the kernel will keep running until is explicitly shut down. To shut down a kernel, go to the associated notebook and click on menu File -> Close and Halt. Alternatively, the Notebook Dashboard has a tab named Running that shows all the running notebooks (i.e. kernels) and allows shutting them down (by clicking on a Shutdown button).

Summary: First close and halt the notebooks running.

1.3.2 Shut down the Jupyter Notebook App Closing the browser (or the tab) will not close the Jupyter Notebook App. To completely shut it down you need to close the associated terminal. In more detail, the Jupyter Notebook App is a server that appears in your browser at a default address (http://localhost:8888). Closing the browser will not shut down the server. You can reopen the previous address and the Jupyter Notebook App will be redisplayed. You can run many copies of the Jupyter Notebook App and they will show up at a similar address (only the number after “:”, which is the port, will increment for each new copy). Since with a single Jupyter Notebook App you can already open many notebooks, we do not recommend running multiple copies of Jupyter Notebook App.

Summary: Second, quit the terminal from which you fired Jupyter.

Strange Jackson exception being thrown when serializing Hibernate object

i got the same error, but with no relation to Hibernate. I got scared here from all frightening suggestions, which i guess relevant in case of Hibernate and lazy loading... However, in my case i got the error since in an inner class i had no getters/setters, so the BeanSerializer could not serialize the data...

Adding getters & setters resolved the problem.

What does "The APR based Apache Tomcat Native library was not found" mean?

Had this problem as well. If you do have the libraries, but still have this error, it may be a configuration error. Your server.xml may be missing the following line:

 <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

(Alternatively, it may be commented out). This <Listener>, like other listeners is a child of the top-level <Server>.

Without the <Listener> line, there's no attempt to load the APR library, so LD_LIBRARY_PATH and -Djava.library.path= settings are ignored.

How to set a Default Route (To an Area) in MVC

routes.MapRoute(
                "Area",
                "{area}/",
                new { area = "AreaZ", controller = "ControlerX ", action = "ActionY " }
            );

Have you tried that ?

Twitter Bootstrap - add top space between rows

Bootstrap3

CSS (gutter only, without margins around):

.row.row-gutter {
  margin-bottom: -15px;
  overflow: hidden;
}
.row.row-gutter > *[class^="col"] {
  margin-bottom: 15px;
}

CSS (equal margins around, 15px/2):

.row.row-margins {
  padding-top: 7px; /* or margin-top: 7px; */
  padding-bottom: 7px; /* or margin-bottom: 7px; */
}
.row.row-margins > *[class^="col"] {
  margin-top: 8px;
  margin-bottom: 8px;
}

Usage:

<div class="row row-gutter">
    <div class="col col-sm-9">first</div>
    <div class="col col-sm-3">second</div>
    <div class="col col-sm-12">third</div>
</div>

(with SASS or LESS 15px could be a variable from bootstrap)

What is the most efficient way to concatenate N arrays?

[].concat.apply([], [array1, array2, ...])

edit: proof of efficiency: http://jsperf.com/multi-array-concat/7

edit2: Tim Supinie mentions in the comments that this may cause the interpreter to exceed the call stack size. This is perhaps dependent on the js engine, but I've also gotten "Maximum call stack size exceeded" on Chrome at least. Test case: [].concat.apply([], Array(300000).fill().map(_=>[1,2,3])). (I've also gotten the same error using the currently accepted answer, so one is anticipating such use cases or building a library for others, special testing may be necessary no matter which solution you choose.)

Axios get in url works but with second parameter as object it doesn't

On client:

  axios.get('/api', {
      params: {
        foo: 'bar'
      }
    });

On server:

function get(req, res, next) {

  let param = req.query.foo
   .....
}

How to convert date to timestamp in PHP?

<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>

http://php.net/manual/en/function.date.php

How do I disable "missing docstring" warnings at a file-level in Pylint?

Edit file "C:\Users\Your User\AppData\Roaming\Code\User\settings.json" and add these python.linting.pylintArgs lines at the end as shown below:

{
    "team.showWelcomeMessage": false,
    "python.dataScience.sendSelectionToInteractiveWindow": true,
    "git.enableSmartCommit": true,
    "powershell.codeFormatting.useCorrectCasing": true,
    "files.autoSave": "onWindowChange",
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
        "--errors-only"
    ],
}