Programs & Examples On #Dbunit

DbUnit is a JUnit extension targeted at database-driven projects that, among other things, puts your database into a known state between test runs.

Why doesn't java.util.Set have get(int index)?

Please note only 2 basic data structure can be accessed via index.

  • Array data structure can be accessed via index with O(1) time complexity to achieve get(int index) operation.
  • LinkedList data structure can also be accessed via index, but with O(n) time complexity to achieve get(int index) operation.

In Java, ArrayList is implemented using Array data structure.

While Set data structure usually can be implemented via HashTable/HashMap or BalancedTree data structure, for fast detecting whether an element exists and add non-existing element, usually a well implemented Set can achieve O(1) time complexity contains operation. In Java, HashSet is the most common used implementation of Set, it is implemented by calling HashMap API, and HashMap is implemented using separate chaining with linked lists (a combination of Array and LinkedList).

Since Set can be implemented via different data structure, there is no get(int index) method for it.

How do I create a readable diff of two spreadsheets using git diff?

I found an openoffice macro here that will invoke openoffice's compare documents function on two files. Unfortunately, openoffice's spreadsheet compare seems a little flaky; I just had the 'Reject All' button insert a superfluous column in my document.

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

use MM(months) instead of mm(minutes) :

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

check here for more format options.

Determine the line of code that causes a segmentation fault?

All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.

If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.

It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

look at this

https://codepen.io/bagdaulet/pen/bzdKjL

getElementById fastest than querySelector on 25%

jquery is slowest

var q = time_my_script(function() {

    for (i = 0; i < 1000000; i++) {
         var w = document.querySelector('#ll');
    }

});

console.log('querySelector: '+q+'ms');

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

Test if a vector contains a given element

Both the match() (returns the first appearance) and %in% (returns a Boolean) functions are designed for this.

v <- c('a','b','c','e')

'b' %in% v
## returns TRUE

match('b',v)
## returns the first location of 'b', in this case: 2

Retrieving a random item from ArrayList

anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.

Might want to re-write it like:

import java.util.ArrayList;
import java.util.Random;

public class Catalogue
{
    private Random randomGenerator;
    private ArrayList<Item> catalogue;

    public Catalogue()
    { 
        catalogue = new ArrayList<Item>();
        randomGenerator = new Random();
    }

    public Item anyItem()
    {
        int index = randomGenerator.nextInt(catalogue.size());
        Item item = catalogue.get(index);
        System.out.println("Managers choice this week" + item + "our recommendation to you");
        return item;
    }
}

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

Setting a div's height in HTML with CSS

A 2 column layout is a little bit tough to get working in CSS (at least until CSS3 is practical.)

Floating left and right will work to a point, but it won't allow you to extend the background. To make backgrounds stay solid, you'll have to implement a technique known as "faux columns," which basically means your columns themselves won't have a background image. Your 2 columns will be contained inside of a parent tag. This parent tag is given a background image that contains the 2 column colors you want. Make this background only as big as you need it to (if it is a solid color, only make it 1 pixel high) and have it repeat-y. AListApart has a great walkthrough on what is needed to make it work.

http://www.alistapart.com/articles/fauxcolumns/

What is the best data type to use for money in C#?

Decimal. If you choose double you're leaving yourself open to rounding errors

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

How can you integrate a custom file browser/uploader with CKEditor?

An article at zerokspot entitled Custom filebrowser callbacks in CKEditor 3.0 handles this. The most relevant section is quoted below:

So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:

window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);

For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:

<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage); </script>

If the upload failed, set the errorMessage to some non-zero-length string and empty the url, and vice versa on success.

How do I change the number of open files limit in Linux?

If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting

[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread

Try to put ulimit -s unlimited into /etc/init.d/httpd. This does not require a server reboot.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

This is a great solution! With a few additional CSS rules you can format it just like an MS Word outline list with a hanging first line indent:

OL { 
  counter-reset: item; 
}
LI { 
  display: block; 
}
LI:before { 
  content: counters(item, ".") "."; 
  counter-increment: item; 
  padding-right:10px; 
  margin-left:-20px;
}

Get selected value in dropdown list using JavaScript

Just do: document.getElementById('idselect').options.selectedIndex

Then you i'll get select index value, starting in 0.

What are allowed characters in cookies?

There is another interesting issue with IE and Edge. Cookies that have names with more than 1 period seem to be silently dropped. So This works:

cookie_name_a=valuea

while this will get dropped

cookie.name.a=valuea

XSLT - How to select XML Attribute by Attribute?

I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t

<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>

Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.

Mixing C# & VB In The Same Project

No, you can't. An assembly/project (each project compiles to 1 assembly usually) has to be one language. However, you can use multiple assemblies, and each can be coded in a different language because they are all compiled to CIL.

It compiled fine and didn't complain because a VB.NET project will only actually compile the .vb files and a C# project will only actually compile the .cs files. It was ignoring the other ones, therefore you did not receive errors.

Edit: If you add a .vb file to a C# project, select the file in the Solution Explorer panel and then look at the Properties panel, you'll notice that the Build Action is 'Content', not 'Compile'. It is treated as a simple text file and doesn't even get embedded in the compiled assembly as a binary resource.

Edit: With asp.net websites you may add c# web user control to vb.net website

How do I do a case-insensitive string comparison?

The usual approach is to uppercase the strings or lower case them for the lookups and comparisons. For example:

>>> "hello".upper() == "HELLO".upper()
True
>>> 

How to use Spring Boot with MySQL database and JPA?

When moving classes into specific packages like repository, controller, domain just the generic @SpringBootApplication is not enough.

You will have to specify the base package for component scan

@ComponentScan("base_package")

For JPA

@EnableJpaRepositories(basePackages = "repository")

is also needed, so spring data will know where to look into for repository interfaces.

Catching exceptions from Guzzle

I was catching GuzzleHttp\Exception\BadResponseException as @dado is suggesting. But one day I got GuzzleHttp\Exception\ConnectException when DNS for domain wasn't available. So my suggestion is - catch GuzzleHttp\Exception\ConnectException to be safe about DNS errors as well.

Copy filtered data to another sheet using VBA

I suggest you do it a different way.

In the following code I set as a Range the column with the sports name F and loop through each cell of it, check if it is "hockey" and if yes I insert the values in the other sheet one by one, by using Offset.

I do not think it is very complicated and even if you are just learning VBA, you should probably be able to understand every step. Please let me know if you need some clarification

Sub TestThat()

'Declare the variables
Dim DataSh As Worksheet
Dim HokySh As Worksheet
Dim SportsRange As Range
Dim rCell As Range
Dim i As Long

'Set the variables
Set DataSh = ThisWorkbook.Sheets("Data")
Set HokySh = ThisWorkbook.Sheets("Hoky")

Set SportsRange = DataSh.Range(DataSh.Cells(3, 6), DataSh.Cells(Rows.Count, 6).End(xlUp))
    'I went from the cell row3/column6 (or F3) and go down until the last non empty cell

    i = 2

    For Each rCell In SportsRange 'loop through each cell in the range

        If rCell = "hockey" Then 'check if the cell is equal to "hockey"

            i = i + 1                                'Row number (+1 everytime I found another "hockey")
            HokySh.Cells(i, 2) = i - 2               'S No.
            HokySh.Cells(i, 3) = rCell.Offset(0, -1) 'School
            HokySh.Cells(i, 4) = rCell.Offset(0, -2) 'Background
            HokySh.Cells(i, 5) = rCell.Offset(0, -3) 'Age

        End If

    Next rCell

End Sub

Invalid application path

I eventually tracked this down to the Anonymous Authentication Credentials. I don't know what had changed, because this application used to work, but anyway, this is what I did: Click on the Application -> Authentication. Make sure Anonymous Authentication is enabled (it was, in my case), but also click on Edit... and change the anonymous user identity to "Application pool identity" not "Specific user". Making this change worked for me.

Regards.

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

I am using XAMPP on Ubuntu. I found this error when connecting database through terminal. I solve it without any configuration because default socket file path in XAMPP is written in "/opt/lampp/etc/my.cnf" as following:

[client]
#password   = your_password
port        = 3306
socket      = /opt/lampp/var/mysql/mysql.sock

now you can connect just by giving this socket path parameter with mysql command on terminal like:

mysql -u root --socket /opt/lampp/var/mysql/mysql.sock

and it's done without any configuration.

If you don't want to type socket path everytime, then go for changing default path in my.cnf by "/var/run/mysqld/mysqld.sock". Provide permissions and restart mysql server.

Determine the number of NA values in a column

sapply(name of the data, function(x) sum(is.na(x)))

How to get the full url in Express?

Here is a great way to add a function you can call on the req object to get the url

  app.use(function(req, res, next) {
    req.getUrl = function() {
      return req.protocol + "://" + req.get('host') + req.originalUrl;
    }
    return next();
  });

Now you have a function you can call on demand if you need it.

Creating a div element in jQuery

If you are using Jquery > 1.4, you are best of with Ian's answer. Otherwise, I would use this method:

This is very similar to celoron's answer, but I don't know why they used document.createElement instead of Jquery notation.

$("body").append(function(){
        return $("<div/>").html("I'm a freshly created div. I also contain some Ps!")
            .attr("id","myDivId")
            .addClass("myDivClass")
            .css("border", "solid")                 
            .append($("<p/>").html("I think, therefore I am."))
            .append($("<p/>").html("The die is cast."))
});

//Some style, for better demonstration if you want to try it out. Don't use this approach for actual design and layout!
$("body").append($("<style/>").html("p{background-color:blue;}div{background-color:yellow;}div>p{color:white;}"));

I also think using append() with a callback function is in this case more readable, because you now immediately that something is going to be appended to the body. But that is a matter of taste, as always when writing any code or text.

In general, use as less HTML as possible in JQuery code, since this is mostly spaghetti code. It is error prone and hard to maintain, because the HTML-String can easily contain typos. Also, it mixes a markup language (HTML) with a programming language (Javascript/Jquery), which is usually a bad Idea.

How do I set the maximum line length in PyCharm?

For PyCharm 4

File >> Settings >> Editor >> Code Style: Right margin (columns)

suggestion: Take a look at other options in that tab, they're very helpful

How to make borders collapse (on a div)?

Use simple negative margin rather than using display table.

Updated in fiddle JS Fiddle

.container { 
    border-style: solid;
    border-color: red;
    border-width: 1px 0 0 1px;
    display: inline-block;
}
.column { 
    float: left; overflow: hidden; 
}
.cell { 
    border: 1px solid red; width: 120px; height: 20px; 
    margin:-1px 0 0 -1px;
}
.clearfix {
    clear:both;
}

What is the convention in JSON for empty vs. null?

Empty array for empty collections and null for everything else.

Selenium WebDriver: Wait for complex page with JavaScript to load

I had a same issue. This solution works for me from WebDriverDoku:

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

How do I print the elements of a C++ vector in GDB?

To view vector std::vector myVector contents, just type in GDB:

(gdb) print myVector

This will produce an output similar to:

$1 = std::vector of length 3, capacity 4 = {10, 20, 30}

To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on gdb wiki.

What is more, after installing above, this works well with Eclipse C++ debugger GUI (and any other IDE using GDB, as I think).

Is it possible to embed animated GIFs in PDFs?

I haven't tested it but apparently you can add quicktime animations to a pdf (no idea why). So the solution would be to export the animated gif to quicktime and add it to the pdf.

Here the solution that apparently works:

  1. Open the GIF in Quicktime and save as MOV (Apparently it works with other formats too, you'll have to try it out).
  2. Insert the MOV into the PDF (with Adobe InDesign (make sure to set Object> Interactive> film options > Embed in PDF) - It should work with Adobe Acrobat Pro DC too: see link
  3. Save the PDF.

See this link (German)

Where is the web server root directory in WAMP?

If you installed WAMP to c:\wamp then I believe your webserver root directory would be c:\wamp\www, however this might vary depending on version.

Yes, this is where you would put your site files to access them through a browser.

How to get the containing form of an input?

would this work? (leaving action blank submits form back to itself too, right?)

<form action="">
<select name="memberid" onchange="this.form.submit();">
<option value="1">member 1</option>
<option value="2">member 2</option>
</select>

"this" would be the select element, .form would be its parent form. Right?

ReactJS - .JS vs .JSX

JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern

// filename: MyComponent.js
function MyComponent() {
  return <div />;
}

as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here

Recommended add-ons/plugins for Microsoft Visual Studio

KingsTools is also a nice collection of macros containing:

  • Run Doxygen
  • Insert Doxygen comments
  • Build Solution stats
  • Dependency Graph
  • Inheritance Graph
  • Swap .h<->.cpp
  • Colorize
  • } End of
  • region/#endregion for c++

  • Search the web

How can I submit a form using JavaScript?

Set the name attribute of your form to "theForm" and your code will work.

tmux set -g mouse-mode on doesn't work

Just a quick heads-up to anyone else who is losing their mind right now:

https://github.com/tmux/tmux/blob/310f0a960ca64fa3809545badc629c0c166c6cd2/CHANGES#L12

so that's just

 :setw -g mouse

Send FormData with other field in AngularJS

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.

var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

Selecting last element in JavaScript array

Use JavaScript objects if this is critical to your application. You shouldn't be using raw primitives to manage critical parts of your application. As this seems to be the core of your application, you should use objects instead. I've written some code below to help get you started. The method lastLocation would return the last location.


function User(id) {
    this.id = id;

    this.locations = [];

    this.getId = function() {
        return this.id;
    };

    this.addLocation = function(latitude, longitude) {
        this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
    };

    this.lastLocation = function() {
        return this.locations[this.locations.length - 1];
    };

    this.removeLastLocation = function() {
        return this.locations.pop();
    };

}

function Users() {
    this.users = {};

    this.generateId = function() {
        return Math.random();
    };

    this.createUser = function() {
        var id = this.generateId();
        this.users[id] = new User(id);
        return this.users[id];
    };

    this.getUser = function(id) {
        return this.users[id];
    };

    this.removeUser = function(id) {
        var user = this.getUser(id);
        delete this.users[id];

        return user;
    };

}


var users = new Users();

var user = users.createUser();

user.addLocation(0, 0);
user.addLocation(0, 1);

Which are more performant, CTE or temporary tables?

One use where I found CTE's excelled performance wise was where I needed to join a relatively complex Query on to a few tables which had a few million rows each.

I used the CTE to first select the subset based of the indexed columns to first cut these tables down to a few thousand relevant rows each and then joined the CTE to my main query. This exponentially reduced the runtime of my query.

Whilst results for the CTE are not cached and table variables might have been a better choice I really just wanted to try them out and found the fit the above scenario.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

How do I add a Font Awesome icon to input field?

Similar to the top answer, I used the unicode character in the value= section of the HTML and called FontAwesome as the font family on that input element. The only thing I'll add that the top answer doesn't cover is that because my value element also had text inside it after the icon, changing the font family to FontAwesome made the regular text look bad. The solution was simply to change the CSS to include fallback fonts:

<input type="text" id="datepicker" placeholder="Change Date" value="? Sat Oct 19" readonly="readonly" class="hasDatepicker">

font-family: FontAwesome, Roboto, sans-serif;

This way, FontAwesome will grab the icon, but all non-icon text will have the desired font applied.

Selecting a Record With MAX Value

Note: An incorrect revision of this answer was edited out. Please review all answers.

A subselect in the WHERE clause to retrieve the greatest BALANCE aggregated over all rows. If multiple ID values share that balance value, all would be returned.

SELECT 
  ID,
  BALANCE
FROM CUSTOMERS
WHERE BALANCE = (SELECT MAX(BALANCE) FROM CUSTOMERS)

Java serialization - java.io.InvalidClassException local class incompatible

The short answer here is the serial ID is computed via a hash if you don't specify it. (Static members are not inherited--they are static, there's only (1) and it belongs to the class).

http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html

The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.

If you alter a class or its hierarchy your hash will be different. This is a good thing. Your objects are different now that they have different members. As such, if you read it back in from its serialized form it is in fact a different object--thus the exception.

The long answer is the serialization is extremely useful, but probably shouldn't be used for persistence unless there's no other way to do it. Its a dangerous path specifically because of what you're experiencing. You should consider a database, XML, a file format and probably a JPA or other persistence structure for a pure Java project.

Capturing TAB key in text box

In Chrome on the Mac, alt-tab inserts a tab character into a <textarea> field.

Here’s one: . Wee!

Split a List into smaller lists of N size

I find accepted answer (Serj-Tm) most robust, but I'd like to suggest a generic version.

public static List<List<T>> splitList<T>(List<T> locations, int nSize = 30)
{
    var list = new List<List<T>>();

    for (int i = 0; i < locations.Count; i += nSize)
    {
        list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i)));
    }

    return list;
}

