Programs & Examples On #Inter process communicat

Inter-Process Communication (IPC) refers to the exchange of data among multiple threads in one or more processes, either locally or on remote computers connected in a network. The available methods of IPC vary based on the bandwidth and latency of communication between the threads, and the type of data being transmitted. IPC includes subtopics such as message passing, synchronization, shared memory, and remote procedure calls (RPC).

Make HTML5 video poster be same size as video itself

Depending on what browsers you're targeting, you could go for the object-fit property to solve this:

object-fit: cover;

or maybe fill is what you're looking for. Still under consideration for IE.

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

'uint32_t' identifier not found error

I had to run project in VS2010 and I could not introduce any modifications in the code. My solution was to install vS2013 and in VS2010 point VC++ Directories->IncludeDirectories to Program Files(x86)\Microsoft Visual Studio 12.0\VC\include. Then my project compiled without any issues.

Determine the number of NA values in a column

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

When should I use a List vs a LinkedList

The difference between List and LinkedList lies in their underlying implementation. List is array based collection (ArrayList). LinkedList is node-pointer based collection (LinkedListNode). On the API level usage, both of them are pretty much the same since both implement same set of interfaces such as ICollection, IEnumerable, etc.

The key difference comes when performance matter. For example, if you are implementing the list that has heavy "INSERT" operation, LinkedList outperforms List. Since LinkedList can do it in O(1) time, but List may need to expand the size of underlying array. For more information/detail you might want to read up on the algorithmic difference between LinkedList and array data structures. http://en.wikipedia.org/wiki/Linked_list and Array

Hope this help,

Python: convert string from UTF-8 to Latin-1

data="UTF-8 data"
udata=data.decode("utf-8")
data=udata.encode("latin-1","ignore")

Should do it.

how to change directory using Windows command line

Another alternative is pushd, which will automatically switch drives as needed. It also allows you to return to the previous directory via popd:

C:\Temp>pushd D:\some\folder
D:\some\folder>popd
C:\Temp>_

Remove composer

curl -sS https://getcomposer.org/installer | sudo php
sudo mv composer.phar /usr/local/bin/composer
export PATH="$HOME/.composer/vendor/bin:$PATH"

If you have installed by this way simply

Delete composer.phar from where you've putted it.

In this case path will be /usr/local/bin/composer

Note: There is no need to delete the exported path.

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

Change the On/Off text of a toggle button Android

It appears you no longer need toggleButton.setTextOff(textOff); and toggleButton.setTextOn(textOn);. The text for each toggled state will change by merely including the relevant xml characteristics. This will override the default ON/OFF text.

<ToggleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/toggleText"
    android:textOff="ADD TEXT"
    android:textOn="CLOSE TEXT"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"
    android:visibility="gone"/>

"int cannot be dereferenced" in Java

Assuming getItemNumber() returns an int, replace

if (id.equals(list[pos].getItemNumber()))

with

if (id == list[pos].getItemNumber())

Using port number in Windows host file

What you want can be achieved by modifying the hosts file through Fiddler 2 application.

Follow these steps:

  1. Install Fiddler2

  2. Navigate to Fiddler2 menu:- Tools > HOSTS.. (Click to select)

  3. Add a line like this:-

    localhost:8080 www.mydomainname.com

  4. Save the file & then checkout www.mydomainname.com in browser.

Get list of databases from SQL Server

In SQL Server 7, dbid 1 thru 4 are the system dbs.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

This happens because your upstream takes too much to answer the request and NGINX thinks the upstream already failed in processing the request, so it responds with an error. Just include and increase proxy_read_timeout in location config block. Same thing happened to me and I used 1 hour timeout for an internal app at work:

proxy_read_timeout 3600;

With this, NGINX will wait for an hour (3600s) for its upstream to return something.

How can I merge two commits into one if I already started rebase?

Rebase: You Ain't Gonna Need It:

A simpler way for most frequent scenario.

In most cases:

Actually if all you want is just simply combine several recent commits into one but do not need drop, reword and other rebase work.

you can simply do:

git reset --soft "HEAD~n"
  • Assuming ~n is number of commits to softly un-commit (i.e. ~1, ~2,...)

Then, use following command to modify the commit message.

git commit --amend

which is pretty much the same as a long range of squash and one pick.

And it works for n commits but not just two commits as above answer prompted.

How can I strip first and last double quotes?

Remove a determinated string from start and end from a string.

s = '""Hello World""'
s.strip('""')

> 'Hello World'

How to create module-wide variables in Python?

For this, you need to declare the variable as global. However, a global variable is also accessible from outside the module by using module_name.var_name. Add this as the first line of your module:

global __DBNAME__

How to set Default Controller in asp.net MVC 4 & MVC 5

I didnt see this question answered:

How should I setup a default Area when the application starts?

So, here is how you can set up a default Area:

var route = routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    ).DataTokens = new RouteValueDictionary(new { area = "MyArea" });

What size should apple-touch-icon.png be for iPad and iPhone?

I have been developing and designing iOS apps for a while and This is the best iOS design cheat sheet out there!

have fun :)!

this image is from that article :)

Update: For iOS 8+, and the new devices (iPhone 6, 6 Plus, iPad Air) see this updated link.

Meta update: Iphone 6s/6s Plus have the same resolutions as iPhone 6/6 Plus respectively

This is an image from the new version of the article:

iOS 8 and mid 2014 devices info

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Change text from "Submit" on input tag

The value attribute on submit-type <input> elements controls the text displayed.

<input type="submit" class="like" value="Like" />

Add timestamp column with default NOW() for new rows only

You need to add the column with a default of null, then alter the column to have default now().

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP;
ALTER TABLE mytable ALTER COLUMN created_at SET DEFAULT now();

How to remove unused imports from Eclipse

You can direct use the shortcut by pressing Ctrl+Shift+O

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

**Different way to Find Element:**

IEDriver.findElement(By.id("id"));
IEDriver.findElement(By.linkText("linkText"));
IEDriver.findElement(By.xpath("xpath"));

IEDriver.findElement(By.xpath(".//*[@id='id']"));
IEDriver.findElement(By.xpath("//button[contains(.,'button name')]"));
IEDriver.findElement(By.xpath("//a[contains(.,'text name')]"));
IEDriver.findElement(By.xpath("//label[contains(.,'label name')]"));

IEDriver.findElement(By.xpath("//*[contains(text(), 'your text')]");

Check Case Sensitive:
IEDriver.findElement(By.xpath("//*[contains(lower-case(text()),'your text')]");

For exact match: 
IEDriver.findElement(By.xpath("//button[text()='your text']");

**Find NG-Element:**

Xpath == //td[contains(@ng-show,'childsegment.AddLocation')]
CssSelector == .sprite.icon-cancel

How to connect to SQL Server from command prompt with Windows authentication

type sqlplus/"as sysdba" in cmd for connection in cmd prompt

Using C++ base class constructors?

Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used

  B( int v) : A( v )
  {
  }

Javascript Array.sort implementation?

After some more research, it appears, for Mozilla/Firefox, that Array.sort() uses mergesort. See the code here.

How can I create directories recursively?

Here is my implementation for your reference:

def _mkdir_recursive(self, path):
    sub_path = os.path.dirname(path)
    if not os.path.exists(sub_path):
        self._mkdir_recursive(sub_path)
    if not os.path.exists(path):
        os.mkdir(path)

Hope this help!

How to handle Pop-up in Selenium WebDriver using Java

public void Test(){

     WebElement sign = fc.findElement(By.xpath(".//*[@id='login-scroll']/a"));
        sign.click();
        WebElement LoginAsGuest=fc.findElement(By.xpath(".//*[@id='guest-login-option']"));
        LoginAsGuest.click();
        WebElement email_id= fc.findElement(By.xpath(".//*[@id='guestemail']"));
        email_id.sendKeys("[email protected]");
        WebElement ContinueButton=fc.findElement(By.xpath(".//*[@id='contibutton']"));
        ContinueButton.click();

}

How to declare a global variable in React?

Why don't you try using Context?

You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this.context.varname. You only have to specify childContextTypes and getChildContext in the parent component and thereafter you can use/modify this from any component by just specifying contextTypes in the child component.

However, please take a note of this as mentioned in docs:

Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

How to read barcodes with the camera on Android?

With Google Firebase ML Kit's barcode scanning API, you can read data encoded using most standard barcode formats.

https://firebase.google.com/docs/ml-kit/read-barcodes?authuser=0

You can follow this link to read barcodes efficiently.

Where to put default parameter value in C++?

C++ places the default parameter logic in the calling side, this means that if the default value expression cannot be computed from the calling place, then the default value cannot be used.

Other compilation units normally just include the declaration so default value expressions placed in the definition can be used only in the defining compilation unit itself (and after the definition, i.e. after the compiler sees the default value expressions).

The most useful place is in the declaration (.h) so that all users will see it.

Some people like to add the default value expressions in the implementation too (as a comment):

void foo(int x = 42,
         int y = 21);

void foo(int x /* = 42 */,
         int y /* = 21 */)
{
   ...
}

However, this means duplication and will add the possibility of having the comment out of sync with the code (what's worse than uncommented code? code with misleading comments!).

Convert String[] to comma separated string in java

String[] name = {"amit", "rahul", "surya"};


public static String arrayToString(String array[])
{
    if (array.length == 0) return "";
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.length; ++i)
    {
        sb.append(",'").append(array[i]).append("'");
    }
    return sb.substring(1);
}

Changing font size and direction of axes text in ggplot2

Ditto @Drew Steen on the use of theme(). Here are common theme attributes for axis text and titles.

ggplot(mtcars, aes(x = factor(cyl), y = mpg))+
  geom_point()+
  theme(axis.text.x = element_text(color = "grey20", size = 20, angle = 90, hjust = .5, vjust = .5, face = "plain"),
        axis.text.y = element_text(color = "grey20", size = 12, angle = 0, hjust = 1, vjust = 0, face = "plain"),  
        axis.title.x = element_text(color = "grey20", size = 12, angle = 0, hjust = .5, vjust = 0, face = "plain"),
        axis.title.y = element_text(color = "grey20", size = 12, angle = 90, hjust = .5, vjust = .5, face = "plain"))

How to keep form values after post

you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.

What are MVP and MVC and what is the difference?

MVP

MVP stands for Model - View- Presenter. This came to a picture in early 2007 where Microsoft introduced Smart Client windows applications.

A presenter is acting as a supervisory role in MVP which binding View events and business logic from models.

View event binding will be implemented in the Presenter from a view interface.

The view is the initiator for user inputs and then delegates the events to the Presenter and the presenter handles event bindings and gets data from models.

Pros: The view is having only UI not any logics High level of testability

Cons: Bit complex and more work when implementing event bindings

MVC

MVC stands for Model-View-Controller. Controller is responsible for creating models and rendering views with binding models.

Controller is the initiator and it decides which view to render.

Pros: Emphasis on Single Responsibility Principle High level of testability

Cons: Sometimes too much workload for Controllers, if try to render multiple views in same controller.

Connecting PostgreSQL 9.2.1 with Hibernate

This is the hibernate.cfg.xml file to connect postgresql 9.5 and this is help to you basic configuration.

 <?xml version='1.0' encoding='utf-8'?>

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration
>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">password</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.waseem.UserDetails"/>
    </session-factory>
</hibernate-configuration>

Make sure File Location should be under src/main/resources/hibernate.cfg.xml

Is there a way to specify a max height or width for an image?

You could use some CSS and with the idea of kbrimington it should do the trick.

The CSS could be like this.

img {
  width:  75px;
  height: auto;
}

I got it from here: another post

CSS Cell Margin

Try padding-right. You're not allowed to put margin's between cells.

<table>
   <tr>
      <td style="padding-right: 10px;">one</td>
      <td>two</td>
   </tr>
</table>

C++ Convert string (or char*) to wstring (or wchar_t*)

method s2ws works well. Hope helps.

std::wstring s2ws(const std::string& s) {
    std::string curLocale = setlocale(LC_ALL, ""); 
    const char* _Source = s.c_str();
    size_t _Dsize = mbstowcs(NULL, _Source, 0) + 1;
    wchar_t *_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 0, _Dsize);
    mbstowcs(_Dest,_Source,_Dsize);
    std::wstring result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, curLocale.c_str());
    return result;
}

Simple proof that GUID is not unique

Personally, I think the "Big Bang" was caused when two GUIDs collided.

Share application "link" in Android

finally, this code is worked for me to open the email client from android device. try this snippet.

Intent testIntent = new Intent(Intent.ACTION_VIEW);
                    Uri data = Uri.parse("mailto:?subject=" + "Feedback" + "&body=" + "Write Feedback here....." + "&to=" + "[email protected]");
                    testIntent.setData(data);
                    startActivity(testIntent);

Simpler way to create dictionary of separate variables?

In python 3 this is easy

myVariable = 5
for v in locals():
  if id(v) == id("myVariable"):
    print(v, locals()[v])

this will print:

myVariable 5

Get a specific bit from byte

While it's good to read and understand Josh's answer, you'll probably be happier using the class Microsoft provided for this purpose: System.Collections.BitArray It's available in all versions of .NET Framework.

How to rename uploaded file before saving it into a directory?

The move_uploaded_file will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file

Control the size of points in an R scatterplot?

pch=20 returns a symbol sized between "." and 19.

It's a filled symbol (which is probably what you want).

Aside from that, even the base graphics system in R allows a user fine-grained control over symbol size, color, and shape. E.g.,

dfx = data.frame(ev1=1:10, ev2=sample(10:99, 10), ev3=10:1)

with(dfx, symbols(x=ev1, y=ev2, circles=ev3, inches=1/3,
                  ann=F, bg="steelblue2", fg=NULL))

Graph example

How to download a branch with git?

Git clone and cd in the repo name:

$ git clone https://github.com/PabloEzequiel/iOS-AppleWach.git
Cloning into 'iOS-AppleWach'...
$ cd iOS-AppleWach

Switch to the branch (a GitHub page) that I want:

$ git checkout -b gh-pages origin/gh-pages
Branch gh-pages set up to track remote branch gh-pages from origin.
Switched to a new branch 'gh-pages'

And pull the branch:

$ git pull
Already up-to-date.

ls:

$ ls
index.html      params.json     stylesheets

html button to send email

This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...

HTML:

<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):