How to store a datetime in MySQL with timezone info

MySQL stores DATETIME without timezone information. Let's say you store '2019-01-01 20:00:00' into a DATETIME field, when you retrieve that value you're expected to know what timezone it belongs to.

So in your case, when you store a value into a DATETIME field, make sure it is Tanzania time. Then when you get it out, it will be Tanzania time. Yay!

Now, the hairy question is: When I do an INSERT/UPDATE, how do I make sure the value is Tanzania time? Two cases:

  1. You do INSERT INTO table (dateCreated) VALUES (CURRENT_TIMESTAMP or NOW()).

  2. You do INSERT INTO table (dateCreated) VALUES (?), and specify the current time from your application code.

CASE #1

MySQL will take the current time, let's say that is '2019-01-01 20:00:00' Tanzania time. Then MySQL will convert it to UTC, which comes out to '2019-01-01 17:00:00', and store that value into the field.

So how do you get the Tanzania time, which is '20:00:00', to store into the field? It's not possible. Your code will need to expect UTC time when reading from this field.

CASE #2

It depends on what type of value you pass as ?. If you pass the string '2019-01-01 20:00:00', then good for you, that's exactly what will be stored to the DB. If you pass a Date object of some kind, then it'll depend on how the db driver interprets that Date object, and ultimate what 'YYYY-MM-DD HH:mm:ss' string it provides to MySQL for storage. The db driver's documentation should tell you.

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

Get the name of an object's type

Use constructor.name when you can, and regex function when I can't.

Function.prototype.getName = function(){
  if (typeof this.name != 'undefined')
    return this.name;
  else
    return /function (.+)\(/.exec(this.toString())[1];
};

Xampp localhost/dashboard

If you want to display directory than edit htdocs/index.php file

Below code is display all directory in table

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to Nims Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="server/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- START PAGE SOURCE -->
<div id="wrap">
  <div id="top">
    <h1 id="sitename">Nims <em>Server</em> Directory list</h1>
    <div id="searchbar">
      <form action="#">
        <div id="searchfield">
          <input type="text" name="keyword" class="keyword" />
          <input class="searchbutton" type="image" src="server/images/searchgo.gif"  alt="search" />
        </div>
      </form>
    </div>
  </div>

<div class="background">
<div class="transbox">
<table width="100%" border="0" cellspacing="3" cellpadding="5" style="border:0px solid #333333;background: #F9F9F9;"> 
<tr>
<?php
//echo md5("saketbook007");

//File functuion DIR is used here.
$d = dir($_SERVER['DOCUMENT_ROOT']); 
$i=-1;
//Loop start with read function
while ($entry = $d->read()) {
if($entry == "." || $entry ==".."){
}else{
?>
<td  class="site" width="33%"><a href="<?php echo $entry;?>" ><?php echo ucfirst($entry); ?></a></td>  
<?php 
}
if($i%3 == 0){
echo "</tr><tr>";
}
$i++;
}?>
</tr> 
</table>

<?php $d->close();
?> 

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

Style:

@import url("fontface.css");
* {
    padding:0;
    margin:0;
}
.clear {
    clear:both;
}

body {
    background:url(images/bg.jpg) repeat;
    font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
    color:#212713;
}
#wrap {
    width:1300px;
    margin:auto;
}

#sitename {
    font: normal 46px chunk;
    color:#1b2502;
    text-shadow:#5d7a17 1px 1px 1px;
    display:block;
    padding:45px 0 0 0;
    width:60%;
    float:left;
}
#searchbar {
    width:39%;
    float:right;
}
#sitename em {
    font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
}
#top {
    height:145px;
}
img {

    width:90%;
    height:250px;
    padding:10px;
    border:1px solid #000;
    margin:0 0 0 50px;
}


.post h2 a {
    color:#656f42;
    text-decoration:none;
}
#searchbar {
    padding:55px 0 0 0;
}
#searchfield {
    background:url(images/searchbar.gif) no-repeat;
    width:239px;
    height:35px;
    float:right;
}
#searchfield .keyword {
    width:170px;
    background:transparent;
    border:none;
    padding:8px 0 0 10px;
    color:#fff;
    display:block;
    float:left;
}
#searchfield .searchbutton {
    display:block;
    float:left;
    margin:7px 0 0 5px;
}

div.background
{
  background:url(h.jpg) repeat-x;
  border: 2px solid black;

  width:99%;
}
div.transbox
{
  margin: 15px;
  background-color: #ffffff;

  border: 1px solid black;
  opacity:0.8;
  filter:alpha(opacity=60); /* For IE8 and earlier */
  height:500px;
}

.site{

border:1px solid #CCC; 
}

.site a{text-decoration:none;font-weight:bold; color:#000; line-height:2}
.site:hover{background:#000; border:1px solid #03C;}
.site:hover a{color:#FFF}

Output : enter image description here

C/C++ NaN constant (literal)?

Is this possible to assign a NaN to a double or float in C ...?

Yes, since C99, (C++11) <math.h> offers the below functions:

#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

which are like their strtod("NAN(n-char-sequence)",0) counterparts and NAN for assignments.

// Sample C code
uint64_t u64;
double x;
x = nan("0x12345");
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = -strtod("NAN(6789A)",0);
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = NAN;
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);

Sample output: (Implementation dependent)

(7ff8000000012345)
(fff000000006789a)
(7ff8000000000000)

How do you send a Firebase Notification to all devices via CURL?

Firebase Notifications doesn't have an API to send messages. Luckily it is built on top of Firebase Cloud Messaging, which has precisely such an API.

With Firebase Notifications and Cloud Messaging, you can send so-called downstream messages to devices in three ways:

  1. to specific devices, if you know their device IDs
  2. to groups of devices, if you know the registration IDs of the groups
  3. to topics, which are just keys that devices can subscribe to

You'll note that there is no way to send to all devices explicitly. You can build such functionality with each of these though, for example: by subscribing the app to a topic when it starts (e.g. /topics/all) or by keeping a list of all device IDs, and then sending the message to all of those.

For sending to a topic you have a syntax error in your command. Topics are identified by starting with /topics/. Since you don't have that in your code, the server interprets allDevices as a device id. Since it is an invalid format for a device registration token, it raises an error.

From the documentation on sending messages to topics:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}

Add empty columns to a dataframe with specified names from a vector

The problem with your code is in the line:

for(i in length(namevector))

You need to ask yourself: what is length(namevector)? It's one number. So essentially you're saying:

for(i in 11)
df[,i] <- NA

Or more simply:

df[,11] <- NA

That's why you're getting an error. What you want is:

for(i in namevector)
    df[,i] <- NA

Or more simply:

df[,namevector] <- NA

How can I add an ampersand for a value in a ASP.net/C# app config file value

Have you tried this?

<appSettings>  
  <add key="myurl" value="http://www.myurl.com?&amp;cid=&amp;sid="/>
<appSettings>

String length in bytes in JavaScript

Here is a much faster version, which doesn't use regular expressions, nor encodeURIComponent():

function byteLength(str) {
  // returns the byte length of an utf8 string
  var s = str.length;
  for (var i=str.length-1; i>=0; i--) {
    var code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s+=2;
    if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
  }
  return s;
}

Here is a performance comparison.

It just computes the length in UTF8 of each unicode codepoints returned by charCodeAt() (based on wikipedia's descriptions of UTF8, and UTF16 surrogate characters).

It follows RFC3629 (where UTF-8 characters are at most 4-bytes long).

Difference between iCalendar (.ics) and the vCalendar (.vcs)

Both .ics and .vcs files are in ASCII. If you use "Save As" option to save a calendar entry (Appt, Meeting Request/Response/Postpone/Cancel and etc) in both .ics and .vcs format and use vimdiff, you can easily see the difference.

Both .vcs (vCal) and .ics (iCal) belongs to the same VCALENDAR camp, but .vcs file shows "VERSION:1.0" whereas .ics file uses "VERSION:2.0".

The spec for vCalendar v1.0 can be found at http://www.imc.org/pdi/pdiproddev.html. The spec for iCalendar (vCalendar v2.0) is in RFC5545. In general, the newer is better, and that is true for Outlook 2007 and onward, but not for Outlook 2003.

For Outlook 2003, the behavior is peculiar. It can save the same calendar entry in both .ics and .vcs format, but it only read & display .vcs file correctly. It can read .ics file but it omits some fields and does not display it in calendar mode. My guess is that back then Microsoft wanted to provide .ics to be compatible with Mac's iCal but not quite committed to v2.0 yet.

So I would say for Outlook 2003, .vcs is the native format.

javascript functions to show and hide divs

<script> 
    function show() { 
        if(document.getElementById('benefits').style.display=='none') { 
            document.getElementById('benefits').style.display='block'; 
        } 
        return false;
    } 
    function hide() { 
        if(document.getElementById('benefits').style.display=='block') { 
            document.getElementById('benefits').style.display='none'; 
        } 
        return false;
    }   
</script> 


 <div id="opener"><a href="#1" name="1" onclick="return show();">click here</a></div> 
    <div id="benefits" style="display:none;">some input in here plus the close button 
           <div id="upbutton"><a onclick="return hide();">click here</a></div> 
    </div> 

Change SQLite database mode to read-write

Edit the DB: I was having problems editing the db. I ended up having to
sudo chown 'non root username' ts3server.sqlitedb
as long as it wasn't root, i could edit the file. Username is the username of my non root account.

Auto start TeamSpeak: as your non root account
crontab -e
@reboot /path to ts3server/ aka /home/ts3server/ts3server_startscript.sh start

Google Spreadsheet, Count IF contains a string

You should use

=COUNTIF(A2:A51, "*iPad*")/COUNTA(A2:A51)

Additionally, if you wanted to count more than one element, like iPads OR Kindles, you would use

=SUM(COUNTIF(A2:A51, {"*iPad*", "*kindle*"}))/COUNTA(A2:A51)

in the numerator.

.htaccess redirect http to https

I use the following to successfully redirect all pages of my domain from http to https:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Note this will redirect using the 301 'permanently moved' redirect, which will help transfer your SEO rankings.

To redirect using the 302 'temporarily moved' change [R=302,L]

JavaFX 2.1 TableView refresh items

UPDATE:
Finally tableview refreshing is resolved in JavaFX 8u60, which is available for early access.


About refreshing see the Updating rows in Tableview.
And about the blank column see the JavaFx 2 create TableView with single column. Basically it is not a column, i.e. you cannot select the item clicking on this blank column items. It is just a blank area styled like a row.


UPDATE: If you are updating the tableView via reseller_table.setItems(data) then you don't need to use SimpleStringProperty. It would be useful if you were updating one row/item only. Here is a working full example of refreshing the table data:

import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Dddeb extends Application {

    public static class Product {
        private String name;
        private String code;

        public Product(String name, String code) {
            this.name = name;
            this.code = code;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    private TableView<Product> productTable = new TableView<Product>();

    @Override
    public void start(Stage stage) {

        Button refreshBtn = new Button("Refresh table");
        refreshBtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                // You can get the new data from DB
                List<Product> newProducts = new ArrayList<Product>();
                newProducts.add(new Product("new product A", "1201"));
                newProducts.add(new Product("new product B", "1202"));
                newProducts.add(new Product("new product C", "1203"));
                newProducts.add(new Product("new product D", "1244"));

                productTable.getItems().clear();
                productTable.getItems().addAll(newProducts);
                //productTable.setItems(FXCollections.observableArrayList(newProducts));
            }
        });

        TableColumn nameCol = new TableColumn("Name");
        nameCol.setMinWidth(100);
        nameCol.setCellValueFactory(new PropertyValueFactory<Product, String>("name"));

        TableColumn codeCol = new TableColumn("Code");
        codeCol.setCellValueFactory(new PropertyValueFactory<Product, String>("code"));

        productTable.getColumns().addAll(nameCol, codeCol);
        productTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        // You can get the data from DB
        List<Product> products = new ArrayList<Product>();
        products.add(new Product("product A", "0001"));
        products.add(new Product("product B", "0002"));
        products.add(new Product("product C", "0003"));

        //productTable.getItems().addAll(products);
        productTable.setItems(FXCollections.observableArrayList(products));

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.getChildren().addAll(productTable, refreshBtn);

        Scene scene = new Scene(new Group());
        ((Group) scene.getRoot()).getChildren().addAll(vbox);
        stage.setScene(scene);
        stage.setWidth(300);
        stage.setHeight(500);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Note that

productTable.setItems(FXCollections.observableArrayList(newProducts));

and

productTable.getItems().clear();
productTable.getItems().addAll(newProducts);

are almost equivalent. So I used the one to fill the table for the first time and other when the table is refreshed. It is for demo purposes only. I have tested the code in JavaFX 2.1. And finally, you can (and should) edit your question to improve it by moving the code pieces in your answer to your question.

html button to send email

@user544079

Even though it is very old and irrelevant now, I am replying to help people like me! it should be like this:

<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">

Here $emailID, $MySubject, $MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):

<form method="post" action="mailto:[email protected]?subject=New Registration Alert &message= New Registration requires your approval">

Convert character to ASCII code in JavaScript

For supporting all UTF-16 (also non-BMP/supplementary characters) from ES6 the string.codePointAt() method is available;

This method is an improved version of charCodeAt which could support only unicode codepoints < 65536 ( 216 - a single 16bit ) .

Prevent form redirect OR refresh on submit?

If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):

<input name="o" required="required" aria-required="true" type="text">

You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:

$('form').on('submit', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment

As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.

So if you want to get rid of these default pop-ups, use the click event on the submit button:

$('form input[type=submit]').on('click', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

What is the purpose of the "role" attribute in HTML?

Is this role attribute necessary?

Answer: Yes.

  • The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
  • Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.

It provides you:

  • Accessibility
  • Device adaptation
  • Server-side processing
  • Complex data description,...etc.

How can I change the text inside my <span> with jQuery?

This will be used to change the Html content inside the span

 $('#abc span').html('goes inside the span');

if you want to change the text inside the span, you can use:

 $('#abc span').text('goes inside the span');

How can I find where Python is installed on Windows?

Simple way is

1) open CMD
2) type >>where python

Creating a triangle with for loops

Try this one in Java

for (int i = 6, k = 0; i > 0 && k < 6; i--, k++) {
    for (int j = 0; j < i; j++) {
        System.out.print(" ");
    }
    for (int j = 0; j < k; j++) {
        System.out.print("*");
    }
    for (int j = 1; j < k; j++) {
        System.out.print("*");
    }
    System.out.println();
}

Calculating bits required to store decimal number

let its required n bit then 2^n=(base)^digit and then take log and count no. for n

Relative imports for the billionth time

Here's a general recipe, modified to fit as an example, that I am using right now for dealing with Python libraries written as packages, that contain interdependent files, where I want to be able to test parts of them piecemeal. Let's call this lib.foo and say that it needs access to lib.fileA for functions f1 and f2, and lib.fileB for class Class3.

I have included a few print calls to help illustrate how this works. In practice you would want to remove them (and maybe also the from __future__ import print_function line).

This particular example is too simple to show when we really need to insert an entry into sys.path. (See Lars' answer for a case where we do need it, when we have two or more levels of package directories, and then we use os.path.dirname(os.path.dirname(__file__))—but it doesn't really hurt here either.) It's also safe enough to do this without the if _i in sys.path test. However, if each imported file inserts the same path—for instance, if both fileA and fileB want to import utilities from the package—this clutters up sys.path with the same path many times, so it's nice to have the if _i not in sys.path in the boilerplate.

from __future__ import print_function # only when showing how this works

if __package__:
    print('Package named {!r}; __name__ is {!r}'.format(__package__, __name__))
    from .fileA import f1, f2
    from .fileB import Class3
else:
    print('Not a package; __name__ is {!r}'.format(__name__))
    # these next steps should be used only with care and if needed
    # (remove the sys.path manipulation for simple cases!)
    import os, sys
    _i = os.path.dirname(os.path.abspath(__file__))
    if _i not in sys.path:
        print('inserting {!r} into sys.path'.format(_i))
        sys.path.insert(0, _i)
    else:
        print('{!r} is already in sys.path'.format(_i))
    del _i # clean up global name space

    from fileA import f1, f2
    from fileB import Class3

... all the code as usual ...

if __name__ == '__main__':
    import doctest, sys
    ret = doctest.testmod()
    sys.exit(0 if ret.failed == 0 else 1)

The idea here is this (and note that these all function the same across python2.7 and python 3.x):

  1. If run as import lib or from lib import foo as a regular package import from ordinary code, __package is lib and __name__ is lib.foo. We take the first code path, importing from .fileA, etc.

  2. If run as python lib/foo.py, __package__ will be None and __name__ will be __main__.

    We take the second code path. The lib directory will already be in sys.path so there is no need to add it. We import from fileA, etc.

  3. If run within the lib directory as python foo.py, the behavior is the same as for case 2.

  4. If run within the lib directory as python -m foo, the behavior is similar to cases 2 and 3. However, the path to the lib directory is not in sys.path, so we add it before importing. The same applies if we run Python and then import foo.

    (Since . is in sys.path, we don't really need to add the absolute version of the path here. This is where a deeper package nesting structure, where we want to do from ..otherlib.fileC import ..., makes a difference. If you're not doing this, you can omit all the sys.path manipulation entirely.)

Notes

There is still a quirk. If you run this whole thing from outside:

$ python2 lib.foo

or:

$ python3 lib.foo

the behavior depends on the contents of lib/__init__.py. If that exists and is empty, all is well:

Package named 'lib'; __name__ is '__main__'

But if lib/__init__.py itself imports routine so that it can export routine.name directly as lib.name, you get:

$ python2 lib.foo
Package named 'lib'; __name__ is 'lib.foo'
Package named 'lib'; __name__ is '__main__'

That is, the module gets imported twice, once via the package and then again as __main__ so that it runs your main code. Python 3.6 and later warn about this:

$ python3 lib.routine
Package named 'lib'; __name__ is 'lib.foo'
[...]/runpy.py:125: RuntimeWarning: 'lib.foo' found in sys.modules
after import of package 'lib', but prior to execution of 'lib.foo';
this may result in unpredictable behaviour
  warn(RuntimeWarning(msg))
Package named 'lib'; __name__ is '__main__'

The warning is new, but the warned-about behavior is not. It is part of what some call the double import trap. (For additional details see issue 27487.) Nick Coghlan says:

This next trap exists in all current versions of Python, including 3.3, and can be summed up in the following general guideline: "Never add a package directory, or any directory inside a package, directly to the Python path".

Note that while we violate that rule here, we do it only when the file being loaded is not being loaded as part of a package, and our modification is specifically designed to allow us to access other files in that package. (And, as I noted, we probably shouldn't do this at all for single level packages.) If we wanted to be extra-clean, we might rewrite this as, e.g.:

    import os, sys
    _i = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    if _i not in sys.path:
        sys.path.insert(0, _i)
    else:
        _i = None

    from sub.fileA import f1, f2
    from sub.fileB import Class3

    if _i:
        sys.path.remove(_i)
    del _i

That is, we modify sys.path long enough to achieve our imports, then put it back the way it was (deleting one copy of _i if and only if we added one copy of _i).

Left-pad printf with spaces

int space = 40;
printf("%*s", space, "Hello");

This statement will reserve a row of 40 characters, print string at the end of the row (removing extra spaces such that the total row length is constant at 40). Same can be used for characters and integers as follows:

printf("%*d", space, 10);
printf("%*c", space, 'x');

This method using a parameter to determine spaces is useful where a variable number of spaces is required. These statements will still work with integer literals as follows:

printf("%*d", 10, 10);
printf("%*c", 20, 'x');
printf("%*s", 30, "Hello");

Hope this helps someone like me in future.

Show DialogFragment with animation growing from a point

In DialogFragment, custom animation is called onCreateDialog. 'DialogAnimation' is custom animation style in previous answer.

public Dialog onCreateDialog(Bundle savedInstanceState) 
{
    final Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
    return dialog;
}

How to Install pip for python 3.7 on Ubuntu 18?

In general, don't do this:

pip install package

because, as you have correctly noticed, it's not clear what Python version you're installing package for.

Instead, if you want to install package for Python 3.7, do this:

python3.7 -m pip install package

Replace package with the name of whatever you're trying to install.

Took me a surprisingly long time to figure it out, too. The docs about it are here.

Your other option is to set up a virtual environment. Once your virtual environment is active, executable names like python and pip will point to the correct ones.

What is the difference between HAVING and WHERE in SQL?

HAVING: is used to check conditions after the aggregation takes place.
WHERE: is used to check conditions before the aggregation takes place.

This code:

select City, CNT=Count(1)
From Address
Where State = 'MA'
Group By City

Gives you a table of all cities in MA and the number of addresses in each city.

This code:

select City, CNT=Count(1)
From Address
Where State = 'MA'
Group By City
Having Count(1)>5

Gives you a table of cities in MA with more than 5 addresses and the number of addresses in each city.

How to print a linebreak in a python function?

All three way you can use for newline character :

'\n'

"\n"

"""\n"""

PostgreSQL next value of the sequences?

I tried this and it works perfectly

@Entity
public class Shipwreck {
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
  @Basic(optional = false)
  @SequenceGenerator(name = "seq", sequenceName = "shipwreck_seq", allocationSize = 1)
  Long id;

....

CREATE SEQUENCE public.shipwreck_seq
    INCREMENT 1
    START 110
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

JavaScript file not updating no matter what I do

A little late to the party, but if you put this in your html, it will keep your website from updating the cache. It takes the website a little longer to load, but for debugging purposes i like it. Taken from this answer: How to programmatically empty browser cache?

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>

Set folder browser dialog start location

In my case, it was an accidental double escaping.

this works:

SelectedPath = @"C:\Program Files\My Company\My product";

this doesn't:

SelectedPath = @"C:\\Program Files\\My Company\\My product";

Not showing placeholder for input type="date" field

From Angular point of view I managed to put a placeholder in input type date element.

First of all I defined the following css:

.placeholder {
    color: $text-grey;
  }

  input[type='date']::before {
    content: attr(placeholder);
  }

  input::-webkit-input-placeholder {
    color: $text-grey;
  }

The reason why this is neccessary is that if css3 content has different color that the normal placeholder, so I had to use a common one.

<input #birthDate
         class="birthDate placeholder"
         type="date"
         formControlName="birthDate"
         placeholder="{{getBirthDatePlaceholder() | translate}}"
         [class.error]="!onboardingForm.controls.birthDate.valid && onboardingForm.controls.birthDate.dirty"
         autocomplete="off"
         >

Then in the template used a viewchild birthDate attribute, to be able to access this input from the component. And defined an angular expression on the placeholder attribute, which will decide if we show the placeholder or not. This is the major drawback of the solution, is that you have to manage the visibility of the placeholder.

@ViewChild('birthDate') birthDate;

getBirthDatePlaceholder() {
  if (!this.birthDate) {
    return;
  } else {
    return this.birthDate.nativeElement.value === '' ?
    'ONBOARDING_FORM_COMPONENT.HINT_BIRTH_DATE' :
    '';
  }
}

How to convert a String to CharSequence?

Straight answer:

String s = "Hello World!";

// String => CharSequence conversion:

CharSequence cs = s;  // String is already a CharSequence

CharSequence is an interface, and the String class implements CharSequence.

How to configure "Shorten command line" method for whole project in IntelliJ

Intellij 2018.2.5

Run => Edit Configurations => Choose Node on the left hand side => expand Environment => Shorten Command line options => choose Classpath file or JAR manifest

Screen shot of Run/Debug Configuration showing the command line options

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

Here simple example to create pandas dataframe by using numpy array.

import numpy as np
import pandas as pd

# create an array 
var1  = np.arange(start=1, stop=21, step=1).reshape(-1)
var2 = np.random.rand(20,1).reshape(-1)
print(var1.shape)
print(var2.shape)

dataset = pd.DataFrame()
dataset['col1'] = var1
dataset['col2'] = var2
dataset.head()

INSERT INTO...SELECT for all MySQL columns

Addition to Mark Byers answer :

Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.

INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367

Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.

Uncaught ReferenceError: $ is not defined

I had this problem when tried to run different web-socket samples.

When pointing browser to 'http://localhost:8080/' I got this error, but pointing exactly to 'http://localhost:8080/index.html' gave no error since in 'index.html' all was fully ok - jquery was included before using $..

Somehow autoforwarding to index.html not fully worked

Procedure expects parameter which was not supplied

I had a problem where I would get the error when I supplied 0 to an integer param. And found that:

cmd.Parameters.AddWithValue("@Status", 0);

works, but this does not:

cmd.Parameters.Add(new SqlParameter("@Status", 0));

OnClick Send To Ajax

Tried and working. you are using,

<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

I am using javascript , (don't know about php), use id ="status" in textarea like

<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag

<srcipt>
function UpdateStatus(){

//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({

        type:"GET",//or POST
        url:'http://localhost:7080/ajaxforjson/Testajax',
                           //  (or whatever your url is)
        data:{data1:var1},
        //can send multipledata like {data1:var1,data2:var2,data3:var3
        //can use dataType:'text/html' or 'json' if response type expected 
        success:function(responsedata){
               // process on data
               alert("got response as "+"'"+responsedata+"'");

        }
     })

}
</script>

and jsp is like

the servlet will look like:   //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")

public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
    super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String data1=request.getParameter("data1");
    //do processing on datas pass in other java class to add to DB
    // i am adding or concatenate
    String data="i Got : "+"'"+data1+"' ";
    System.out.println(" data1 : "+data1+"\n data "+data);
    response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

Date to milliseconds and back to date in Swift

let dateTimeStamp = NSDate(timeIntervalSince1970:Double(currentTimeInMiliseconds())/1000)  //UTC time  //YOUR currentTimeInMiliseconds METHOD
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone() 
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle


let strDateSelect = dateFormatter.stringFromDate(dateTimeStamp)
print("Local Time", strDateSelect) //Local time


let dateFormatter2 = NSDateFormatter()
dateFormatter2.timeZone = NSTimeZone(name: "UTC") as NSTimeZone!
dateFormatter2.dateFormat = "yyyy-MM-dd"

let date3 = dateFormatter.dateFromString(strDateSelect)
print("DATE",date3)

How to deselect a selected UITableView cell?

Please check with the delegate method whether it is correct or not. For example;

-(void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

for

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

npm notice created a lockfile as package-lock.json. You should commit this file

Yes it is wise to use a version control system for your project. Anyway, focusing on your installation warning issue you can try to launch npm install command starting from your root project folder instead of outside of it, so the installation steps will only update the existing package-lock.json file instead of creating a new one. Hope this helps.

How to deselect all selected rows in a DataGridView control?

To deselect all rows and cells in a DataGridView, you can use the ClearSelection method:

myDataGridView.ClearSelection()

If you don't want even the first row/cell to appear selected, you can set the CurrentCell property to Nothing/null, which will temporarily hide the focus rectangle until the control receives focus again:

myDataGridView.CurrentCell = Nothing

To determine when the user has clicked on a blank part of the DataGridView, you're going to have to handle its MouseUp event. In that event, you can HitTest the click location and watch for this to indicate HitTestInfo.Nowhere. For example:

Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
    ''# See if the left mouse button was clicked
    If e.Button = MouseButtons.Left Then
        ''# Check the HitTest information for this click location
        If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
            myDataGridView.ClearSelection()
            myDataGridView.CurrentCell = Nothing
        End If
    End If
End Sub

Of course, you could also subclass the existing DataGridView control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp method similar to the way shown above. I also like to provide a public DeselectAll method for convenience that both calls the ClearSelection method and sets the CurrentCell property to Nothing.

(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)

enable or disable checkbox in html

According the W3Schools you might use JavaScript for disabled checkbox.

<!-- Checkbox who determine if the other checkbox must be disabled -->
<input type="checkbox" id="checkboxDetermine">
<!-- The other checkbox conditionned by the first checkbox -->
<input type="checkbox" id="checkboxConditioned">
<!-- JS Script -->
<script type="text/javascript">
    // Get your checkbox who determine the condition
    var determine = document.getElementById("checkboxDetermine");
    // Make a function who disabled or enabled your conditioned checkbox
    var disableCheckboxConditioned = function () {
        if(determine.checked) {
            document.getElementById("checkboxConditioned").disabled = true;
        }
        else {
            document.getElementById("checkboxConditioned").disabled = false;
        }
    }
    // On click active your function
    determine.onclick = disableCheckboxConditioned;
    disableCheckboxConditioned();
</script>

You can see the demo working here : http://jsfiddle.net/antoinesubit/vptk0nh6/

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

Also, you can use event.preventDefault inside onclick attribute.

<a href="#" onclick="event.preventDefault(); doSmth();">doSmth</a>

No need to write exstra click event.

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Android: Remove all the previous activities from the back stack

Try this it will work:

Intent logout_intent = new Intent(DashboardActivity.this, LoginActivity.class);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(logout_intent);
finish();

jQuery delete confirmation box

$(document).ready(function(){
  $(".del").click(function(){
    if (!confirm("Do you want to delete")){
      return false;
    }
  });
});

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

Make an image follow mouse pointer

Here's my code (not optimized but a full working example):

<head>
<style>
#divtoshow {position:absolute;display:none;color:white;background-color:black}
#onme {width:150px;height:80px;background-color:yellow;cursor:pointer}
</style>
<script type="text/javascript">
var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
var offX = 15;          // X offset from mouse position
var offY = 15;          // Y offset from mouse position

function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}

function follow(evt) {
    var obj = document.getElementById(divName).style;
    obj.left = (parseInt(mouseX(evt))+offX) + 'px';
    obj.top = (parseInt(mouseY(evt))+offY) + 'px'; 
    }
document.onmousemove = follow;
</script>
</head>
<body>
<div id="divtoshow">test</div>
<br><br>
<div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>Mouse over this</div>
</body>

how to fetch array keys with jQuery?

I use something like this function I created...

Object.getKeys = function(obj, add) {
    if(obj === undefined || obj === null) {
        return undefined;
    }
    var keys = [];
    if(add !== undefined) {
        keys = jQuery.merge(keys, add);
    }
    for(key in obj) {
        if(obj.hasOwnProperty(key)) {
                keys.push(key);
        }
    }
    return keys;
};

I think you could set obj to self or something better in the first test. It seems sometimes I'm checking if it's empty too so I did it that way. Also I don't think {} is Object.* or at least there's a problem finding the function getKeys on the Object that way. Maybe you're suppose to put prototype first, but that seems to cause a conflict with GreenSock etc.

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

I had a related problem, but Raghuram's answer helped. (I don't have enough reputation yet to vote his answer up). I'm using Maven bundled with NetBeans, and was getting the same "...was cached in the local repository, resolution will not be reattempted until the update interval of nexus has elapsed or updates are forced -> [Help 1]" error.

To fix this I added <updatePolicy>always</updatePolicy> to my settings file (C:\Program Files\NetBeans 7.0\java\maven\conf\settings.xml)

<profile>
  <id>nexus</id>
  <!--Enable snapshots for the built in central repo to direct -->
  <!--all requests to nexus via the mirror -->
  <repositories>
    <repository>
      <id>central</id>
      <url>http://central</url>
      <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
      <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
    </repository>
  </repositories>
 <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <url>http://central</url>
      <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
      <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
    </pluginRepository>
  </pluginRepositories>
</profile>

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

I think we should sent in this format

var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});