$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:[email protected]?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.

It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.

HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

How do I avoid the specification of the username and password at every git push?

Just wanted to point out something about the solution said above several times:

git config credential.helper store

You can use any command that requires a password after this. You don't have to push. (you can also pull for instance) After that, you won't need to type in your username / password again.

Validating parameters to a Bash script

#!/bin/sh
die () {
    echo >&2 "$@"
    exit 1
}

[ "$#" -eq 1 ] || die "1 argument required, $# provided"
echo $1 | grep -E -q '^[0-9]+$' || die "Numeric argument required, $1 provided"

while read dir 
do
    [ -d "$dir" ] || die "Directory $dir does not exist"
    rm -rf "$dir"
done <<EOF
~/myfolder1/$1/anotherfolder 
~/myfolder2/$1/yetanotherfolder 
~/myfolder3/$1/thisisafolder
EOF

edit: I missed the part about checking if the directories exist at first, so I added that in, completing the script. Also, have addressed issues raised in comments; fixed the regular expression, switched from == to eq.

This should be a portable, POSIX compliant script as far as I can tell; it doesn't use any bashisms, which is actually important because /bin/sh on Ubuntu is actually dash these days, not bash.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?

Try a software called Access to MySQL.

Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.

  • Wizard interface.
  • Transfer data directly from one server to another.
  • Create a dump file.
  • Select tables to transfer.
  • Select fields to transfer.
  • Transfer password protected databases.
  • Supports both shared security and user-level security.
  • Optional transfer of indexes.
  • Optional transfer of records.
  • Optional transfer of default values in field definitions.
  • Identifies and transfers auto number field types.
  • Command line interface.
  • Easy install, uninstall and upgrade.

See the aforementioned link for a step-by-step tutorial with screenshots.

Parse (split) a string in C++ using string delimiter (standard C++)

Container splitR(const std::string& input, const std::string& delims) {
    Container out;
    size_t delims_len = delims.size();
    auto begIdx = 0;
    auto endIdx = input.find(delims, begIdx);
    if (endIdx == std::string::npos && input.size() != 0) {
        insert_in_container(out, input);
    }
    while (endIdx != std::string::npos) {
        insert_in_container(out, input.substr(begIdx, endIdx - begIdx));
        begIdx = endIdx + delims_len;
        endIdx = input.find(delims, begIdx);
        if (endIdx == std::string::npos) {
            insert_in_container(out, input.substr(begIdx, input.length() - begIdx));
        }
    }
    return out;
}

Remove all child elements of a DOM node in JavaScript

In response to DanMan, Maarten and Matt. Cloning a node, to set the text is indeed a viable way in my results.

// @param {node} node
// @return {node} empty node
function removeAllChildrenFromNode (node) {
  var shell;
  // do not copy the contents
  shell = node.cloneNode(false);

  if (node.parentNode) {
    node.parentNode.replaceChild(shell, node);
  }

  return shell;
}

// use as such
var myNode = document.getElementById('foo');
myNode = removeAllChildrenFromNode( myNode );

Also this works for nodes not in the dom which return null when trying to access the parentNode. In addition, if you need to be safe a node is empty before adding content this is really helpful. Consider the use case underneath.

// @param {node} node
// @param {string|html} content
// @return {node} node with content only
function refreshContent (node, content) {
  var shell;
  // do not copy the contents
  shell = node.cloneNode(false);

  // use innerHTML or you preffered method
  // depending on what you need
  shell.innerHTML( content );

  if (node.parentNode) {
    node.parentNode.replaceChild(shell, node);
  }

  return shell;
}

// use as such
var myNode = document.getElementById('foo');
myNode = refreshContent( myNode );

I find this method very useful when replacing a string inside an element, if you are not sure what the node will contain, instead of worrying how to clean up the mess, start out fresh.

Exception from HRESULT: 0x800A03EC Error

Still seeing this error in 2020. As was stated by stt106 above, there are many, many possible causes. In my case, it was during automated insertion of data into a worksheet, and a date had been incorrectly typed in as year 1019 instead of 2019. Since i was inserting using a data array, it was difficult to find the problem until I switched to row-by-row insertion.

This was my old code, which "hid" the problem data.

    Dim DataArray(MyDT.Rows.Count + 1, MyDT.Columns.Count + 1) As Object
    Try
        XL.Range(XL.Cells(2, 1), XL.Cells(MyDT.Rows.Count, MyDT.Columns.Count)).Value = DataArray
    Catch ex As Exception
        MsgBox("Fatal Error in F100 at 1270: " & ex.Message)
        End
    End Try

When inserting the same data by single rows at a time, it stopped with the same error but now it was easy to find the offending data.

I am adding this information so many years later, in case this helps someone else.

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

This is often caused by an attempt to process a null object. An example, trying to empty a Bindable list that is null will trigger the exception:

public class MyViewModel {
    [BindableProperty]
    public virtual IList<Products> ProductsList{ get; set; }

    public MyViewModel ()
    {
        ProductsList.Clear(); // here is the problem
    }
}

This could easily be fixed by checking for null:

if (ProductsList!= null) ProductsList.Clear();

Android toolbar center title and custom font

A very quick and easy way to set a custom font is to use a custom titleTextAppearance with a fontFamily:

Add to styles.xml:

<style name="ToolbarTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#FF202230</item>
    <item name="android:fontFamily">@font/varela_round_regular</item>
</style>

In your res folder create a font folder (Ex: varela_round_regular.ttf)

Read the official guide to find out more https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

Python Key Error=0 - Can't find Dict error in code

The error you're getting is that self.adj doesn't already have a key 0. You're trying to append to a list that doesn't exist yet.

Consider using a defaultdict instead, replacing this line (in __init__):

self.adj = {}

with this:

self.adj = defaultdict(list)

You'll need to import at the top:

from collections import defaultdict

Now rather than raise a KeyError, self.adj[0].append(edge) will create a list automatically to append to.

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

Redirecting to URL in Flask

its pretty easy if u just want to redirect to a url without any status codes or anything like that u can simple say

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def redirect_to_link():
    # return redirect method, NOTE: replace google.com with the link u want
    return redirect('https://google.com')

here is the link to the Flask Docs for more explanation

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

Predefined type 'System.ValueTuple´2´ is not defined or imported

For .NET 4.6.2 or lower, .NET Core 1.x, and .NET Standard 1.x you need to install the NuGet package System.ValueTuple:

Install-Package "System.ValueTuple"

Or using a package reference in VS 2017:

<PackageReference Include="System.ValueTuple" Version="4.4.0" />

.NET Framework 4.7, .NET Core 2.0, and .NET Standard 2.0 include these types.

Build Eclipse Java Project from Command Line

After 27 years, I too, am uncomfortable developing in an IDE. I tried these suggestions (above) - and probably just didn't follow everything right -- so I did a web-search and found what worked for me at 'http://incise.org/android-development-on-the-command-line.html'.

The answer seemed to be a combination of all the answers above (please tell me if I'm wrong and accept my apologies if so).

As mentioned above, eclipse/adt does not create the necessary ant files. In order to compile without eclipse IDE (and without creating ant scripts):

1) Generate build.xml in your top level directory:

android list targets  (to get target id used below)

android update project --target target_id --name project_name  --path top_level_directory

   ** my sample project had a target_id of 1 and a project name of 't1', and 
   I am building from the top level directory of project
   my command line looks like android update project --target 1 --name t1 --path `pwd`

2) Next I compile the project. I was a little confused by the request to not use 'ant'. Hopefully -- requester meant that he didn't want to write any ant scripts. I say this because the next step is to compile the application using ant

 ant target

    this confused me a little bit, because i thought they were talking about the
    android device, but they're not.  It's the mode  (debug/release)
    my command line looks like  ant debug

3) To install the apk onto the device I had to use ant again:

 ant target install

    ** my command line looked like  ant debug install

4) To run the project on my android phone I use adb.

 adb shell 'am start -n your.project.name/.activity'

    ** Again there was some confusion as to what exactly I had to use for project 
    My command line looked like adb shell 'am start -n com.example.t1/.MainActivity'
    I also found that if you type 'adb shell' you get put to a cli shell interface
    where you can do just about anything from there.

3A) A side note: To view the log from device use:

 adb logcat

3B) A second side note: The link mentioned above also includes instructions for building the entire project from the command.

Hopefully, this will help with the question. I know I was really happy to find anything about this topic here.

jQuery "blinking highlight" effect on div?

For those who do not want to include the whole of jQuery UI, you can use jQuery.pulse.js instead.

To have looping animation of changing opacity, do this:

$('#target').pulse({opacity: 0.8}, {duration : 100, pulses : 5});

It is light (less than 1kb), and allows you to loop any kind of animations.

WebView and HTML5 <video>

I answer this topic just in case someone read it and is interested on the result. It is possible to view a video element (video html5 tag) within a WebView, but I must say I had to deal with it for few days. These are the steps I had to follow so far:

-Find a properly encoded video

-When initializing the WebView, set the JavaScript, Plug-ins the WebViewClient and the WebChromeClient.

url = new String("http://broken-links.com/tests/video/"); 
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebChromeClient(chromeClient);
mWebView.setWebViewClient(wvClient);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl(url);

-Handle the onShowCustomView in the WebChromeClient object.