Its already mentioned in Pass array to mvc Action via AJAX

It worked for me

Method to get all files within folder and subfolders that will return a list

I am not sure of why you're adding the strings to files, which is declared as a field rather than a temporary variable. You could change the signature of DirSearch to:

private List<string> DirSearch(string sDir)

And, after the catch block, add:

return files;

Alternatively, you could create a temporary variable inside of your method and return it, which seems to me the approach you might desire. Otherwise, each time you call that method, the newly found strings will be added to the same list as before and you'll have duplicates.

Python reading from a file and saving to utf-8

You can also get through it by the code below:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()

Unix: How to delete files listed in a file

Assuming that the list of files is in the file 1.txt, then do:

xargs rm -r <1.txt

The -r option causes recursion into any directories named in 1.txt.

If any files are read-only, use the -f option to force the deletion:

xargs rm -rf <1.txt

Be cautious with input to any tool that does programmatic deletions. Make certain that the files named in the input file are really to be deleted. Be especially careful about seemingly simple typos. For example, if you enter a space between a file and its suffix, it will appear to be two separate file names:

file .txt

is actually two separate files: file and .txt.

This may not seem so dangerous, but if the typo is something like this:

myoldfiles *

Then instead of deleting all files that begin with myoldfiles, you'll end up deleting myoldfiles and all non-dot-files and directories in the current directory. Probably not what you wanted.

Set language for syntax highlighting in Visual Studio Code

Syntax Highlighting for custom file extension

Any custom file extension can be associated with standard syntax highlighting with custom files association in User Settings as follows.

Changing File Association settings for permanent Syntax Highlighting

Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in Select Language Mode box (without changing file association settings)

Installing new Syntax Package

If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.

You can further reproduce the above steps to map the file extensions with the new syntax package.

Get a list of URLs from a site

Write a spider which reads in every html from disk and outputs every "href" attribute of an "a" element (can be done with a parser). Keep in mind which links belong to a certain page (this is common task for a MultiMap datastructre). After this you can produce a mapping file which acts as the input for the 404 handler.

How can we programmatically detect which iOS version is device running on?

Marek Sebera's is great most of the time, but if you're like me and find that you need to check the iOS version frequently, you don't want to constantly run a macro in memory because you'll experience a very slight slowdown, especially on older devices.

Instead, you want to compute the iOS version as a float once and store it somewhere. In my case, I have a GlobalVariables singleton class that I use to check the iOS version in my code using code like this:

if ([GlobalVariables sharedVariables].iOSVersion >= 6.0f) {
    // do something if iOS is 6.0 or greater
}

To enable this functionality in your app, use this code (for iOS 5+ using ARC):

GlobalVariables.h:

@interface GlobalVariables : NSObject

@property (nonatomic) CGFloat iOSVersion;

    + (GlobalVariables *)sharedVariables;

@end

GlobalVariables.m:

@implementation GlobalVariables

@synthesize iOSVersion;

+ (GlobalVariables *)sharedVariables {
    // set up the global variables as a static object
    static GlobalVariables *globalVariables = nil;
    // check if global variables exist
    if (globalVariables == nil) {
        // if no, create the global variables class
        globalVariables = [[GlobalVariables alloc] init];
        // get system version
        NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
        // separate system version by periods
        NSArray *systemVersionComponents = [systemVersion componentsSeparatedByString:@"."];
        // set ios version
        globalVariables.iOSVersion = [[NSString stringWithFormat:@"%01d.%02d%02d", \
                                       systemVersionComponents.count < 1 ? 0 : \
                                       [[systemVersionComponents objectAtIndex:0] integerValue], \
                                       systemVersionComponents.count < 2 ? 0 : \
                                       [[systemVersionComponents objectAtIndex:1] integerValue], \
                                       systemVersionComponents.count < 3 ? 0 : \
                                       [[systemVersionComponents objectAtIndex:2] integerValue] \
                                       ] floatValue];
    }
    // return singleton instance
    return globalVariables;
}

@end

Now you're able to easily check the iOS version without running macros constantly. Note in particular how I converted the [[UIDevice currentDevice] systemVersion] NSString to a CGFloat that is constantly accessible without using any of the improper methods many have already pointed out on this page. My approach assumes the version string is in the format n.nn.nn (allowing for later bits to be missing) and works for iOS5+. In testing, this approach runs much faster than constantly running the macro.

Hope this helps anyone experiencing the issue I had!

phpinfo() - is there an easy way for seeing it?

If you have php installed on your local machine try:

$ php -a
Interactive shell

php > phpinfo();

How to parse JSON without JSON.NET library?

You can use DataContractJsonSerializer. See this link for more details.

Android Studio - No JVM Installation found

My JAVA_HOME was pointing to c:/jre directly. So I changed it to C:/java/jre because it was confused to pick up which one to use, so I changed it to the specific one and it works for me. Note: It is better to have only one JRE install on your machine

How do I load an HTML page in a <div> using JavaScript?

This is usually needed when you want to include header.php or whatever page.

In Java it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Java function in script tag.

In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php I.e convert the php include function to Java function in script tag and place all your content in that included file.

.NET obfuscation tools/strategy

SmartAssembly is great,I was used in most of my projects

jQuery: How to get the HTTP status code from within the $.ajax.error method?

use

   statusCode: {
    404: function() {
      alert('page not found');
    }
  }

-

$.ajax({
    type: 'POST',
    url: '/controller/action',
    data: $form.serialize(),
    success: function(data){
        alert('horray! 200 status code!');
    },
    statusCode: {
    404: function() {
      alert('page not found');
    },

    400: function() {
       alert('bad request');
   }
  }

});

Find the index of a dict within a list, by matching the dict's value

lst = [{'id':'1234','name':'Jason'}, {'id':'2345','name':'Tom'}, {'id':'3456','name':'Art'}]

tom_index = next((index for (index, d) in enumerate(lst) if d["name"] == "Tom"), None)
# 1

If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get operations would be O(1) time. An idea:

def build_dict(seq, key):
    return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))

info_by_name = build_dict(lst, key="name")
tom_info = info_by_name.get("Tom")
# {'index': 1, 'id': '2345', 'name': 'Tom'}

How to check if the URL contains a given string?

Try this:

<script type="text/javascript">             
    $(document).ready
    (
        function () 
        { 
            var regExp = /franky/g;
            var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
            if(regExp.test(testString)) // This doesn't work, any suggestions.                 
            {                      
                alert("your url contains the name franky");                 
            }             
        }
    );         
</script> 

The network path was not found

This is probably related to your database connection string or something like that.

I just solved this exception right now. What was happening is that I was using a connection string intended to be used when debugging in a different machine (the server).

I commented the wrong connection string in Web.config and uncommented the right one. Now I'm back in business... this is something I forget to look at after sometime not working in a given solution. ;)

SQL Server Group By Month

DECLARE @start [datetime] = 2010/4/1;

Should be...