@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
    super.onShowCustomView(view, callback);
    if (view instanceof FrameLayout){
        FrameLayout frame = (FrameLayout) view;
        if (frame.getFocusedChild() instanceof VideoView){
            VideoView video = (VideoView) frame.getFocusedChild();
            frame.removeView(video);
            a.setContentView(video);
            video.setOnCompletionListener(this);
            video.setOnErrorListener(this);
            video.start();
        }
    }
}

-Handle the onCompletion and the onError events for the video, in order to get back to the web view.

public void onCompletion(MediaPlayer mp) {
    Log.d(TAG, "Video completo");
    a.setContentView(R.layout.main);
    WebView wb = (WebView) a.findViewById(R.id.webview);
    a.initWebView();
}

But now I should say there are still an important issue. I can play it only once. The second time I click on the video dispatcher (either the poster or some play button), it does nothing.

I would also like the video to play inside the WebView frame, instead of opening the Media Player window, but this is for me a secondary issue.

I hope it helps somebody, and I would also thank any comment or suggestion.

Saludos, terrícolas.

Why is Python running my module when I import it, and how do I stop it?

Although you cannot use import without running the code; there is quite a swift way in which you can input your variables; by using numpy.savez, which stores variables as numpy arrays in a .npz file. Afterwards you can load the variables using numpy.load.

See a full description in the scipy documentation

Please note this is only the case for variables and arrays of variable, and not for methods, etc.

getting the X/Y coordinates of a mouse click on an image with jQuery

You can use pageX and pageY to get the position of the mouse in the window. You can also use jQuery's offset to get the position of an element.

So, it should be pageX - offset.left for how far from the left of the image and pageY - offset.top for how far from the top of the image.

Here is an example:

$(document).ready(function() {
  $('img').click(function(e) {
    var offset = $(this).offset();
    alert(e.pageX - offset.left);
    alert(e.pageY - offset.top);
  });
});

I've made a live example here and here is the source.

To calculate how far from the bottom or right, you would have to use jQuery's width and height methods.

How to center an element in the middle of the browser window?

div#wrapper {
    position: absolute;
    top:  50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

Sum of Numbers C++

The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.

jQuery.post( ) .done( ) and success:

From the doc:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

The point it is just an alternative for success callback option, and jqXHR.success() is deprecated.

What is your favorite C programming trick?

Declaring array's of pointer to functions for implementing finite state machines.

int (* fsm[])(void) = { ... }

The most pleasing advantage is that it is simple to force each stimulus/state to check all code paths.

In an embedded system, I'll often map an ISR to point to such a table and revector it as needed (outside the ISR).

How to send a simple email from a Windows batch file?

It works for me, by using double quotes around variables.

I am using batch script to call powershell Send-MailMessage

Batch Script:send_email.bat

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -command 'E:\path\send_email.ps1

Pwershell Script send_email.ps1

Send-MailMessage -From "noreply@$env:computername" -To '<[email protected]>' -Subject 'Blah Blah' -SmtpServer  'smtp.domain.com'  -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "

Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(R.id.imageViewCompass);
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            shortclick();
        }
     });

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        longclick();
        return true;
    }
});

//Then the functions that are called:

 public void shortclick()
{
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();

}

 public void longclick()
{
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();

}

It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

SQL grouping by all the columns

Short answer: no. GROUP BY clauses intrinsically require order to the way they arrange your results. A different order of field groupings would lead to different results.

Specifying a wildcard would leave the statement open to interpretation and unpredictable behaviour.

How can I get the active screen dimensions?

This is a "Center Screen DotNet 4.5 solution", using SystemParameters instead of System.Windows.Forms or My.Compuer.Screen: Since Windows 8 has changed the screen dimension calculation, the only way it works for me looks like that (Taskbar calculation included):

Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    Dim BarWidth As Double = SystemParameters.VirtualScreenWidth - SystemParameters.WorkArea.Width
    Dim BarHeight As Double = SystemParameters.VirtualScreenHeight - SystemParameters.WorkArea.Height
    Me.Left = (SystemParameters.VirtualScreenWidth - Me.ActualWidth - BarWidth) / 2
    Me.Top = (SystemParameters.VirtualScreenHeight - Me.ActualHeight - BarHeight) / 2         
End Sub

Center Screen WPF XAML

How can I echo a newline in a batch file?

echo. Enough said.

If you need it in a single line, use the &. For example,

echo Line 1 & echo. & echo line 3

would output as:

Line 1

line 3

Now, say you want something a bit fancier, ...

set n=^&echo.
echo hello %n% world

Outputs

hello
world

Then just throw in a %n% whenever you want a new line in an echo statement. This is more close to your \n used in various languages.

Breakdown

set n= sets the variable n equal to:

^ Nulls out the next symbol to follow:

& Means to do another command on the same line. We don't care about errorlevel(its an echo statement for crying out loud), so no && is needed.

echo. Continues the echo statement.

All of this works because you can actually create variables that are code, and use them inside of other commands. It is sort of like a ghetto function, since batch is not exactly the most advanced of shell scripting languages. This only works because batch's poor usage of variables, not designating between ints, chars, floats, strings, etc naturally.

If you are crafty, you could get this to work with other things. For example, using it to echo a tab

set t=^&echo.     ::there are spaces up to the double colon

How to check if variable's type matches Type stored in a variable

GetType() exists on every single framework type, because it is defined on the base object type. So, regardless of the type itself, you can use it to return the underlying Type

So, all you need to do is:

u.GetType() == t

Dead simple example of using Multiprocessing Queue, Pool and Locking

Here is an example from my code (for threaded pool, but just change class name and you'll have process pool):

def execute_run(rp): 
   ... do something 

pool = ThreadPoolExecutor(6)
for mat in TESTED_MATERIAL:
    for en in TESTED_ENERGIES:
        for ecut in TESTED_E_CUT:
            rp = RunParams(
                simulations, DEST_DIR,
                PARTICLE, mat, 960, 0.125, ecut, en
            )
            pool.submit(execute_run, rp)
pool.join()

Basically:

  • pool = ThreadPoolExecutor(6) creates a pool for 6 threads
  • Then you have bunch of for's that add tasks to the pool
  • pool.submit(execute_run, rp) adds a task to pool, first arogument is a function called in in a thread/process, rest of the arguments are passed to the called function.
  • pool.join waits until all tasks are done.

Call parent method from child class c#

One way to do this would be to pass the instance of ParentClass to the ChildClass on construction

public ChildClass
{
    private ParentClass parent;

    public ChildClass(ParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Make sure to pass the reference to this when constructing ChildClass inside parent:

if(loadData){

     ChildClass childClass = new ChildClass(this); // here

     childClass.LoadData(this.Datatable);

}

Caveat: This is probably not the best way to organise your classes, but it directly answers your question.

EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass. This is possible with the introduction of an interface, eg:

public interface IParentClass
{
    void UpdateProgressBar();
    int CurrentRow{get; set;}
}

Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:

public ChildClass
{
    private IParentClass parent;

    public ChildClass(IParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Now anything that implements IParentClass can construct an instance of ChildClass and pass this to its constructor.

Iterator invalidation rules

C++11 (Source: Iterator Invalidation Rules (C++0x))


Insertion

Sequence containers

  • vector: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.3.6.5/1]
  • deque: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.3.3.4/1]
  • list: all iterators and references unaffected [23.3.5.4/1]
  • forward_list: all iterators and references unaffected (applies to insert_after) [23.3.4.5/1]
  • array: (n/a)

Associative containers

  • [multi]{set,map}: all iterators and references unaffected [23.2.4/9]

Unsorted associative containers

  • unordered_[multi]{set,map}: all iterators invalidated when rehashing occurs, but references unaffected [23.2.5/8]. Rehashing does not occur if the insertion does not cause the container's size to exceed z * B where z is the maximum load factor and B the current number of buckets. [23.2.5/14]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence containers

  • vector: every iterator and reference at or after the point of erase is invalidated [23.3.6.5/3]
  • deque: erasing the last element invalidates only iterators and references to the erased elements and the past-the-end iterator; erasing the first element invalidates only iterators and references to the erased elements; erasing any other elements invalidates all iterators and references (including the past-the-end iterator) [23.3.3.4/4]
  • list: only the iterators and references to the erased element is invalidated [23.3.5.4/3]
  • forward_list: only the iterators and references to the erased element is invalidated (applies to erase_after) [23.3.4.5/1]
  • array: (n/a)

Associative containers

  • [multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.4/9]

Unordered associative containers

  • unordered_[multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.5/13]

Container adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Resizing

  • vector: as per insert/erase [23.3.6.5/12]
  • deque: as per insert/erase [23.3.3.3/3]
  • list: as per insert/erase [23.3.5.3/1]
  • forward_list: as per insert/erase [23.3.4.5/25]
  • array: (n/a)

Note 1

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.2.1/11]

Note 2

no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [23.2.1/10]

Note 3

Other than the above caveat regarding swap(), it's not clear whether "end" iterators are subject to the above listed per-container rules; you should assume, anyway, that they are.

Note 4

vector and all unordered associative containers support reserve(n) which guarantees that no automatic resizing will occur at least until the size of the container grows to n. Caution should be taken with unordered associative containers because a future proposal will allow the specification of a minimum load factor, which would allow rehashing to occur on insert after enough erase operations reduce the container size below the minimum; the guarantee should be considered potentially void after an erase.

Cannot send a content-body with this verb-type

I had the similar issue using Flurl.Http:

Flurl.Http.FlurlHttpException: Call failed. Cannot send a content-body with this verb-type. GET http://******:8301/api/v1/agents/**** ---> System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.

The problem was I used .WithHeader("Content-Type", "application/json") when creating IFlurlRequest.

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

You might be running an older version of Intel HAXM (or haven't installed it at all). Go to https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager and download/install the latest Intel HAXM package for MAC OS X.

EDIT: according to https://software.intel.com/en-us/forums/topic/506790 you should also make sure that Virtual PC/Parallel/VMWare is not running.

Accurate way to measure execution times of php scripts

You have the right idea, except a more precise timing is available with the microtime() function.

If what is inside the loop is fast, it is possible that the apparent elapsed time will be zero. If so, wrap another loop around the code and call it repeatedly. Be sure to divide the difference by the number of iterations to get a per-once time. I have profiled code which required 10,000,000 iterations to get consistent, reliable timing results.

How can I output a UTF-8 CSV in PHP that Excel will read properly?

To quote a Microsoft support engineer,

Excel for Mac does not currently support UTF-8

Update, 2017: This is true of all versions of Microsoft Excel for Mac before Office 2016. Newer versions (from Office 365) do now support UTF-8.

In order to output UTF-8 content that Excel both on Windows and OS X will be able to successfully read, you will need to do two things:

  1. Make sure that you convert your UTF-8 CSV text to UTF-16LE

    mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
    
  2. Make sure that you add the UTF-16LE byte order mark to the start of the file

    chr(255) . chr(254)
    

The next problem that appears only with Excel on OS X (but not Windows) will be when viewing a CSV file with comma separated values, Excel will render rows only with one row and all of the text along with the commas in the first row.

The way to avoid this is to use tabs as your separated value.

I used this function from the PHP comments (using tabs "\t" instead of commas) and it worked perfectly on OS X and Windows Excel.

Note that to fix an issue with an empty column as the end of a row, that I did have to change the line of code that says:

    $field_cnt = count($fields);

to

    $field_cnt = count($fields)-1;

As some of the other comments on this page say, other spreadsheet apps like OpenOffice Calc, Apple's own Numbers and Google Doc's Spreadsheet have no issues with UTF-8 files with commas.

See the table in this question for what works and doesn't work for Unicode CSV files in Excel


As a side note, I might add that if you are using Composer, you should have a look at adding League\Csv to your requires. League\Csv has a really nice API for building CSV files.

To use League\Csv with this method of creating CSV files, check out this example

How to extract elements from a list using indices in Python?

Bounds checked:

 [a[index] for index in (1,2,5,20) if 0 <= index < len(a)]
 # [11, 12, 15] 

set initial viewcontroller in appdelegate - swift

Try this. For example: You should use UINavigationController as the initial view controller. Then, you can set any view controller as root from the storyboard.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let navigationController = storyboard.instantiateInitialViewController() as UINavigationController
    let rootViewController = storyboard.instantiateViewControllerWithIdentifier("VC") as UIViewController
    navigationController.viewControllers = [rootViewController]
    self.window?.rootViewController = navigationController
    return true
}

See my storyboard screen.

Xcode process launch failed: Security

Alternatively if one does not see "Untrust App Developer" dialog:

Go to your iPhone > Settings > General > Profile > "[email protected]" > Trust

Pass parameter from a batch file to a PowerShell script

When a script is loaded, any parameters that are passed are automatically loaded into a special variables $args. You can reference that in your script without first declaring it.

As an example, create a file called test.ps1 and simply have the variable $args on a line by itself. Invoking the script like this, generates the following output:

PowerShell.exe -File test.ps1 a b c "Easy as one, two, three"
a
b
c
Easy as one, two, three

As a general recommendation, when invoking a script by calling PowerShell directly I would suggest using the -File option rather than implicitly invoking it with the & - it can make the command line a bit cleaner, particularly if you need to deal with nested quotes.

What is the difference between And and AndAlso in VB.NET?

Also see Stack Overflow question: Should I always use the AndAlso and OrElse operators?.

Also: A comment for those who mentioned using And if the right side of the expression has a side-effect you need:

If the right side has a side effect you need, just move it to the left side rather than using "And". You only really need "And" if both sides have side effects. And if you have that many side effects going on you're probably doing something else wrong. In general, you really should prefer AndAlso.

How to get the Full file path from URI

  public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

Using this method we can get string filepath from Uri.

How to set the value for Radio Buttons When edit?

<td><input type="radio" name="gender" value="Male" id="male" <? if($gender=='Male')
{?> checked="" <? }?>/>Male
<input type="radio" name="gender" value="Female" id="female" <? if($gender=='Female') {?> checked="" <?}?>/>Female<br/> </td>

Convert String to SecureString

If you would like to compress the conversion of a string to a SecureString into a LINQ statement you can express it as follows:

var plain  = "The quick brown fox jumps over the lazy dog";
var secure = plain
             .ToCharArray()
             .Aggregate( new SecureString()
                       , (s, c) => { s.AppendChar(c); return s; }
                       , (s)    => { s.MakeReadOnly(); return s; }
                       );

However, keep in mind that using LINQ does not improve the security of this solution. It suffers from the same flaw as any conversion from string to SecureString. As long as the original string remains in memory the data is vulnerable.

That being said, what the above statement can offer is keeping together the creation of the SecureString, its initialization with data and finally locking it from modification.

Python: What OS am I running on?

For the record here's the results on Mac:

>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

The below code may help you.

protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
    final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    numberFormat.setGroupingUsed(true);
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    return numberFormat.format(input);
}

Constructor overload in TypeScript

Actually it might be too late for this answer but you can now do this:

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor();
    constructor(obj: IBox);
    constructor(obj?: IBox) {    
        this.x = !obj ? 0 : obj.x;
        this.y = !obj ? 0 : obj.y;
        this.height = !obj ? 0 : obj.height;
        this.width = !obj ? 0 : obj.width;
    }
}