DECLARE @start [datetime] = '2010-04-01';

The one you have is dividing 2010 by 4, then by 1, then converting to a date. Which is the 57.5th day from 1900-01-01.

Try SELECT @start after your initialisation to check if this is correct.

C# listView, how do I add items to columns 2, 3 and 4 etc?

There are several ways to do it, but here is one solution (for 4 columns).

string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);

And a more verbose way is here:

ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");

ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");

ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");

ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});

How can I do DNS lookups in Python, including referring to /etc/hosts?

list( map( lambda x: x[4][0], socket.getaddrinfo( \
     'www.example.com.',22,type=socket.SOCK_STREAM)))

gives you a list of the addresses for www.example.com. (ipv4 and ipv6)

How can I build a recursive function in python?

I'm wondering whether you meant "recursive". Here is a simple example of a recursive function to compute the factorial function:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

The two key elements of a recursive algorithm are:

  • The termination condition: n == 0
  • The reduction step where the function calls itself with a smaller number each time: factorial(n - 1)

Creating a system overlay window (always on top)

This might be a stupid solution. But it works. If you can improve it, please let me know.

OnCreate of your Service: I have used WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH flag. This is the only change in service.

@Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();
        mView = new HUDView(this);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.RIGHT | Gravity.TOP;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.addView(mView, params);
    }

Now, you will start getting each and every click event. So, you need to rectify in your event handler.

In your ViewGroup touch event

@Override
public boolean onTouchEvent(MotionEvent event) {

    // ATTENTION: GET THE X,Y OF EVENT FROM THE PARAMETER
    // THEN CHECK IF THAT IS INSIDE YOUR DESIRED AREA


    Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();
    return true;
}

Also you may need to add this permission to your manifest:

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

MS Excel showing the formula in a cell instead of the resulting value

I had the same problem and solved with below:

Range("A").Formula = Trim(CStr("the formula"))

How do I pass variables and data from PHP to JavaScript?

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best, because your server side and client side scripts are completely separate.

Pros

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

Cons

  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 *
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); // In the end, you need to echo the result.
                      // All data should be json_encode()d.

                      // You can json_encode() any value in PHP, arrays, strings,
                      //even objects.

index.php (or whatever the actual page is named like)

<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        // This is where you handle what to do with the response.
        // The actual data is found on this.responseText
        alert(this.responseText); // Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

Some more reading material

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Pros

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.

Cons

  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

index.php

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

3. Echo the data directly to JavaScript

This is probably the easiest to understand.

Pros

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.

Cons

  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

Implementation is relatively straightforward:

<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->

Good luck!

Extracting text from HTML file using Python

Another example using BeautifulSoup4 in Python 2.7.9+

includes:

import urllib2
from bs4 import BeautifulSoup

Code:

def read_website_to_text(url):
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page, 'html.parser')
    for script in soup(["script", "style"]):
        script.extract() 
    text = soup.get_text()
    lines = (line.strip() for line in text.splitlines())
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    text = '\n'.join(chunk for chunk in chunks if chunk)
    return str(text.encode('utf-8'))

Explained:

Read in the url data as html (using BeautifulSoup), remove all script and style elements, and also get just the text using .get_text(). Break into lines and remove leading and trailing space on each, then break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")). Then using text = '\n'.join, drop blank lines, finally return as sanctioned utf-8.

Notes:

Find which rows have different values for a given column in Teradata SQL

Personally, I would print them to a file using Perl or Python in the format

<COL_NAME>:  <COL_VAL>

for each row so that the file has as many lines as there are columns. Then I'd do a diff between the two files, assuming you are on Unix or compare them using some equivalent utilty on another OS. If you have multiple recordsets (i.e. more than one row), I would prepend to each file row and then the file would have NUM_DB_ROWS * NUM_COLS lines

Google Maps API warning: NoApiKeys

I had the same problem and I found out that if you add the URL param ?v=3 you won't get the warning message anymore:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>

Reproduction online

As pointed out in the comments by @Zia Ul Rehman Mughal

Turns out specifying this means you are referring to old frozen version 3.0 not the latest version. Frozen old versions are not updated with bug fixes or anything. But this is good to mention though. https://developers.google.com/maps/documentation/javascript/versions#the-frozen-version

Update 07-Jun-2016

This solution doesn't work anymore.

how to convert long date value to mm/dd/yyyy format

Refer Below code which give the date in String form.

import java.text.SimpleDateFormat;
import java.util.Date;



public class Test{

    public static void main(String[] args) {
        long val = 1346524199000l;
        Date date=new Date(val);
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        String dateText = df2.format(date);
        System.out.println(dateText);
    }
}

xcode library not found

In XCode 10.1, I had to set "Library Search Paths" to something like $(PROJECT_DIR)/.../path/to/your/library

Difference between the Apache HTTP Server and Apache Tomcat?

Apache Tomcat is used to deploy your Java Servlets and JSPs. So in your Java project you can build your WAR (short for Web ARchive) file, and just drop it in the deploy directory in Tomcat.

So basically Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies.

Tomcat includes Catalina, which is a servlet container. A servlet, at the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (HttpServlet), which is then compiled to .class files by the server and executed by the Java virtual machine.

What is the difference between lower bound and tight bound?

The phrases minimum time and maximum time are a bit misleading here. When we talk about big O notations, it's not the actual time we are interested in, it is how the time increases when our input size gets bigger. And it's usually the average or worst case time we are talking about, not best case, which usually is not meaningful in solving our problems.

Using the array search in the accepted answer to the other question as an example. The time it takes to find a particular number in list of size n is n/2 * some_constant in average. If you treat it as a function f(n) = n/2*some_constant, it increases no faster than g(n) = n, in the sense as given by Charlie. Also, it increases no slower than g(n) either. Hence, g(n) is actually both an upper bound and a lower bound of f(n) in Big-O notation, so the complexity of linear search is exactly n, meaning that it is Theta(n).

In this regard, the explanation in the accepted answer to the other question is not entirely correct, which claims that O(n) is upper bound because the algorithm can run in constant time for some inputs (this is the best case I mentioned above, which is not really what we want to know about the running time).

What does the NS prefix mean?

Bill Bumgarner aka @bbum, who should know, posted on the CocoaBuilder mailing list in 2005:

Sun entered the picture a bit after the NS prefix had come into play. The NS prefix came about in public APIs during the move from NeXTSTEP 3.0 to NeXTSTEP 4.0 (also known as OpenStep). Prior to 4.0, a handful of symbols used the NX prefix, but most classes provided by the system libraries were not prefixed at all -- List, Hashtable, View, etc...

It seems that everyone agrees that the prefix NX (for NeXT) was used until 1993/1994, and Apple's docs say:

The official OpenStep API, published in September of 1994, was the first to split the API between Foundation and Application Kit and the first to use the “NS” prefix.

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

How to do SQL Like % in Linq?

I'm assuming you're using Linq-to-SQL* (see note below). If so, use string.Contains, string.StartsWith, and string.EndsWith to generate SQL that use the SQL LIKE operator.

from o in dc.Organization
join oh in dc.OrganizationsHierarchy on o.Id equals oh.OrganizationsId
where oh.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

or

from o in dc.Organization
where o.OrganizationsHierarchy.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

Note: * = if you are using the ADO.Net Entity Framework (EF / L2E) in .net 3.5, be aware that it will not do the same translation as Linq-to-SQL. Although L2S does a proper translation, L2E v1 (3.5) will translate into a t-sql expression that will force a full table scan on the table you're querying unless there is another better discriminator in your where clause or join filters.
Update: This is fixed in EF/L2E v4 (.net 4.0), so it will generate a SQL LIKE just like L2S does.

Error Code: 1406. Data too long for column - MySQL

I think that switching off the STRICT mode is not a good option because the app can start losing the data entered by users.

If you receive values for the TESTcol from an app you could add model validation, like in Rails

validates :TESTcol, length: { maximum: 45 }

If you manipulate with values in SQL script you could truncate the string with the SUBSTRING command

INSERT INTO TEST
VALUES
(
    1,
    SUBSTRING('Vikas Kumar Gupta Kratika Shukla Kritika Shukla', 0, 45)
);

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

how to set textbox value in jquery

I would like to point out to you that .val() also works with selects to select the current selected value.

Count number of objects in list

Let's create an empty list (not required, but good to know):

> mylist <- vector(mode="list")

Let's put some stuff in it - 3 components/indexes/tags (whatever you want to call it) each with differing amounts of elements:

> mylist <- list(record1=c(1:10),record2=c(1:5),record3=c(1:2))

If you are interested in just the number of components in a list use:

> length(mylist)
[1] 3

If you are interested in the length of elements in a specific component of a list use: (both reference the same component here)

length(mylist[[1]])
[1] 10
length(mylist[["record1"]]
[1] 10

If you are interested in the length of all elements in all components of the list use:

> sum(sapply(mylist,length))
[1] 17

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

So here is the solution for this:

I check port 80 used by Skype, after that I changes port to 81 and also along with that somewhere i read this error may be because of SSL Port then I changed SSL port to 444. However this got resolved easily.

One most important thing to notice here, all the port changes should be done inside config files, for http port change: httpd.conf for SSL httpd-ssl.conf. Otherwise changes will not replicate to Apache, Sometime PC reboot is also required.

Edit: Make Apache use port 80 and make Skype communicate on other Port

For those who are struggling with Skype, want to change its port and to make Apache to use port 80.

No need to Re-Install, Here is simply how to change Skype Port

Goto: Tools > Options > Advanced > Connection

There you need to uncheck Use port 80 and 443 as alternative for incoming connections.

That's it, here is screen shot of it.

Changing Skype Port

Open new popup window without address bars in firefox & IE

Check the mozilla documentation on window.open. The window features ("directory=...,...,height=350") etc. arguments should be a string:

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

Try if that works in your browsers. Note that some of the features might be overridden by user preferences, such as "location" (see doc.)

How to pass params with history.push/Link/Redirect in react-router v4?

Add on info to get query parameters.

const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');

For more info about URLSearchParams check this link URLSearchParams

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

If you're using more than one argument it has to be in a tuple (note the extra parentheses):

'%s in %s' % (unicode(self.author),  unicode(self.publication))

As EOL points out, the unicode() function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to explicitly pass the encoding:

'%s in %s' % (unicode(self.author,'utf-8'),  unicode(self.publication('utf-8')))

And as of Python 3.0, it's preferred to use the str.format() syntax instead:

'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))

SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

ON a.userid = b.sourceid AND a.listid = b.destinationid;

Apache VirtualHost 403 Forbidden

I had this issue on Arch Linux too... it costs me some time but I'm happy now that I found my mistake:

My directory with the .html files where in my account.
I set everything on r+x but I still got the 403 error.
Than I went completely back and tried to set my home-directory to execute which solved my problem.

How to access form methods and controls from a class in C#?

JUST YOU CAN SEND FORM TO CLASS LIKE THIS

Class1 excell = new Class1 (); //you must declare this in form as you want to control

excel.get_data_from_excel(this); // And create instance for class and sen this form to another class

INSIDE CLASS AS YOU CREATE CLASS1

class Class1
{
    public void get_data_from_excel (Form1 form) //you getting the form here and you can control as you want
    {
        form.ComboBox1.text = "try it"; //you can chance Form1 UI elements inside the class now
    }
}

IMPORTANT : But you must not forgat you have declare modifier form properties as PUBLIC and you can access other wise you can not see the control in form from class

Jquery change background color

try putting a delay on the last color fade.

$("p#44.test").delay(3000).css("background-color","red");

What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!

Cron and virtualenv

If you're on python and using a Conda Virtual Environment where your python script contains the shebang #!/usr/bin/env python the following works:

* * * * * cd /home/user/project && /home/user/anaconda3/envs/envname/bin/python script.py 2>&1

Additionally, if you want to capture any outputs in your script (e.g. print, errors, etc) you can use the following:

* * * * * cd /home/user/project && /home/user/anaconda3/envs/envname/bin/python script.py >> /home/user/folder/script_name.log 2>&1

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

Can an AWS Lambda function call another

I found a way using the aws-sdk.

var aws = require('aws-sdk');
var lambda = new aws.Lambda({
  region: 'us-west-2' //change to your region
});

lambda.invoke({
  FunctionName: 'name_of_your_lambda_function',
  Payload: JSON.stringify(event, null, 2) // pass params
}, function(error, data) {
  if (error) {
    context.done('error', error);
  }
  if(data.Payload){
   context.succeed(data.Payload)
  }
});

You can find the doc here: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html

How to deal with http status codes other than 200 in Angular 2

Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs for the same like this way

import {Observable} from 'rxjs/Rx';

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status === 500) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 400) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 409) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 406) {
                    return Observable.throw(new Error(error.status));
                }
            });
    }

also you can handel error (with err block) that is throw by catch block while .map function,

like this -

...
.subscribe(res=>{....}
           err => {//handel here});

Update

as required for any status without checking particluar one you can try this: -

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status < 400 ||  error.status ===500) {
                    return Observable.throw(new Error(error.status));
                }
            })
            .subscribe(res => {...},
                       err => {console.log(err)} );

Python-Requests close http connection

On Requests 1.X, the connection is available on the response object:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json",
                  data={'track': toTrack}, auth=('username', 'passwd'))

r.connection.close()

How to check if file already exists in the folder

Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"

Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.

If System.IO.File.Exists(SavePath) Then
   'The file exists
Else
    'the file doesn't exist
End If

Execute SQL script from command line

If you want to run the script file then use below in cmd

sqlcmd -U user -P pass  -S servername -d databasename -i "G:\Hiren\Lab_Prodution.sql"

Get last 3 characters of string

Many ways this can be achieved.

Simple approach should be taking Substring of an input string.

var result = input.Substring(input.Length - 3);

Another approach using Regular Expression to extract last 3 characters.

var result = Regex.Match(input,@"(.{3})\s*$");

Working Demo

How to check all versions of python installed on osx and centos

Find out which version of Python is installed by issuing the command python --version: $ python --version Python 2.7.10

If you see something like this, Python 2.7 is your default version. You can also see if you have Python 3 installed:

$ python3 --version
Python 3.7.2

If you also want to know the path where it is installed, you can issue the command "which" with python and python3:

$ which python
/usr/bin/python

$ which python3
/usr/local/bin/python3

inline if statement java, why is not working

cond? statementA: statementB

Equals to:

if (cond)
    statementA
else
    statementB

For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

Log4Net configuring log level

If you would like to perform it dynamically try this:

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;
using NUnit.Framework;

namespace ExampleConsoleApplication
{
  enum DebugLevel : int
  { 
    Fatal_Msgs = 0 , 
    Fatal_Error_Msgs = 1 , 
    Fatal_Error_Warn_Msgs = 2 , 
    Fatal_Error_Warn_Info_Msgs = 3 ,
    Fatal_Error_Warn_Info_Debug_Msgs = 4 
  }

  class TestClass
  {
    private static readonly ILog logger = LogManager.GetLogger(typeof(TestClass));

    static void Main ( string[] args )
    {
      TestClass objTestClass = new TestClass ();

      Console.WriteLine ( " START " );

      int shouldLog = 4; //CHANGE THIS FROM 0 TO 4 integer to check the functionality of the example
      //0 -- prints only FATAL messages 
      //1 -- prints FATAL and ERROR messages 
      //2 -- prints FATAL , ERROR and WARN messages 
      //3 -- prints FATAL  , ERROR , WARN and INFO messages 
      //4 -- prints FATAL  , ERROR , WARN , INFO and DEBUG messages 

      string srtLogLevel = String.Empty; 
      switch (shouldLog)
      {
        case (int)DebugLevel.Fatal_Msgs :
          srtLogLevel = "FATAL";
          break;
        case (int)DebugLevel.Fatal_Error_Msgs:
          srtLogLevel = "ERROR";
          break;
        case (int)DebugLevel.Fatal_Error_Warn_Msgs :
          srtLogLevel = "WARN";
          break;
        case (int)DebugLevel.Fatal_Error_Warn_Info_Msgs :
          srtLogLevel = "INFO"; 
          break;
        case (int)DebugLevel.Fatal_Error_Warn_Info_Debug_Msgs :
          srtLogLevel = "DEBUG" ;
          break ;
        default:
          srtLogLevel = "FATAL";
          break;
      }

      objTestClass.SetLogingLevel ( srtLogLevel );


      objTestClass.LogSomething ();


      Console.WriteLine ( " END HIT A KEY TO EXIT " );
      Console.ReadLine ();
    } //eof method 

    /// <summary>
    /// Activates debug level 
    /// </summary>
    /// <sourceurl>http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx</sourceurl>
    private void SetLogingLevel ( string strLogLevel )
    {
     string strChecker = "WARN_INFO_DEBUG_ERROR_FATAL" ;

      if (String.IsNullOrEmpty ( strLogLevel ) == true || strChecker.Contains ( strLogLevel ) == false)
        throw new Exception ( " The strLogLevel should be set to WARN , INFO , DEBUG ," );



      log4net.Repository.ILoggerRepository[] repositories = log4net.LogManager.GetAllRepositories ();

      //Configure all loggers to be at the debug level.
      foreach (log4net.Repository.ILoggerRepository repository in repositories)
      {
        repository.Threshold = repository.LevelMap[ strLogLevel ];
        log4net.Repository.Hierarchy.Hierarchy hier = (log4net.Repository.Hierarchy.Hierarchy)repository;
        log4net.Core.ILogger[] loggers = hier.GetCurrentLoggers ();
        foreach (log4net.Core.ILogger logger in loggers)
        {
          ( (log4net.Repository.Hierarchy.Logger)logger ).Level = hier.LevelMap[ strLogLevel ];
        }
      }

      //Configure the root logger.
      log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository ();
      log4net.Repository.Hierarchy.Logger rootLogger = h.Root;
      rootLogger.Level = h.LevelMap[ strLogLevel ];
    }

    private void LogSomething ()
    {
      #region LoggerUsage
      DOMConfigurator.Configure (); //tis configures the logger 
      logger.Debug ( "Here is a debug log." );
      logger.Info ( "... and an Info log." );
      logger.Warn ( "... and a warning." );
      logger.Error ( "... and an error." );
      logger.Fatal ( "... and a fatal error." );
      #endregion LoggerUsage

    }
  } //eof class 
} //eof namespace 

The app config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net"
                 type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    <log4net>
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <param name="File" value="LogTest2.txt" />
            <param name="AppendToFile" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="[Header] \r\n" />
                <param name="Footer" value="[Footer] \r\n" />
                <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
            </layout>
        </appender>

        <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
            <mapping>
                <level value="ERROR" />
                <foreColor value="White" />
                <backColor value="Red, HighIntensity" />
            </mapping>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            </layout>
        </appender>


        <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
            <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <connectionString value="data source=ysg;initial catalog=DBGA_DEV;integrated security=true;persist security info=True;" />
            <commandText value="INSERT INTO [DBGA_DEV].[ga].[tb_Data_Log] ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />

            <parameter>
                <parameterName value="@log_date" />
                <dbType value="DateTime" />
                <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
            </parameter>
            <parameter>
                <parameterName value="@thread" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout" value="%thread" />
            </parameter>
            <parameter>
                <parameterName value="@log_level" />
                <dbType value="String" />
                <size value="50" />
                <layout type="log4net.Layout.PatternLayout" value="%level" />
            </parameter>
            <parameter>
                <parameterName value="@logger" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout" value="%logger" />
            </parameter>
            <parameter>
                <parameterName value="@message" />
                <dbType value="String" />
                <size value="4000" />
                <layout type="log4net.Layout.PatternLayout" value="%messag2e" />
            </parameter>
        </appender>
        <root>
            <level value="INFO" />
            <appender-ref ref="LogFileAppender" />
            <appender-ref ref="AdoNetAppender" />
            <appender-ref ref="ColoredConsoleAppender" />
        </root>
    </log4net>
</configuration>

The references in the csproj file:

<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\Log4Net\log4net-1.2.10\bin\net\2.0\release\log4net.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />

What is the best way to give a C# auto-property an initial value?

When you inline an initial value for a variable it will be done implicitly in the constructor anyway.

I would argue that this syntax was best practice in C# up to 5:

class Person 
{
    public Person()
    {
        //do anything before variable assignment

        //assign initial values
        Name = "Default Name";

        //do anything after variable assignment
    }
    public string Name { get; set; }
}

As this gives you clear control of the order values are assigned.

As of C#6 there is a new way:

public string Name { get; set; } = "Default Name";

How to iterate (keys, values) in JavaScript?

You can do something like this :

dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);

for(var i = 0; i < keys.length;i++){
   //keys[i] for key
   //dictionary[keys[i]] for the value
}

Subtract two variables in Bash

You can use:

((count = FIRSTV - SECONDV))

to avoid invoking a separate process, as per the following transcript:

pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

printf %f with only 2 numbers after the decimal point?

You can use something like this:

printf("%.2f", number);

If you need to use the string for something other than printing out, use the NumberFormat class:

NumberFormat formatter = new DecimalFormatter("#.##");
String s = formatter.format(3.14159265); // Creates a string containing "3.14"

Parse JSON from JQuery.ajax success data

I recommend you use:

var returnedData = JSON.parse(response);

to convert the JSON string (if it is just text) to a JavaScript object.

How do I use sudo to redirect output to a location I don't have permission to write to?

Whenever I have to do something like this I just become root:

# sudo -s
# ls -hal /root/ > /root/test.out
# exit

It's probably not the best way, but it works.

iOS: Compare two dates

According to Apple documentation of NSDate compare:

Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.

- (NSComparisonResult)compare:(NSDate *)anotherDate

Parameters anotherDate

The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.

Return Value

If:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame

The receiver is later in time than anotherDate, NSOrderedDescending

The receiver is earlier in time than anotherDate, NSOrderedAscending

In other words:

if ([date1 compare:date2] == NSOrderedSame) ...

Note that it might be easier in your particular case to read and write this :

if ([date2 isEqualToDate:date2]) ...

See Apple Documentation about this one.