so instead of static methods you can do the above. I hope it will help you!!!

How can I get stock quotes using Google Finance API?

In order to find chart data using the financial data API of Google, one must simply go to Google as if looking for a search term, type finance into the search engine, and a link to Google finance will appear. Once at the Google finance search engine, type the ticker name into the financial data API engine and the result will be displayed. However, it should be noted that all Google finance charts are delayed by 15 minutes, and at most can be used for a better understanding of the ticker's past history, rather than current price.

A solution to the delayed chart information is to obtain a real-time financial data API. An example of one would be the barchartondemand interface that has real-time quote information, along with other detailed features that make it simpler to find the exact chart you're looking for. With fully customizable features, and specific programming tools for the precise trading information you need, barchartondemand's tools outdo Google finance by a wide margin.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

What is the purpose of "pip install --user ..."?

Why not just put an executable somewhere in my $PATH

~/.local/bin directory is theoretically expected to be in your $PATH.

According to these people it's a bug not adding it in the $PATH when using systemd.

This answer explains it more extensively.

But even if your distro includes the ~/.local/bin directory to the $PATH, it might be in the following form (inside ~/.profile):

if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
fi

which would require you to logout and login again, if the directory was not there before.

Fatal error: Call to undefined function mb_detect_encoding()

There's a much easier way than recompiling PHP. Just yum install the required mbstring library:

Example: How to install PHP mbstring on CentOS 6.2

yum --enablerepo=remi install php-mbstring

Oh, and don't forget to restart apache afterward.

Does JSON syntax allow duplicate keys in an object?

The standard does say this:

Programming languages vary widely on whether they support objects, and if so, what characteristics and constraints the objects offer. The models of object systems can be wildly divergent and are continuing to evolve. JSON instead provides a simple notation for expressing collections of name/value pairs. Most programming languages will have some feature for representing such collections, which can go by names like record, struct, dict, map, hash, or object.

The bug is in node.js at least. This code succeeds in node.js.

try {
     var json = {"name":"n","name":"v"};
     console.log(json); // outputs { name: 'v' }
} catch (e) {
     console.log(e);
}

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

   @{
    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
    }

More Ways to do, can be found here, hope this helps someone.

jQuery check if it is clicked or not

This is the one that i've tried & it works pretty well for me

$('.mybutton').on('click', function() {
       if (!$(this).data('clicked')) {
           //do your stuff here if the button is not clicked
           $(this).data('clicked', true);
       } else {
           //do your stuff here if the button is clicked
           $(this).data('clicked', false);
       }

   });

for more reference check this link JQuery toggle click

How to pass a variable from Activity to Fragment, and pass it back?

Sending data from Activity into Fragments linked by XML

If you create a fragment in Android Studio using one of the templates e.g. File > New > Fragment > Fragment (List), then the fragment is linked via XML. The newInstance method is created in the fragment but is never called so can't be used to pass arguments.

Instead in the Activity override the method onAttachFragment

@Override
public void onAttachFragment(Fragment fragment) {
    if (fragment instanceof DetailsFragment) {
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);        
     }
}

Then read the arguments in the fragment onCreate method as per the other answers

Best way to list files in Java, sorted by Date Modified?

You might also look at apache commons IO, it has a built in last modified comparator and many other nice utilities for working with files.

CUDA incompatible with my gcc version

Another way of configuring nvcc to use a specific version of gcc (gcc-4.4, for instance), is to edit nvcc.profile and alter PATH to include the path to the gcc you want to use first.

For example (gcc-4.4.6 installed in /opt):

PATH += /opt/gcc-4.4.6/lib/gcc/x86_64-unknown-linux-gnu/4.4.6:/opt/gcc-4.4.6/bin:$(TOP)/open64/bin:$(TOP)/share/cuda/nvvm:$(_HERE_):

The location of nvcc.profile varies, but it should be in the same directory as the nvcc executable itself.

This is a bit of a hack, as nvcc.profile is not intended for user configuration as per the nvcc manual, but it was the solution which worked best for me.

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

In my case I used the binaries from Shining Light and the environment variables were already updated. But still had the issue until I ran a command window with elevated privileges.

When you open the CMD window be sure to run it as Administrator. (Right click the Command Prompt in Start menu and choose "Run as administrator")

I think it can't read the files due to User Account Control.

EditText underline below text property

change your colorAccent which color you need that color set on colorAccent and run you get the output

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

I just made the right-most sticky column of a table sticky.

th:last-of-type {
 position: sticky;
 right: 0;
 width: 120px;
 background: #f7f7f7;
}


td:last-of-type {
 position: sticky;
 right: 0;
 background: #f7f7f7;
 width: 120px;
}

I believe if you'll do {position: sticky; left: 0;}, you'll get the desired result.

Python + Django page redirect

Beware. I did this on a development server and wanted to change it later.

I had to clear my caches to change it. In order to avoid this head-scratching in the future, I was able to make it temporary like so:

from django.views.generic import RedirectView

url(r'^source$', RedirectView.as_view(permanent=False, 
                                      url='/dest/')),

How to run two jQuery animations simultaneously?

yes there is!

$(function () {
    $("#first").animate({
       width: '200px'
    }, { duration: 200, queue: false });

    $("#second").animate({
       width: '600px'
    }, { duration: 200, queue: false });
});

Better way to get type of a Javascript variable?

I guess the most universal solution here - is to check for undefined and null first, then just call constructor.name.toLowerCase().

const getType = v =>
  v === undefined
    ? 'undefined'
    : v === null
      ? 'null'
      : v.constructor.name.toLowerCase();




console.log(getType(undefined)); // 'undefined'
console.log(getType(null)); // 'null'
console.log(getType('')); // 'string'
console.log(getType([])); // 'array'
console.log(getType({})); // 'object'
console.log(getType(new Set())); // `set'
console.log(getType(Promise.resolve())); // `promise'
console.log(getType(new Map())); // `map'

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

How to SHUTDOWN Tomcat in Ubuntu?

if you are run this command

 debian@debian:~$  /usr/share/tomcat7/bin/shutdown.sh
 then your server will not stop and you will get o/p like that you provided if you use in 
 super user mode then effect will appear o/p will come like this

 debian@debian:~$ sudo /usr/share/tomcat7/bin/shutdown.sh
 [sudo] password for debian: 
 Using CATALINA_BASE:   /var/lib/tomcat
 Using CATALINA_HOME:   /var/lib/tomcat
 Using CATALINA_TMPDIR: /var/lib/tomcat/temp
 Using JRE_HOME:        /usr/lib/jvm/java-1.6.0-openjdk
 Using CLASSPATH:   /var/lib/tomcat/bin/bootstrap.jar:/var/lib/tomcat/bin/tomcat-juli.jar

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

following this link:

How To: Eclipse Maven install build jar with dependencies

i found out that this is not workable solution because the class loader doesn't load jars from within jars, so i think that i will unpack the dependencies inside the jar.

Checking password match while typing

$(function() {
    $("#txtConfirmPassword").keyup(function() {
        var password = $("#txtNewPassword").val();
        $("#divCheckPasswordMatch").html(password == $(this).val()
            ? "Passwords match."
            : "Passwords do not match!"
        );
    });
});?

Demo here

Find non-ASCII characters in varchar columns using SQL Server

try something like this:

DECLARE @YourTable table (PK int, col1 varchar(20), col2 varchar(20), col3 varchar(20))
INSERT @YourTable VALUES (1, 'ok','ok','ok')
INSERT @YourTable VALUES (2, 'BA'+char(182)+'D','ok','ok')
INSERT @YourTable VALUES (3, 'ok',char(182)+'BAD','ok')
INSERT @YourTable VALUES (4, 'ok','ok','B'+char(182)+'AD')
INSERT @YourTable VALUES (5, char(182)+'BAD','ok',char(182)+'BAD')
INSERT @YourTable VALUES (6, 'BAD'+char(182),'B'+char(182)+'AD','BAD'+char(182)+char(182)+char(182))

--if you have a Numbers table use that, other wise make one using a CTE
;WITH AllNumbers AS
(   SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<1000
)
SELECT 
    pk, 'Col1' BadValueColumn, CONVERT(varchar(20),col1) AS BadValue --make the XYZ in convert(varchar(XYZ), ...) the largest value of col1, col2, col3
    FROM @YourTable           y
        INNER JOIN AllNumbers n ON n.Number <= LEN(y.col1)
    WHERE ASCII(SUBSTRING(y.col1, n.Number, 1))<32 OR ASCII(SUBSTRING(y.col1, n.Number, 1))>127
UNION
SELECT 
    pk, 'Col2' BadValueColumn, CONVERT(varchar(20),col2) AS BadValue --make the XYZ in convert(varchar(XYZ), ...) the largest value of col1, col2, col3
    FROM @YourTable           y
        INNER JOIN AllNumbers n ON n.Number <= LEN(y.col2)
    WHERE ASCII(SUBSTRING(y.col2, n.Number, 1))<32 OR ASCII(SUBSTRING(y.col2, n.Number, 1))>127
UNION
SELECT 
    pk, 'Col3' BadValueColumn, CONVERT(varchar(20),col3) AS BadValue --make the XYZ in convert(varchar(XYZ), ...) the largest value of col1, col2, col3
    FROM @YourTable           y
        INNER JOIN AllNumbers n ON n.Number <= LEN(y.col3)
    WHERE ASCII(SUBSTRING(y.col3, n.Number, 1))<32 OR ASCII(SUBSTRING(y.col3, n.Number, 1))>127
order by 1
OPTION (MAXRECURSION 1000)

OUTPUT:

pk          BadValueColumn BadValue
----------- -------------- --------------------
2           Col1           BA¶D
3           Col2           ¶BAD
4           Col3           B¶AD
5           Col1           ¶BAD
5           Col3           ¶BAD
6           Col1           BAD¶
6           Col2           B¶AD
6           Col3           BAD¶¶¶

(8 row(s) affected)

forEach is not a function error with JavaScript array

parent.children is not an array. It is HTMLCollection and it does not have forEach method. You can convert it to the array first. For example in ES6:

Array.from(parent.children).forEach(child => {
    console.log(child)
});

or using spread operator:

[...parent.children].forEach(function (child) {
    console.log(child)
});

How can I perform a short delay in C# without using sleep?

If you're using .NET 4.5 you can use the new async/await framework to sleep without locking the thread.

How it works is that you mark the function in need of asynchronous operations, with the async keyword. This is just a hint to the compiler. Then you use the await keyword on the line where you want your code to run asynchronously and your program will wait without locking the thread or the UI. The method you call (on the await line) has to be marked with an async keyword as well and is usually named ending with Async, as in ImportFilesAsync.

What you need to do in your example is:

  1. Make sure your program has .Net Framework 4.5 as Target Framework
  2. Mark your function that needs to sleep with the async keyword (see example below)
  3. Add using System.Threading.Tasks; to your code.

Your code is now ready to use the Task.Delay method instead of the System.Threading.Thread.Sleep method (it is possible to use await on Task.Delay because Task.Delay is marked with async in its definition).

private async void button1_Click(object sender, EventArgs e)
{
    textBox1.Text += "\r\nThread Sleeps!";
    await Task.Delay(3000);
    textBox1.Text += "\r\nThread awakens!";
}

Here you can read more about Task.Delay and Await.

Can't create project on Netbeans 8.2

I had the same issue,

  • Quit Netbeans.
  • Delete the JDK9 file in : /Library/Java/JavaVirtualMachines
  • Install the JDK8 : Download link

Good luck :)

NullInjectorError: No provider for AngularFirestore

I take that to my app.module. After the imports it should be works

providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy },
    { provide: FirestoreSettingsToken, useValue: {} }
  ],

My Version:

Angular CLI: 7.2.4
Node: 10.15.0
Angular: 7.2.5
... common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.12.4
@angular-devkit/build-angular     0.12.4
@angular-devkit/build-optimizer   0.12.4
@angular-devkit/build-webpack     0.12.4
@angular-devkit/core              7.2.4
@angular-devkit/schematics        7.2.4
@angular/animations               8.0.0-beta.4+7.sha-3c7ce82
@angular/cdk                      7.3.2-3ae6eb2
@angular/cli                      7.2.4
@angular/fire                     5.1.1
@angular/flex-layout              7.0.0-beta.23
@angular/material                 7.3.2-3ae6eb2
@ngtools/webpack                  7.2.4
@schematics/angular               7.2.4
@schematics/update                0.12.4
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.28.4

How to add a line break within echo in PHP?

The new line character is \n, like so:

echo __("Thanks for your email.\n<br />\n<br />Your order's details are below:", 'jigoshop');

Format Instant to String

public static void main(String[] args) {

    DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            .withZone(ZoneId.systemDefault());

    System.out.println(DATE_TIME_FORMATTER.format(new Date().toInstant()));

}

How to get a path to a resource in a Java JAR file

A File is an abstraction for a file in a filesystem, and the filesystems don't know anything about what are the contents of a JAR.

Try with an URI, I think there's a jar:// protocol that might be useful for your purpouses.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

How do you round a floating point number in Perl?

You don't need any external module.

$x[0] = 1.2;
$x[1] = 1.7;

foreach (@x){
  print $_.' = '.( ( ($_-int($_))<0.5) ? int($_) : int($_)+1 );
  print "\n";
}

I may be missing your point, but I thought this was much cleaner way to do the same job.

What this does is to walk through every positive number in the element, print the number and rounded integer in the format you mentioned. The code concatenates respective rounded positive integer only based on the decimals. int($_) basically round-down the number so ($-int($)) captures the decimals. If the decimals are (by definition) strictly less than 0.5, round-down the number. If not, round-up by adding 1.

Beautiful way to remove GET-variables with PHP?

How about:

preg_replace('/\\?.*/', '', $str)

How can I record a Video in my Android App.?

Here is another example which is working

public class EnregistrementVideoStackActivity extends Activity implements SurfaceHolder.Callback {
    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public MediaRecorder mrec = new MediaRecorder();
    private Button startRecording = null;

    File video;
    private Camera mCamera;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_surface);
        Log.i(null , "Video starting");
        startRecording = (Button)findViewById(R.id.buttonstart);
        mCamera = Camera.open();
        surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, 0, 0, "StartRecording");
        menu.add(0, 1, 0, "StopRecording");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case 0:
            try {
                startRecording();
            } catch (Exception e) {
                String message = e.getMessage();
                Log.i(null, "Problem Start"+message);
                mrec.release();
            }
            break;

        case 1: //GoToAllNotes
            mrec.stop();
            mrec.release();
            mrec = null;
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void startRecording() throws IOException 
    {
        mrec = new MediaRecorder();  // Works well
        mCamera.unlock();

        mrec.setCamera(mCamera);

        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mrec.setAudioSource(MediaRecorder.AudioSource.MIC); 

        mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setOutputFile("/sdcard/zzzz.3gp"); 

        mrec.prepare();
        mrec.start();
    }

    protected void stopRecording() {
        mrec.stop();
        mrec.release();
        mCamera.release();
    }

    private void releaseMediaRecorder(){
        if (mrec != null) {
            mrec.reset();   // clear recorder configuration
            mrec.release(); // release the recorder object
            mrec = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (mCamera != null){
            Parameters params = mCamera.getParameters();
            mCamera.setParameters(params);
        }
        else {
            Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();
    }
}

camera_surface.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<SurfaceView
    android:id="@+id/surface_camera"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1" />

<Button
    android:id="@+id/buttonstart"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/record_start" />

</RelativeLayout>

And of course include these permission in manifest:

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to print the full NumPy array, without truncation?

A slight modification: (since you are going to print a huge list)

import numpy as np
np.set_printoptions(threshold=np.inf, linewidth=200)

x = np.arange(1000)
print(x)

This will increase the number of characters per line (default linewidth of 75). Use any value you like for the linewidth which suits your coding environment. This will save you from having to go through huge number of output lines by adding more characters per line.

Twitter bootstrap scrollable table

Don't need the wrap it in a div...

CSS:

tr {
width: 100%;
display: inline-table;
table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

What is the difference between bool and Boolean types in C#

bool is an alias for the Boolean class. I use the alias when declaring a variable and the class name when calling a method on the class.

Curl : connection refused

127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.

Java enum - why use toString instead of name

name() is a "built-in" method of enum. It is final and you cannot change its implementation. It returns the name of enum constant as it is written, e.g. in upper case, without spaces etc.

Compare MOBILE_PHONE_NUMBER and Mobile phone number. Which version is more readable? I believe the second one. This is the difference: name() always returns MOBILE_PHONE_NUMBER, toString() may be overriden to return Mobile phone number.

css divide width 100% to 3 column

Using this fiddle, you can play around with the width of each div. I've tried in both Chrome and IE and I notice a difference in width between 33% and 33.3%. I also notice a very small difference between 33.3% and 33.33%. I don't notice any difference further than this.

The difference between 33.33% and the theoretical 33.333...% is a mere 0.00333...%.

For arguments sake, say my screen width is 1960px; a fairly high but common resolution. The difference between these two widths is still only 0.065333...px.

So, further than two decimal places, the difference in precision is negligible.

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Can you do a partial checkout with Subversion?

If you already have the full local copy, you can remove unwanted sub folders by using --set-depth command.

svn update --set-depth=exclude www

See: http://blogs.collab.net/subversion/sparse-directories-now-with-exclusion

The set-depth command support multipile paths.

Updating the root local copy will not change the depth of the modified folder.

To restore the folder to being recusively checkingout, you could use --set-depth again with infinity param.

svn update --set-depth=infinity www

How to check for null in a single statement in scala?

Try to avoid using null in Scala. It's really there only for interoperability with Java. In Scala, use Option for things that might be empty. If you're calling a Java API method that might return null, wrap it in an Option immediately.

def getObject : Option[QueueObject] = {
  // Wrap the Java result in an Option (this will become a Some or a None)
  Option(someJavaObject.getResponse)
}

Note: You don't need to put it in a val or use an explicit return statement in Scala; the result will be the value of the last expression in the block (in fact, since there's only one statement, you don't even need a block).

def getObject : Option[QueueObject] = Option(someJavaObject.getResponse)

Besides what the others have already shown (for example calling foreach on the Option, which might be slightly confusing), you could also call map on it (and ignore the result of the map operation if you don't need it):

getObject map QueueManager.add

This will do nothing if the Option is a None, and call QueueManager.add if it is a Some.

I find using a regular if however clearer and simpler than using any of these "tricks" just to avoid an indentation level. You could also just write it on one line:

if (getObject.isDefined) QueueManager.add(getObject.get)

or, if you want to deal with null instead of using Option:

if (getObject != null) QueueManager.add(getObject)

edit - Ben is right, be careful to not call getObject more than once if it has side-effects; better write it like this:

val result = getObject
if (result.isDefined) QueueManager.add(result.get)

or:

val result = getObject
if (result != null) QueueManager.add(result)

Can you control how an SVG's stroke-width is drawn?

A (dirty) possible solution is by using patterns,

here is an example with an inside stroked triangle :

https://jsfiddle.net/qr3p7php/5/

<style>
#triangle1{
  fill: #0F0;
  fill-opacity: 0.3;
  stroke: #000;
  stroke-opacity: 0.5;
  stroke-width: 20;
}
#triangle2{
  stroke: #f00;
  stroke-opacity: 1;
  stroke-width: 1;
}    
</style>

<svg height="210" width="400" >
    <pattern id="fagl" patternUnits="objectBoundingBox" width="2" height="1" x="-50%">
        <path id="triangle1" d="M150 0 L75 200 L225 200 Z">
    </pattern>    
    <path id="triangle2" d="M150 0 L75 200 L225 200 Z" fill="url(#fagl)"/>
</svg>

Returning http 200 OK with error within response body

HTTP Is the Protocol handling the transmission of data over the internet.

If that transmission breaks for whatever reason the HTTP error codes tell you why it can't be sent to you.

The data being transmitted is not handled by HTTP Error codes. Only the method of transmission.

HTTP can't say 'Ok, this answer is gobbledigook, but here it is'. it just says 200 OK.

i.e : I've completed my job of getting it to you, the rest is up to you.

I know this has been answered already but I put it in words I can understand. sorry for any repetition.

How to deploy a Java Web Application (.war) on tomcat?

Note that you can deploy remotely using HTTP.

http://localhost:8080/manager/deploy

Upload the web application archive (WAR) file that is specified as the request data in this HTTP PUT request, install it into the appBase directory of our corresponding virtual host, and start it using the war file name without the .war extension as the path. The application can later be undeployed (and the corresponding application directory removed) by use of the /undeploy. To deploy the ROOT web application (the application with a context path of "/"), name the war ROOT.war.

and if you're using Ant you can do this using Tomcat Ant tasks (perhaps following a successful build).

To determine which path you then hit on your browser, you need to know the port Tomcat is running on, the context and your servlet path. See here for more details.

How to enable native resolution for apps on iPhone 6 and 6 Plus?

Note that iPhone 6 will use the 320pt (640px) resolution if you have enabled the 'Display Zoom' in iPhone > Settings > Display & Brightness > View.

C++ cast to derived class

dynamic_cast should be what you are looking for.

EDIT:

DerivedType m_derivedType = m_baseType; // gives same error

The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.

DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error

You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.

Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):

DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);

If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.

Hope this helps!

Difference between ${} and $() in Bash

  1. your understanding is right. For detailed info on {} see bash ref - parameter expansion

  2. 'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.

With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done in essence manage everything about the iteration yourself

How to count no of lines in text file and store the value into a variable using batch script?

You can also mark with a wildcard symbol * to facilitate group files to count.

Z:\SQLData>find /c /v "" FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_*.txt

Result

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIFRS01_V1.TXT: 2041

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIOST00_V1.TXT: 315938

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_AVIFRS00_V1.TXT: 0

---------- FR_OP133_OCCURENCES_COUNT_PER_DOCUMENTS_CNTPTF00_V1.TXT: 277

Insert node at a certain position in a linked list C++

Insert an element at very beginning position. case-1 when the list is empty. case-2 When the list is not empty.

    #include<iostream>

using namespace std;

struct Node{
int data;
Node* next; //link == head =stored the address of the next node
};

Node* head;  //pointer to Head node with empty list

void Insert(int y);
void print();

int main(){
    head = nullptr; //empty list
    int n,y;
    cout<<"how many number do you want to enter?"<<endl;
    cin>>n;
    for (int i=0;i<n;i++){
        cout<<"Enter the number "<<i+1<<endl;
        cin>>y;
        Insert(y);
        print();
    }
}

void Insert(int y){
    Node* temp = new Node(); //create dynamic memory allocation
    temp->data = y;
    temp->next = head; // temp->next = null; when list is empty
    head = temp;
}

void print(){
    Node* temp = head;
    cout<<"List is: "<<endl;
    while(temp!= nullptr){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
    cout<<endl;
}

How to provide a mysql database connection in single file in nodejs

I took a similar approach as Sean3z but instead I have the connection closed everytime i make a query.

His way works if it's only executed on the entry point of your app, but let's say you have controllers that you want to do a var db = require('./db'). You can't because otherwise everytime you access that controller you will be creating a new connection.

To avoid that, i think it's safer, in my opinion, to open and close the connection everytime.

here is a snippet of my code.

mysq_query.js

// Dependencies
var mysql   = require('mysql'),
    config  = require("../config");

/*
 * @sqlConnection
 * Creates the connection, makes the query and close it to avoid concurrency conflicts.
 */
var sqlConnection = function sqlConnection(sql, values, next) {

    // It means that the values hasnt been passed
    if (arguments.length === 2) {
        next = values;
        values = null;
    }

    var connection = mysql.createConnection(config.db);
    connection.connect(function(err) {
        if (err !== null) {
            console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
        }
    });

    connection.query(sql, values, function(err) {

        connection.end(); // close the connection

        if (err) {
            throw err;
        }

        // Execute the callback
        next.apply(this, arguments);
    });
}

module.exports = sqlConnection;

Than you can use it anywhere just doing like

var mysql_query = require('path/to/your/mysql_query');
mysql_query('SELECT * from your_table where ?', {id: '1'}, function(err, rows)   {
    console.log(rows);
});

UPDATED: config.json looks like

{
        "db": {
        "user"     : "USERNAME",
        "password" : "PASSWORD",
        "database" : "DATABASE_NAME",
        "socketPath": "/tmp/mysql.sock"
    }
}

Hope this helps.

How to get public directory?

The best way to retrieve your public folder path from your Laravel config is the function:

$myPublicFolder = public_path();
$savePath = $mypublicPath."enter_path_to_save";
$path = $savePath."filename.ext";
return File::put($path , $data);

There is no need to have all the variables, but this is just for a demonstrative purpose.

Hope this helps, GRnGC

Compile error: package javax.servlet does not exist

Add servlet-api.jar into your classpath. It will be available into Tomcat's lib folder.

Is it possible to use Java 8 for Android development?

I asked this question over 3 years ago and obviously the answers have changed over the years. As many above have already answered, as of sometime back, the answer became Yes. I have never updated the accepted answer because it was the correct answer at the time. (I am not sure what the Stack Overflow policy is on that)

I just wanted to add another answer for those who still search for this topic. As of 5/17/2017 Google also announced that Kotlin is also an official language for Android development.

I have not found an official press release, but I did watch some of the Google I/O videos where it was announced. Here is a link to a blog post by the Kotlin team on the announcement.

Use mysql_fetch_array() with foreach() instead of while()

You can code like this:

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
foreach($rows as $row){ 
    $ename = stripslashes($row['name']);
    $eemail = stripcslashes($row['email']);
    $epost = stripslashes($row['post']);
    $eid = $row['id'];

    $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

    echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

    echo $eid . '<br/>';

    echo $ename . '<br/>';

    echo $eemail . '<br/>';

    echo $epost . '<br/><br/><br/><br/>';
}

As you can see, it's still need a loop while to get data from mysql_fetch_array

How to convert const char* to char* in C?

A const to a pointer indicates a "read-only" memory location. Whereas the ones without const are a read-write memory areas. So, you "cannot" convert a const(read-only location) to a normal(read-write) location.

The alternate is to copy the data to a different read-write location and pass this pointer to the required function. You may use strdup() to perform this action.

Java 8 Streams: multiple filters vs. complex condition

The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool()) by filter(ItemType::isCool). That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter invocation using a lambda expression with &&.

But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.

In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.

So there is no simple answer.

The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.


¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation

How to set the timeout for a TcpClient?

You would need to use the async BeginConnect method of TcpClient instead of attempting to connect synchronously, which is what the constructor does. Something like this:

var client = new TcpClient();
var result = client.BeginConnect("remotehost", this.Port, null, null);

var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

if (!success)
{
    throw new Exception("Failed to connect.");
}

// we have connected
client.EndConnect(result);

how do I make a single legend for many subplots with matplotlib?

To build on top of @gboffi's and Ben Usman's answer:

In a situation where one has different lines in different subplots with the same color and label, one can do something along the lines of

labels_handles = {
  label: handle for ax in fig.axes for handle, label in zip(*ax.get_legend_handles_labels())
}

fig.legend(
  labels_handles.values(),
  labels_handles.keys(),
  loc="upper center",
  bbox_to_anchor=(0.5, 0),
  bbox_transform=plt.gcf().transFigure,
)

Getting last month's date in php

if you want to get just previous month, then you can use as like following

$prevmonth = date('M Y', strtotime('-1 months'));

if you want to get same days of previous month, Then you can use as like following ..

$prevmonth = date('M Y d', strtotime('-1 months'));

if you want to get last date of previous month , Then you can use as like following ...

$prevmonth = date('M Y t', strtotime('-1 months'));

if you want to get first date of previous month , Then you can use as like following ...

$prevmonth = date('M Y 1', strtotime('-1 months'));

Cannot uninstall angular-cli

If you are facing issue with angular/cli then use the following commands:
npm uninstall -g angular-cli to uninstall the angular/cli.
npm cache clean to clean your npm cache from app data folder under your username.
use npm cache verify to verify your cache whether it is corrupted or not.
use npm cache verify --force to clean your entire cache from your system.

Note:
You can also delete by the following the paths
C:\Users\"Your_syste_User_name"\AppData\Roaming\npm and
C:\Users\"Your_syste_User_name"\AppData\Roaming\npm-cache
Then use the following command to install latest angular/cli version globally in your system.
npm install -g @angular/cli@latest
To get more information visit github angular-cli update.

Update Multiple Rows in Entity Framework from a list of ids