How to get an array of specific "key" in multidimensional array without looping

PHP 5.5+

Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.

PHP 5.3+

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.

PHP < 5.3

Wordpress 3.1+

In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.

PHP < 5.3

If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here

How to Add Date Picker To VBA UserForm

You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.

I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use the quotemeta function:

$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";

print "wee" if ($text_to_search =~ /$search_string/);

How to add anchor tags dynamically to a div in Javascript?

var newA = document.createElement('a');
newA.setAttribute('href',"http://localhost");
newA.innerHTML = "link text";
document.appendChild(newA);

How to setup virtual environment for Python in VS Code?

  1. If your using vs code on mac, it's important to have your venv installed in the same directory as your workspace.

  2. In my case my venv was in a different directory( not in my project workspace) so a simple cut/copy-paste of my venv to the project workspace did the trick.

  3. As soon as your venv is copied to the project workspace, your vs code will pick that up and show a notification giving you an option to select venv as an interpreter.

Converting Integers to Roman Numerals - Java

Alternative solution based on the OP's own solution by utilizing an enum. Additionally, a parser and round-trip tests are included.

public class RomanNumber {
    public enum Digit {
        M(1000, 3),
        CM(900, 1),
        D(500, 1),
        CD(400, 1),
        C(100, 3),
        XC(90, 1),
        L(50, 1),
        XL(40, 1),
        X(10, 3),
        IX(9, 1),
        V(5, 1),
        IV(4, 1),
        I(1, 3);

        public final int value;
        public final String symbol = name();
        public final int maxArity;

        private Digit(int value, int maxArity) {
            this.value = value;
            this.maxArity = maxArity;
        }
    }

    private static final Digit[] DIGITS = Digit.values();

    public static String of(int number) {
        if (number < 1 || 3999 < number) {
            throw new IllegalArgumentException(String.format(
                    "Roman numbers are only defined for numbers between 1 and 3999 (%d was given)",
                    number
            ));
        }

        StringBuilder sb = new StringBuilder();
        for (Digit digit : DIGITS) {
            int value = digit.value;
            String symbol = digit.symbol;

            while (number >= value) {
                sb.append(symbol);
                number -= value;
            }
        }

        return sb.toString();
    }

    public static int parse(String roman) {
        if (roman.isEmpty()) {
            throw new NumberFormatException("The empty string does not comprise a valid Roman number");
        }

        int number = 0;
        int offset = 0;
        for (Digit digit : DIGITS) {
            int value = digit.value;
            int maxArity = digit.maxArity;
            String symbol = digit.symbol;

            for (int i = 0; i < maxArity && roman.startsWith(symbol, offset); i++) {
                number += value;
                offset += symbol.length();
            }
        }
        if (offset != roman.length()) {
            throw new NumberFormatException(String.format(
                    "The string '%s' does not comprise a valid Roman number",
                    roman
            ));
        }
        return number;
    }

    /** TESTS */
    public static void main(String[] args) {

        /* Demonstrating round-trip for all possible inputs. */

        for (int number = 1; number <= 3999; number++) {
            String roman = of(number);
            int parsed = parse(roman);
            if (parsed != number) {
                System.err.format(
                        "ERROR: number: %d, roman: %s, parsed: %d\n",
                        number,
                        roman,
                        parsed
                );
            }
        }

        /* Some illegal inputs. */

        int[] illegalNumbers = { -1, 0, 4000, 4001 };
        for (int illegalNumber : illegalNumbers) {
            try {
                of(illegalNumber);
                System.err.format(
                        "ERROR: Expected failure on number %d\n",
                        illegalNumber
                );
            } catch (IllegalArgumentException e) {
                // Failed as expected.
            }
        }

        String[] illegalRomans = { "MMMM", "CDCD", "IM", "T", "", "VV", "DM" };
        for (String illegalRoman : illegalRomans) {
            try {
                parse(illegalRoman);
                System.err.format(
                        "ERROR: Expected failure on roman %s\n",
                        illegalRoman
                );
            } catch (NumberFormatException e) {
                // Failed as expected.
            }
        }
    }
}

Bootstrap 3 - disable navbar collapse

The following solution worked for me in Bootstrap 3.3.4:

CSS:

/*no collapse*/

.navbar-collapse.collapse.off {
    display: block!important;
}
.navbar-collapse.collapse.off ul {
    margin: 0;
    padding: 0;
}

.navbar-nav.no-collapse>li,
.navbar-nav.no-collapse {
    float: left !important;
}

.navbar-right.no-collapse {
    float: right!important;
}

then add the .no-collapse class to each of the lists and the .off class to the main container. Here is an example written in jade:

nav.navbar.navbar-default.navbar-fixed-top
        .container-fluid
            .collapse.navbar-collapse.off
                ul.nav.navbar-nav.no-collapse
                    li
                        a(href='#' class='glyph')
                            i(class='glyphicon glyphicon-info-sign')
                ul.nav.navbar-nav.navbar-right.no-collapse
                    li.dropdown
                        a.dropdown-toggle(href='#', data-toggle='dropdown' role='button' aria-expanded='false')
                            | Tools
                            span.caret
                        ul.dropdown-menu(role='menu')
                            li
                                a(href='#') Tool #1
                    li
                        a(href='#')
                            | Logout

Issue in installing php7.2-mcrypt

As an alternative, you can install 7.1 version of mcrypt and create a symbolic link to it:

Install php7.1-mcrypt:

sudo apt install php7.1-mcrypt

Create a symbolic link:

sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available

After enabling mcrypt by sudo phpenmod mcrypt, it gets available.

How to remove illegal characters from path and filenames?

I use Linq to clean up filenames. You can easily extend this to check for valid paths as well.

private static string CleanFileName(string fileName)
{
    return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}

Update

Some comments indicate this method is not working for them so I've included a link to a DotNetFiddle snippet so you may validate the method.

https://dotnetfiddle.net/nw1SWY

Does Ruby have a string.startswith("abc") built in method?

If this is for a non-Rails project, I'd use String#index:

"foobar".index("foo") == 0  # => true

What are the different NameID format used for?

1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:

Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:

urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:

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

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

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

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

How to access PHP session variables from jQuery function in a .js file?

Strangely importing directly from $_SESSION not working but have to do this to make it work :

<?php
$phpVar = $_SESSION['var'];
?>

<script>
    var variableValue= '<?php echo $phpVar; ?>';
    var imported = document.createElement('script');
    imported.src = './your/path/to.js';
    document.head.appendChild(imported);
</script>

and in to.js

$(document).ready(function(){
alert(variableValue);
// rest of js file

How to make sure that string is valid JSON using JSON.NET

I'm using this one:

  internal static bool IsValidJson(string data)
  {
     data = data.Trim();
     try
     {
        if (data.StartsWith("{") && data.EndsWith("}"))
        {
           JToken.Parse(data);
        }
        else if (data.StartsWith("[") && data.EndsWith("]"))
        {
           JArray.Parse(data);
        }
        else
        {
           return false;
        }
        return true;
     }
     catch
     {
        return false;
     }
  }

Getting activity from context in android

I used convert Activity

Activity activity = (Activity) context;

Is putting a div inside an anchor ever correct?

There's a DTD for HTML 4 at http://www.w3.org/TR/REC-html40/sgml/dtd.html . This DTD is the machine-processable form of the spec, with the limitation that a DTD governs XML and HTML 4, especially the "transient" flavor, permits a lot of things that are not "legal" XML. Still, I consider it comes close to codifying the intent of the specifiers.

<!ELEMENT A - - (%inline;)* -(A)       -- anchor -->

<!ENTITY % inline "#PCDATA | %fontstyle; | %phrase; | %special; | %formctrl;">

<!ENTITY % fontstyle "TT | I | B | BIG | SMALL">

<!ENTITY % phrase "EM | STRONG | DFN | CODE | SAMP | KBD | VAR | CITE | ABBR | ACRONYM" >

<!ENTITY % special "A | IMG | OBJECT | BR | SCRIPT | MAP | Q | SUB | SUP | SPAN | BDO">

<!ENTITY % formctrl "INPUT | SELECT | TEXTAREA | LABEL | BUTTON">

I would interpret the tags listed in this hierarchy to be the total of tags allowed.

While the spec may say "inline elements," I'm pretty sure it's not intended that you can get around the intent by declaring the display type of a block element to be inline. Inline tags have different semantics no matter how you may abuse them.

On the other hand, I find it intriguing that the inclusion of special seems to allow nesting A elements. There's probably some strong wording in the spec that disallows this even if it's XML-syntactically correct but I won't pursue this further as it's not the topic of the question.

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

if ($_SERVER['REQUEST_METHOD'] == 'POST') is the correct way, you can send a post request without any post data.

How to run a cron job on every Monday, Wednesday and Friday?

This is how I configure it on my server:

0  19  *  *  1,3,5 root bash /home/divo/data/support_files/support_files_inc_backup.sh

The above command will run my script at 19:00 on Monday, Wednesday, and Friday.

NB: For cron entries for day of the week (dow)

0 = Sunday
1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday

Getting 400 bad request error in Jquery Ajax POST

Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object. So the correct version is here:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: JSON.stringify({
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  }),
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

May be it will help someone else.

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
CASE
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

Move the most recent commit(s) to a new branch with Git

Most of the solutions here count the amount of commits you'd like to go back. I think this is an error prone methodology. Counting would require recounting.

You can simply pass the commit hash of the commit you want to be at HEAD or in other words, the commit you'd like to be the last commit via:

(Notice see commit hash)

To avoid this:

1) git checkout master

2) git branch <feature branch> master

3) git reset --hard <commit hash>

4) git push -f origin master

Docker Networking - nginx: [emerg] host not found in upstream

With links there is an order of container startup being enforced. Without links the containers can start in any order (or really all at once).

I think the old setup could have hit the same issue, if the waapi_php_1 container was slow to startup.

I think to get it working, you could create an nginx entrypoint script that polls and waits for the php container to be started and ready.

I'm not sure if nginx has any way to retry the connection to the upstream automatically, but if it does, that would be a better option.

Import .bak file to a database in SQL server

.bak files are database backups. You can restore the backup with the method below:

How to: Restore a Database Backup (SQL Server Management Studio)

What is the __del__ method, How to call it?

The __del__ method (note spelling!) is called when your object is finally destroyed. Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.

If you want to delete your object and thus call the __del__ method use

del obj1

which will delete the object (provided there weren't any other references to it).

I suggest you write a small class like this

class T:
    def __del__(self):
        print "deleted"

And investigate in the python interpreter, eg

>>> a = T()
>>> del a
deleted
>>> a = T()
>>> b = a
>>> del b
>>> del a
deleted
>>> def fn():
...     a = T()
...     print "exiting fn"
...
>>> fn()
exiting fn
deleted
>>>   

Note that jython and ironpython have different rules as to exactly when the object is deleted and __del__ is called. It isn't considered good practice to use __del__ though because of this and the fact that the object and its environment may be in an unknown state when it is called. It isn't absolutely guaranteed __del__ will be called either - the interpreter can exit in various ways without deleteting all objects.