var idList=new int[]{1, 2, 3, 4};
var friendsToUpdate = await Context.Friends.Where(f => 
    idList.Contains(f.Id).ToListAsync();

foreach(var item in previousEReceipts)
{
  item.msgSentBy = "1234";
}

You can use foreach to update each element that meets your condition.

Here is an example in a more generic way:

var itemsToUpdate = await Context.friends.Where(f => f.Id == <someCondition>).ToListAsync();

foreach(var item in itemsToUpdate)
{
   item.property = updatedValue;
}
Context.SaveChanges()

In general you will most probably use async methods with await for db queries.

How to read from a file or STDIN in Bash?

Perl's behavior, with the code given in the OP can take none or several arguments, and if an argument is a single hyphen - this is understood as stdin. Moreover, it's always possible to have the filename with $ARGV. None of the answers given so far really mimic Perl's behavior in these respects. Here's a pure Bash possibility. The trick is to use exec appropriately.

#!/bin/bash

(($#)) || set -- -
while (($#)); do
   { [[ $1 = - ]] || exec < "$1"; } &&
   while read -r; do
      printf '%s\n' "$REPLY"
   done
   shift
done

Filename's available in $1.

If no arguments are given, we artificially set - as the first positional parameter. We then loop on the parameters. If a parameter is not -, we redirect standard input from filename with exec. If this redirection succeeds we loop with a while loop. I'm using the standard REPLY variable, and in this case you don't need to reset IFS. If you want another name, you must reset IFS like so (unless, of course, you don't want that and know what you're doing):

while IFS= read -r line; do
    printf '%s\n' "$line"
done

How to click a href link using Selenium

Thi is your code :

Driver.findElement(By.xpath(//a[@href ='/docs/configuration']")).click();

You missed the Quotation mark

it should be as below

Driver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();

Hope this helps!

CSS force new line

How about with a :before pseudoelement:

a:before {
  content: '\a';
  white-space: pre;
}

Suppress Scientific Notation in Numpy When Creating Array From Nested List

Python Force-suppress all exponential notation when printing numpy ndarrays, wrangle text justification, rounding and print options:

What follows is an explanation for what is going on, scroll to bottom for code demos.

Passing parameter suppress=True to function set_printoptions works only for numbers that fit in the default 8 character space allotted to it, like this:

import numpy as np
np.set_printoptions(suppress=True) #prevent numpy exponential 
                                   #notation on print, default False

#            tiny     med  large
a = np.array([1.01e-5, 22, 1.2345678e7])  #notice how index 2 is 8 
                                          #digits wide

print(a)    #prints [ 0.0000101   22.     12345678. ]

However if you pass in a number greater than 8 characters wide, exponential notation is imposed again, like this:

np.set_printoptions(suppress=True)

a = np.array([1.01e-5, 22, 1.2345678e10])    #notice how index 2 is 10
                                             #digits wide, too wide!

#exponential notation where we've told it not to!
print(a)    #prints [1.01000000e-005   2.20000000e+001   1.23456780e+10]

numpy has a choice between chopping your number in half thus misrepresenting it, or forcing exponential notation, it chooses the latter.

Here comes set_printoptions(formatter=...) to the rescue to specify options for printing and rounding. Tell set_printoptions to just print bare a bare float:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:f}'.format})

a = np.array([1.01e-5, 22, 1.2345678e30])  #notice how index 2 is 30
                                           #digits wide.  

#Ok good, no exponential notation in the large numbers:
print(a)  #prints [0.000010 22.000000 1234567799999999979944197226496.000000] 

We've force-suppressed the exponential notation, but it is not rounded or justified, so specify extra formatting options:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:0.2f}'.format})  #float, 2 units 
                                               #precision right, 0 on left

a = np.array([1.01e-5, 22, 1.2345678e30])   #notice how index 2 is 30
                                            #digits wide

print(a)  #prints [0.00 22.00 1234567799999999979944197226496.00]

The drawback for force-suppressing all exponential notion in ndarrays is that if your ndarray gets a huge float value near infinity in it, and you print it, you're going to get blasted in the face with a page full of numbers.

Full example Demo 1:

from pprint import pprint
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
           [9.55, 116, 189688622.37, 260332262.0, 1.97],
           [2.2, 768, 6004865.13, 5759960.98, 1.21],
           [3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
           [1.91, 474, 44555062.72, 44555062.72, 0.41],
           [5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
           [4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
           [7.03, 116, 66252511.46, 81109291.0, 1.56],
           [6.52, 116, 47674230.76, 57686991.0, 1.43],
           [1.85, 623, 3002631.96, 2899484.08, 0.64],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]

#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)

#This is a little recursive helper function converts all nested 
#ndarrays to python list of lists so that pretty printer knows what to do.
def arrayToList(arr):
    if type(arr) == type(np.array):
        #If the passed type is an ndarray then convert it to a list and
        #recursively convert all nested types
        return arrayToList(arr.tolist())
    else:
        #if item isn't an ndarray leave it as is.
        return arr

#suppress exponential notation, define an appropriate float formatter
#specify stdout line width and let pretty print do the work
np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:16.3f}'.format}, linewidth=130)
pprint(arrayToList(my_array))

Prints:

array([[           3.740,         5162.000,  13683628846.640,  12783387559.860,            1.810],
       [           9.550,          116.000,    189688622.370,    260332262.000,            1.970],
       [           2.200,          768.000,      6004865.130,      5759960.980,            1.210],
       [           3.740,         4062.000,   3263822121.390,   3066869087.900,            1.930],
       [           1.910,          474.000,     44555062.720,     44555062.720,            0.410],
       [           5.800,         5006.000,   8254968918.100,   7446788272.740,            3.250],
       [           4.500,         7887.000,  30078971595.460,  27814989471.310,            2.180],
       [           7.030,          116.000,     66252511.460,     81109291.000,            1.560],
       [           6.520,          116.000,     47674230.760,     57686991.000,            1.430],
       [           1.850,          623.000,      3002631.960,      2899484.080,            0.640],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320]])

Full example Demo 2:

import numpy as np  
#chaotic python list of lists with very different numeric magnitudes 

#            very tiny      medium size            large sized
#            numbers        numbers                numbers

my_list = [[0.000000000074, 5162, 13683628846.64, 1.01e10, 1.81], 
           [1.000000000055,  116, 189688622.37, 260332262.0, 1.97], 
           [0.010000000022,  768, 6004865.13,   -99e13, 1.21], 
           [1.000000000074, 4062, 3263822121.39, 3066869087.9, 1.93], 
           [2.91,            474, 44555062.72, 44555062.72, 0.41], 
           [5,              5006, 8254968918.1, 7446788272.74, 3.25], 
           [0.01,           7887, 30078971595.46, 27814989471.31, 2.18], 
           [7.03,            116, 66252511.46, 81109291.0, 1.56], 
           [6.52,            116, 47674230.76, 57686991.0, 1.43], 
           [1.85,            623, 3002631.96, 2899484.08, 0.64], 
           [13.76,          1227, 1737874137.5, 1446511574.32, 4.32], 
           [13.76,          1337, 1737874137.5, 1446511574.32, 4.32]] 
import sys 
#convert python list of lists to numpy ndarray called my_array 
my_array = np.array(my_list) 
#following two lines do the same thing, showing that np.savetxt can 
#correctly handle python lists of lists and numpy 2D ndarrays. 
np.savetxt(sys.stdout, my_list, '%19.2f') 
np.savetxt(sys.stdout, my_array, '%19.2f') 

Prints:

 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32
 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32

Notice that rounding is consistent at 2 units precision, and exponential notation is suppressed in both the very large e+x and very small e-x ranges.

How to print environment variables to the console in PowerShell?

In addition to Mathias answer.

Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable:

$ Get-Variable

Name                           Value
----                           -----
$                              name
?                              True
^                              gci
args                           {}
ChocolateyTabSettings          @{AllCommands=False}
ConfirmPreference              High
DebugPreference                SilentlyContinue
EnabledExperimentalFeatures    {}
Error                          {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FormatEnumerationLimit         4
...

These also include stuff you may have set in your profile startup script.

Determine the line of code that causes a segmentation fault?

There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).

Modern¹ compilers come with the handy -fsanitize=address flag, adding some compile time and run time overhead which does more error checking.

According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:

int main() {
  volatile int *ptr = (int*)0;
  *ptr = 0;
}
$ gcc -g -fsanitize=address main.c
$ ./a.out
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)
==4848==The signal is caused by a WRITE memory access.
==4848==Hint: address points to the zero page.
    #0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3
    #1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
    #2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main
==4848==ABORTING

The output is slightly more complicated than what gdb would output but there are upsides:

  • There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.

  • ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.


¹ That is Clang 3.1+ and GCC 4.8+.

How to hide column of DataGridView when using custom DataSource?

Just set DataGridView.AutoGenerateColumns = false;

You need click on the arrow on top right corner (in datagridview) to add columns, and in DataPropertyName you need to put a name of your property in your class.

Then, after you defined your columns in datagridview, you can set datagridview.datasource = myClassViewModel.

What is path of JDK on Mac ?

The location has changed from Java 6 (provided by Apple) to Java 7 and onwards (provided by Oracle). The best generic way to find this out is to run

/usr/libexec/java_home

This is the natively supported way to find out both the path to the default Java installation as well as all alternative ones present.

If you check out its help text (java_home -h), you'll see that you can use this command to reliably start a Java program on OS X (java_home --exec ...), with the ability to explicitly specify the desired Java version and architecture, or even request the user to install it if missing.

A more pedestrian approach, but one which will help you trace specifically which Java installation the command java resolves into, goes like this:

  1. run

    which java
    
  2. if that gives you something like /usr/bin/java, which is a symbolic link to the real location, run

    ls -l `which java`
    

    On my system, this outputs

    /usr/bin/java -> /Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java
    

    and therefrom you can read the Java home directory;

  3. if usr/bin/java points to another symbolic link, recursively apply the same approach with

    ls -l <whatever the /usr/bin/java symlink points to>
    

An important variation is the setup you get if you start by installing Apple's Java and later install Oracle's. In that case Step 2 above will give you

/usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Commands/java

and that particular java binary is a stub which will resolve the actual java command to call by consulting the JAVA_HOME environment variable and, if it's not set or doesn't point to a Java home directory, will fall back to calling java_home. It is important to have this in mind when debugging your setup.

What port is a given program using?

On Vista, you do need elevated privileges to use the -b option with netstat. To get around that, you could run "netstat -ano" which will show all open ports along with the associated process id. You could then use tasklist to lookup which process has the corresponding id.

C:\>netstat -ano

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  ...
  TCP    [::]:49335             [::]:0                 LISTENING       1056
  ...

C:\>tasklist /fi "pid eq 1056"

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
sqlservr.exe                  1056 Services                   0     66,192 K

How to run single test method with phpunit?

for run phpunit test in laravel by many way ..

vendor/bin/phpunit --filter methodName className pathTofile.php

vendor/bin/phpunit --filter 'namespace\\directoryName\\className::methodName'

for test single class :

vendor/bin/phpunit --filter  tests/Feature/UserTest.php
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest'
vendor/bin/phpunit --filter 'UserTest' 

for test single method :

 vendor/bin/phpunit --filter testExample 
 vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest::testExample'
 vendor/bin/phpunit --filter testExample UserTest tests/Feature/UserTest.php

for run tests from all class within namespace :

vendor/bin/phpunit --filter 'Tests\\Feature'

for more way run test see more

Passing data to a bootstrap modal

Here is a cleaner way to do it if you are using Bootstrap 3.2.0.

Link HTML

<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>

Modal JavaScript

//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {

    //get data-id attribute of the clicked element
    var bookId = $(e.relatedTarget).data('book-id');

    //populate the textbox
    $(e.currentTarget).find('input[name="bookId"]').val(bookId);
});

http://jsfiddle.net/k7FC2/

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

I have worked with Xamarin. Here are the positives and negatives I have found:

Positives

  1. Easy to code, C# makes the job easier
  2. Performance won't be a concern
  3. Native UI
  4. Good IDE, much like Xcode and Visual Studio.
  5. Xamarin Debugger
  6. Xamarin SDK is free and open-source. Wiki

Negatives

  1. You need to know the API for each platform you want to target (iOS, Android, WP8). However, you do not need to know Objective-C or Java.
  2. Xamarin shares only a few things across platforms (things like databases and web services).
  3. You have to design the UI of each platform separately (this can be a blessing or a curse).

Is there an "exists" function for jQuery?

Try this.

simple and short and usable in the whole project:

jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin

Usage:

console.log($("element-selector").exists());

_________________________________

OR EVEN SHORTER: (for when you don't want to define a jQuery plugin):

if(!!$("elem-selector")[0]) ...;

or even

if($("elem-selector")[0]) ...;

CSS selector for "foo that contains bar"?

Is there any way you could programatically apply a class to the object?

<object class="hasparams">

then do

object.hasparams

Python 3 Float Decimal Points/Precision

Try this:

num = input("Please input your number: ")

num = float("%0.2f" % (num))

print(num)

I believe this is a lot simpler. For 1 decimal place use %0.1f. For 2 decimal places use %0.2f and so on.

Or, if you want to reduce it all to 2 lines:

num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)

Paste multiple columns together

Using tidyr package, this can be easily handled in 1 function call.

data <- data.frame('a' = 1:3, 
                   'b' = c('a','b','c'), 
                   'c' = c('d', 'e', 'f'), 
                   'd' = c('g', 'h', 'i'))

tidyr::unite_(data, paste(colnames(data)[-1], collapse="_"), colnames(data)[-1])

  a b_c_d
1 1 a_d_g
2 2 b_e_h
3 3 c_f_i

Edit: Exclude first column, everything else gets pasted.

# tidyr_0.6.3

unite(data, newCol, -a) 
# or by column index unite(data, newCol, -1)

#   a newCol
# 1 1  a_d_g
# 2 2  b_e_h
# 3 3  c_f_i

How can I make Flexbox children 100% height of their parent?

_x000D_
_x000D_
.container {
    height: 200px;
    width: 500px;
    display: -moz-box;
    display: -webkit-flexbox;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: -moz-flex;
    display: flex;
    -webkit-flex-direction: row;
    -moz-flex-direction: row;
    -ms-flex-direction: row;
    flex-direction: row;
}
.flex-1 {
   flex:1 0 100px;
    background-color: blue;
}
.flex-2 {
    -moz-box-flex: 1;
    -webkit-flex: 1;
    -moz-flex: 1;
    -ms-flex: 1;
    flex: 1 0 100%;
    background-color: red;
}
.flex-2-child {
    flex: 1 0 100%;
    height: 100%;
    background-color: green;
}
_x000D_
<div class="container">
    <div class="flex-1"></div>
    <div class="flex-2">
        <div class="flex-2-child"></div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/2ZDuE/750/

Objective-C Static Class Level variables

u can rename the class as classA.mm and add C++ features in it.

How to get the index of an element in an IEnumerable?

The way I'm currently doing this is a bit shorter than those already suggested and as far as I can tell gives the desired result:

 var index = haystack.ToList().IndexOf(needle);

It's a bit clunky, but it does the job and is fairly concise.

React Native: Possible unhandled promise rejection

You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)

How can I change cols of textarea in twitter-bootstrap?

Simply add the bootstrap "row-fluid" class to the textarea. It will stretch to 100% width;

Update: For bootstrap 3.x use "col-xs-12" class for textarea;

Update II: Also if you want to extend the container to full width use: container-fluid class.

Renaming column names of a DataFrame in Spark Scala

If structure is flat:

val df = Seq((1L, "a", "foo", 3.0)).toDF
df.printSchema
// root
//  |-- _1: long (nullable = false)
//  |-- _2: string (nullable = true)
//  |-- _3: string (nullable = true)
//  |-- _4: double (nullable = false)

the simplest thing you can do is to use toDF method:

val newNames = Seq("id", "x1", "x2", "x3")
val dfRenamed = df.toDF(newNames: _*)

dfRenamed.printSchema
// root
// |-- id: long (nullable = false)
// |-- x1: string (nullable = true)
// |-- x2: string (nullable = true)
// |-- x3: double (nullable = false)

If you want to rename individual columns you can use either select with alias:

df.select($"_1".alias("x1"))

which can be easily generalized to multiple columns:

val lookup = Map("_1" -> "foo", "_3" -> "bar")

df.select(df.columns.map(c => col(c).as(lookup.getOrElse(c, c))): _*)

or withColumnRenamed:

df.withColumnRenamed("_1", "x1")

which use with foldLeft to rename multiple columns:

lookup.foldLeft(df)((acc, ca) => acc.withColumnRenamed(ca._1, ca._2))

With nested structures (structs) one possible option is renaming by selecting a whole structure:

val nested = spark.read.json(sc.parallelize(Seq(
    """{"foobar": {"foo": {"bar": {"first": 1.0, "second": 2.0}}}, "id": 1}"""
)))

nested.printSchema
// root
//  |-- foobar: struct (nullable = true)
//  |    |-- foo: struct (nullable = true)
//  |    |    |-- bar: struct (nullable = true)
//  |    |    |    |-- first: double (nullable = true)
//  |    |    |    |-- second: double (nullable = true)
//  |-- id: long (nullable = true)

@transient val foobarRenamed = struct(
  struct(
    struct(
      $"foobar.foo.bar.first".as("x"), $"foobar.foo.bar.first".as("y")
    ).alias("point")
  ).alias("location")
).alias("record")

nested.select(foobarRenamed, $"id").printSchema
// root
//  |-- record: struct (nullable = false)
//  |    |-- location: struct (nullable = false)
//  |    |    |-- point: struct (nullable = false)
//  |    |    |    |-- x: double (nullable = true)
//  |    |    |    |-- y: double (nullable = true)
//  |-- id: long (nullable = true)

Note that it may affect nullability metadata. Another possibility is to rename by casting:

nested.select($"foobar".cast(
  "struct<location:struct<point:struct<x:double,y:double>>>"
).alias("record")).printSchema

// root
//  |-- record: struct (nullable = true)
//  |    |-- location: struct (nullable = true)
//  |    |    |-- point: struct (nullable = true)
//  |    |    |    |-- x: double (nullable = true)
//  |    |    |    |-- y: double (nullable = true)

or:

import org.apache.spark.sql.types._

nested.select($"foobar".cast(
  StructType(Seq(
    StructField("location", StructType(Seq(
      StructField("point", StructType(Seq(
        StructField("x", DoubleType), StructField("y", DoubleType)))))))))
).alias("record")).printSchema

// root
//  |-- record: struct (nullable = true)
//  |    |-- location: struct (nullable = true)
//  |    |    |-- point: struct (nullable = true)
//  |    |    |    |-- x: double (nullable = true)
//  |    |    |    |-- y: double (nullable = true)

How do I check if a variable exists?

To check the existence of a local variable:

if 'myVar' in locals():
  # myVar exists.

To check the existence of a global variable:

if 'myVar' in globals():
  # myVar exists.

To check if an object has an attribute:

if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.

CSS - Make divs align horizontally

This seems close to what you want:

_x000D_
_x000D_
#foo {_x000D_
  background: red;_x000D_
  max-height: 100px;_x000D_
  overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
  background: blue;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  float: left;_x000D_
  margin: 1em;_x000D_
}
_x000D_
<div id="foo">_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Flatten an irregular list of lists

I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list,tuple)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]

Seems to work. Test:

flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))

returns:

[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]

How to make git mark a deleted and a new file as a file move?

Do the move and the modify in separate commits.

error: ORA-65096: invalid common user or role name in oracle

SQL> alter session set "_ORACLE_SCRIPT"=true;  
SQL> create user sec_admin identified by "Chutinhbk123@!";

Case-Insensitive List Search

Below is the example of searching for a keyword in the whole list and remove that item:

public class Book
{
  public int BookId { get; set; }
  public DateTime CreatedDate { get; set; }
  public string Text { get; set; }
  public string Autor { get; set; }
  public string Source { get; set; }
}

If you want to remove a book that contains some keyword in the Text property, you can create a list of keywords and remove it from list of books:

List<Book> listToSearch = new List<Book>()
   {
        new Book(){
            BookId = 1,
            CreatedDate = new DateTime(2014, 5, 27),
            Text = " test voprivreda...",
            Autor = "abc",
            Source = "SSSS"

        },
        new Book(){
            BookId = 2,
            CreatedDate = new DateTime(2014, 5, 27),
            Text = "here you go...",
            Autor = "bcd",
            Source = "SSSS"


        }
    };

var blackList = new List<string>()
            {
                "test", "b"
            }; 

foreach (var itemtoremove in blackList)
    {
        listToSearch.RemoveAll(p => p.Source.ToLower().Contains(itemtoremove.ToLower()) || p.Source.ToLower().Contains(itemtoremove.ToLower()));
    }


return listToSearch.ToList();

How to add an image to a JPanel?

JLabel imgLabel = new JLabel(new ImageIcon("path_to_image.png"));

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".

How to get unique device hardware id in Android?

Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html

Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices

.

Constructors in Go

If you want to emulate ___.new() syntax you can do something along the lines of:

type Thing struct {
    Name string
    Num int
}
type Constructor_Thing struct {}
func (c CThing) new(<<CONSTRUCTOR ARGS>>) Thing {
  var thing Thing
  //initiate thing from constructor args
  return thing
}
var cThing CThing

func main(){
  var myThing Thing
  myThing = cThing.new(<<CONSTRUCTOR ARGS>>)
  //...
}

Granted, it is a shame that Thing.new() cannot be implemented without CThing.new() also being implemented (iirc) which is a bit of a shame...

A failure occurred while executing com.android.build.gradle.internal.tasks

Clean Project -> Invalidate caches/restart. My problem resolved with this.

How to lay out Views in RelativeLayout programmatically?

This approach with ViewGroup.MarginLayoutParams worked for me:

RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.my_layout);

TextView someTextView = ...

int leftMargin = Util.getXPos();
int topMargin = Util.getYPos();

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
    new ViewGroup.MarginLayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT));

lp.setMargins(leftMargin, topMargin, 0, 0);

myLayout.addView(someTextView, lp);

Values of disabled inputs will not be submitted

There are two attributes, namely readonly and disabled, that can make a semi-read-only input. But there is a tiny difference between them.

<input type="text" readonly />
<input type="text" disabled />
  • The readonly attribute makes your input text disabled, and users are not able to change it anymore.
  • Not only will the disabled attribute make your input-text disabled(unchangeable) but also cannot it be submitted.

jQuery approach (1):

$("#inputID").prop("readonly", true);
$("#inputID").prop("disabled", true);

jQuery approach (2):

$("#inputID").attr("readonly","readonly");
$("#inputID").attr("disabled", "disabled");

JavaScript approach:

document.getElementById("inputID").readOnly = true;
document.getElementById("inputID").disabled = true;

PS disabled and readonly are standard html attributes. prop introduced with jQuery 1.6.

How can I add NSAppTransportSecurity to my info.plist file?

try With this --- worked for me in Xcode-beta 4 7.0

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>yourdomain.com</key>
        <dict>
            <!--Include to allow subdomains-->
            <key>NSIncludesSubdomains</key>
            <true/>
            <!--Include to allow HTTP requests-->
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <!--Include to specify minimum TLS version-->
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>
    </dict>
</dict>

Also one more option, if you want to disable ATS you can use this :

<key>NSAppTransportSecurity</key>  
 <dict>  
      <key>NSAllowsArbitraryLoads</key><true/>  
 </dict>

But this is not recommended at all. The server should have the SSL certificates and so that there is no privacy leaks.

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

Adding attribute in jQuery

You can add attributes using attr like so:

$('#someid').attr('name', 'value');

However, for DOM properties like checked, disabled and readonly, the proper way to do this (as of JQuery 1.6) is to use prop.

$('#someid').prop('disabled', true);

Delayed function calls

Building upon the answer from David O'Donoghue here is an optimized version of the Delayed Delegate:

using System.Windows.Forms;
using System.Collections.Generic;
using System;

namespace MyTool
{
    public class DelayedDelegate
    {
       static private DelayedDelegate _instance = null;

        private Timer _runDelegates = null;

        private Dictionary<MethodInvoker, DateTime> _delayedDelegates = new Dictionary<MethodInvoker, DateTime>();

        public DelayedDelegate()
        {
        }

        static private DelayedDelegate Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new DelayedDelegate();
                }

                return _instance;
            }
        }

        public static void Add(MethodInvoker pMethod, int pDelay)
        {
            Instance.AddNewDelegate(pMethod, pDelay * 1000);
        }

        public static void AddMilliseconds(MethodInvoker pMethod, int pDelay)
        {
            Instance.AddNewDelegate(pMethod, pDelay);
        }

        private void AddNewDelegate(MethodInvoker pMethod, int pDelay)
        {
            if (_runDelegates == null)
            {
                _runDelegates = new Timer();
                _runDelegates.Tick += RunDelegates;
            }
            else
            {
                _runDelegates.Stop();
            }

            _delayedDelegates.Add(pMethod, DateTime.Now + TimeSpan.FromMilliseconds(pDelay));

            StartTimer();
        }

        private void StartTimer()
        {
            if (_delayedDelegates.Count > 0)
            {
                int delay = FindSoonestDelay();
                if (delay == 0)
                {
                    RunDelegates();
                }
                else
                {
                    _runDelegates.Interval = delay;
                    _runDelegates.Start();
                }
            }
        }

        private int FindSoonestDelay()
        {
            int soonest = int.MaxValue;
            TimeSpan remaining;

            foreach (MethodInvoker invoker in _delayedDelegates.Keys)
            {
                remaining = _delayedDelegates[invoker] - DateTime.Now;
                soonest = Math.Max(0, Math.Min(soonest, (int)remaining.TotalMilliseconds));
            }

            return soonest;
        }

        private void RunDelegates(object pSender = null, EventArgs pE = null)
        {
            try
            {
                _runDelegates.Stop();

                List<MethodInvoker> removeDelegates = new List<MethodInvoker>();

                foreach (MethodInvoker method in _delayedDelegates.Keys)
                {
                    if (DateTime.Now >= _delayedDelegates[method])
                    {
                        method();

                        removeDelegates.Add(method);
                    }
                }

                foreach (MethodInvoker method in removeDelegates)
                {
                    _delayedDelegates.Remove(method);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                StartTimer();
            }
        }
    }
}

The class could be slightly more improved by using a unique key for the delegates. Because if you add the same delegate a second time before the first one fired, you might get a problem with the dictionary.