Programs & Examples On #Stratus

Return a string method in C#

Use x.fullNameMethod() to call the method.

How to output a multiline string in Bash?

One more thing, using printf with predefined var as template.

msg="First line %s
Second line %s
Third line %s
"

one='additional message for the first line'
two='2'
tri='this is the last one'

printf "$msg" "$one" "$two" "$tri"

This ^^^ will print whole message with additional vars inserted instead of '%s' in provided order.

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

?php

/* Database config */

$db_host        = 'localhost';
$db_user        = '~';
$db_pass        = '~';
$db_database    = 'banners'; 

/* End config */


$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

?>

"The semaphore timeout period has expired" error for USB connection

I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.

For me it was that wrong Bits per second value was set.

Execute script after specific delay using JavaScript

I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :)

//  Show current seconds and milliseconds
//  (I know there are other ways, I was aiming for minimal code
//  and fixed width.)
function secs()
{
    var s = Date.now() + ""; s = s.substr(s.length - 5);
  return s.substr(0, 2) + "." + s.substr(2);
}

//  Log we're loading
console.log("Loading: " + secs());

//  Create a list of commands to execute
var cmds = 
[
    function() { console.log("A: " + secs()); },
    function() { console.log("B: " + secs()); },
    function() { console.log("C: " + secs()); },
    function() { console.log("D: " + secs()); },
    function() { console.log("E: " + secs()); },
  function() { console.log("done: " + secs()); }
];

//  Run each command with a second delay in between
var ms = 1000;
cmds.forEach(function(cmd, i)
{
    setTimeout(cmd, ms * i);
});

// Log we've loaded (probably logged before first command)
console.log("Loaded: " + secs());

You can copy the code block and paste it into a console window and see something like:

Loading: 03.077
Loaded: 03.078
A: 03.079
B: 04.075
C: 05.075
D: 06.075
E: 07.076
done: 08.076

Removing items from a ListBox in VB.net

This worked for me.

Private Sub listbox_MouseDoubleClick(sender As Object, e As MouseEventArgs) 
        Handles listbox.MouseDoubleClick
        listbox.Items.RemoveAt(listbox.SelectedIndex.ToString())
    End Sub

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

How to check if a string is null in python

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

How do I uninstall a Windows service if the files do not exist anymore?

You have at least three options. I have presented them in order of usage preference.

Method 1 - You can use the SC tool (Sc.exe) included in the Resource Kit. (included with Windows 7/8)

Open a Command Prompt and enter

sc delete <service-name>

Tool help snippet follows:

DESCRIPTION:
        SC is a command line program used for communicating with the
        NT Service Controller and services.

delete----------Deletes a service (from the registry).

Method 2 - use delserv

Download and use delserv command line utility. This is a legacy tool developed for Windows 2000. In current Window XP boxes this was superseded by sc described in method 1.

Method 3 - manually delete registry entries (Note that this backfires in Windows 7/8)

Windows services are registered under the following registry key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Search for the sub-key with the service name under referred key and delete it. (and you might need to restart to remove completely the service from the Services list)

Failed to Connect to MySQL at localhost:3306 with user root

It failed because there is no server install on your computer. You need to Download 'MySQL Community Server 8.0.17' & restart your server.

Submitting the value of a disabled input field

I know this is old but I just ran into this problem and none of the answers are suitable. nickf's solution works but it requires javascript. The best way is to disable the field and still pass the value is to use a hidden input field to pass the value to the form. For example,

<input type="text" value="22.2222" disabled="disabled" />
<input type="hidden" name="lat" value="22.2222" />

This way the value is passed but the user sees the greyed out field. The readonly attribute does not gray it out.

Passive Link in Angular 2 - <a href=""> equivalent

Here is a simple way

  <div (click)="$event.preventDefault()">
            <a href="#"></a>
   </div>

capture the bubbling event and shoot it down

MySQL - UPDATE query with LIMIT

For people get this post by search "update limit MySQL" trying to avoid turning off the safe update mode when facing update with the multiple-table syntax.

Since the offical document state

For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. In this case, ORDER BY and LIMIT cannot be used.

https://stackoverflow.com/a/28316067/1278112
I think this answer is quite helpful. It gives an example

UPDATE customers SET countryCode = 'USA' WHERE country = 'USA'; -- which gives the error, you just write:

UPDATE customers SET countryCode = 'USA' WHERE (country = 'USA' AND customerNumber <> 0); -- Because customerNumber is a primary key you got no error 1175 any more.

What I want but would raise error code 1175.

UPDATE table1 t1
        INNER JOIN
    table2 t2 ON t1.name = t2.name 
SET 
    t1.column = t2.column
WHERE
    t1.name = t2.name;

The working edition

UPDATE table1 t1
        INNER JOIN
    table2 t2 ON t1.name = t2.name 
SET 
    t1.column = t2.column
WHERE
    (t1.name = t2.name and t1.prime_key !=0);

Which is really simple and elegant. Since the original answer doesn't get too much attention (votes), I post more explanation. Hope this can help others.

Typescript ReferenceError: exports is not defined

Few other Solutions for this issue

  • Add the following line before other references to Javascript. This is a nice little hack.
   <script>var exports = {};</script>
  • This issue occurs with the latest version of TypeScript, this error can be eliminated by referring to typescript version 2.1.6

How to insert a row in an HTML table body in JavaScript

Add rows:

_x000D_
_x000D_
<html>_x000D_
    <script>_x000D_
        function addRow() {_x000D_
            var table = document.getElementById('myTable');_x000D_
            //var row = document.getElementById("myTable");_x000D_
            var x = table.insertRow(0);_x000D_
            var e = table.rows.length-1;_x000D_
            var l = table.rows[e].cells.length;_x000D_
            //x.innerHTML = "&nbsp;";_x000D_
_x000D_
            for (var c=0, m=l; c < m; c++) {_x000D_
                table.rows[0].insertCell(c);_x000D_
                table.rows[0].cells[c].innerHTML = "&nbsp;&nbsp;";_x000D_
            }_x000D_
        }_x000D_
_x000D_
        function addColumn() {_x000D_
            var table = document.getElementById('myTable');_x000D_
            for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
                table.rows[r].insertCell(0);_x000D_
                table.rows[r].cells[0].innerHTML = "&nbsp;&nbsp;";_x000D_
            }_x000D_
        }_x000D_
_x000D_
        function deleteRow() {_x000D_
            document.getElementById("myTable").deleteRow(0);_x000D_
        }_x000D_
_x000D_
        function deleteColumn() {_x000D_
            // var row = document.getElementById("myRow");_x000D_
            var table = document.getElementById('myTable');_x000D_
            for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
                table.rows[r].deleteCell(0); // var table handle_x000D_
            }_x000D_
        }_x000D_
    </script>_x000D_
_x000D_
    <body>_x000D_
        <input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>_x000D_
        <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>_x000D_
        <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>_x000D_
        <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>_x000D_
_x000D_
        <table  id='myTable' border=1 cellpadding=0 cellspacing=0>_x000D_
            <tr id='myRow'>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

And cells.

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my case I've used this:

var query = "select * from table where Id IN @Ids";
var result = conn.Query<MyEntity>(query, new { Ids = ids });

my variable "ids" in the second line is an IEnumerable of strings, also they can be integers I guess.

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

How to calculate difference between two dates in oracle 11g SQL

Oracle DateDiff is from a different product, probably mysql (which is now owned by Oracle).

The difference between two dates (in oracle's usual database product) is in days (which can have fractional parts). Factor by 24 to get hours, 24*60 to get minutes, 24*60*60 to get seconds (that's as small as dates go). The math is 100% accurate for dates within a couple of hundred years or so. E.g. to get the date one second before midnight of today, you could say

select trunc(sysdate) - 1/24/60/60 from dual;

That means "the time right now", truncated to be just the date (i.e. the midnight that occurred this morning). Then it subtracts a number which is the fraction of 1 day that measures one second. That gives you the date from the previous day with the time component of 23:59:59.

2D array values C++

Just want to point out you do not need to specify all dimensions of the array.

The leftmost dimension can be 'guessed' by the compiler.

#include <stdio.h>
int main(void) {
  int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
  printf("sizeof arr is %d bytes\n", (int)sizeof arr);
  printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
  return 0;
}

Equivalent VB keyword for 'break'

Exit [construct], and intelisense will tell you which one(s) are valid in a particular place.

Tab separated values in awk

You can set the Field Separator:

... | awk 'BEGIN {FS="\t"}; {print $1}'

Excellent read:

https://docs.freebsd.org/info/gawk/gawk.info.Field_Separators.html

SQL- Ignore case while searching for a string

See this similar question and answer to searching with case insensitivity - SQL server ignore case in a where expression

Try using something like:

SELECT DISTINCT COL_NAME 
FROM myTable 
WHERE COL_NAME COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%priceorder%'

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Easy way - Project > Manage NuGet Packages... > Browse(tab) > in search input set this: Microsoft.CodeDom.Providers.DotNetCompilerPlatform

You can install or update or uninstall and install this compiler

DotNetCompilerPlatform

Is there a way I can retrieve sa password in sql server 2005

Wait!

There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password


How to use the tool to retrieve the password

To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer

"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user

name for which you want to retrieve password.Copy the password field (Hashed Code) and

paste here (in Hashed code Field) and click on start button to retrieve

I checked the tool on SQLServer 2000 and it's working fine.

how to show calendar on text box click in html

try to use jquery-ui

<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>

<script>   
    $(function() {
         $( "#calendar" ).datepicker();   
    }); 
</script>

<p>Calendar: <input type="text" id="calendar" /></p>

more

Collision Detection between two images in Java

Here's a useful of an open source game that uses a lot of collisions: http://robocode.sourceforge.net/

You may take a look at the code and complement with the answers written here.

UML class diagram enum

Typically you model the enum itself as a class with the enum stereotype

Change bootstrap navbar background color and font color

No need for the specificity .navbar-default in your CSS. Background color requires background-color:#cc333333 (or just background:#cc3333). Finally, probably best to consolidate all your customizations into a single class, as below:

.navbar-custom {
    color: #FFFFFF;
    background-color: #CC3333;
}

..

<div id="menu" class="navbar navbar-default navbar-custom">

Example: http://www.bootply.com/OusJAAvFqR#

If conditions in a Makefile, inside a target

There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)

You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.

UNAME := $(shell uname -m)

all:
    $(info Checking if custom header is needed)
    ifeq ($(UNAME), x86_64)
    ... do some things to build unistd_32.h
    endif

    @make -C $(KDIR) M=$(PWD) modules

So you want unistd_32.h built (maybe) before you invoke the second make, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:

ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif

all:
    @make -C $(KDIR) M=$(PWD) modules

unistd_32.h:
    ... do some things to build unistd_32.h

Now for building unistd_32.h:

F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
    $(info Copying custom header)
    $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else    
    F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
    ifeq ($(F2_EXISTS), 1)
        $(info Copying custom header)
        $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
    else
        $(error asm/unistd_32.h and asm-386/unistd.h does not exist)
    endif
endif

You are trying to build unistd.h from unistd_32.h; the only trick is that unistd_32.h could be in either of two places. The simplest way to clean this up is to use a vpath directive:

vpath unistd.h /usr/include/asm /usr/include/asm-i386

unistd_32.h: unistd.h
    sed -e 's/__NR_/__NR32_/g' $< > $@

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

Hibernate 4.3 is the first version to implement the JPA 2.1 spec (part of Java EE 7). And it's thus expecting the JPA 2.1 library in the classpath, not the JPA 2.0 library. That's why you get this exception: Table.indexes() is a new attribute of Table, introduced in JPA 2.1

Copy all the lines to clipboard

Click the left mouse button, drag across the section you want to copy and release. The code automatically gets copied to clipboard.

Center content in responsive bootstrap navbar

this should work

 .navbar-nav {
    position: absolute;
    left: 50%;
    transform: translatex(-50%);
}

Find the server name for an Oracle database

SELECT  host_name
FROM    v$instance

How to mark a build unstable in Jenkins when running shell scripts

Modern Jenkins versions (since 2.26, October 2016) solved this: it's just an advanced option for the Execute shell build step!

exit code for build

You can just choose and set an arbitrary exit value; if it matches, the build will be unstable. Just pick a value which is unlikely to be launched by a real process in your build.

How to get active user's UserDetails

And if you need authorized user in templates (e.g. JSP) use

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>

together with

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring-security.version}</version>
    </dependency>

After MySQL install via Brew, I get the error - The server quit without updating PID file

This is file permission problem. Check disk permissions and repair.

Osx => Cmd+Space => Disk Utilty => Verify Disk Permissions.

Verify completed after Repair Disk Permissions. mysql.server start command is worked succesfuly.

How to do a https request with bad certificate?

The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):

customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}

Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport struct over time.

Creating/writing into a new file in Qt

#include <QFile>
#include <QCoreApplication>
#include <QTextStream>

int main(int argc, char *argv[])
{
    // Create a new file     
    QFile file("out.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out << "This file is generated by Qt\n";

    // optional, as QFile destructor will already do it:
    file.close(); 

    //this would normally start the event loop, but is not needed for this
    //minimal example:
    //return app.exec();

    return 0;
}

How to rename a table in SQL Server?

To change a table name with a different schema:

Example: Change dbo.MyTable1 to wrk.MyTable2

EXEC SP_RENAME 'dbo.MyTable1', 'MyTable2'

ALTER SCHEMA wrk TRANSFER dbo.MyTable2

get the titles of all open windows

http://pinvoke.net/default.aspx/user32.EnumDesktopWindows

There is an example of using user.dll's EnumWindow in C# to list all open windows.

A warning - comparison between signed and unsigned integer expressions

The primary issue is that underlying hardware, the CPU, only has instructions to compare two signed values or compare two unsigned values. If you pass the unsigned comparison instruction a signed, negative value, it will treat it as a large positive number. So, -1, the bit pattern with all bits on (twos complement), becomes the maximum unsigned value for the same number of bits.

8-bits: -1 signed is the same bits as 255 unsigned 16-bits: -1 signed is the same bits as 65535 unsigned etc.

So, if you have the following code:

int fd;
fd = open( .... );

int cnt;
SomeType buf;

cnt = read( fd, &buf, sizeof(buf) );

if( cnt < sizeof(buf) ) {
    perror("read error");
}

you will find that if the read(2) call fails due to the file descriptor becoming invalid (or some other error), that cnt will be set to -1. When comparing to sizeof(buf), an unsigned value, the if() statement will be false because 0xffffffff is not less than sizeof() some (reasonable, not concocted to be max size) data structure.

Thus, you have to write the above if, to remove the signed/unsigned warning as:

if( cnt < 0 || (size_t)cnt < sizeof(buf) ) {
    perror("read error");
}

This just speaks loudly to the problems.

1.  Introduction of size_t and other datatypes was crafted to mostly work, 
    not engineered, with language changes, to be explicitly robust and 
    fool proof.
2.  Overall, C/C++ data types should just be signed, as Java correctly
    implemented.

If you have values so large that you can't find a signed value type that works, you are using too small of a processor or too large of a magnitude of values in your language of choice. If, like with money, every digit counts, there are systems to use in most languages which provide you infinite digits of precision. C/C++ just doesn't do this well, and you have to be very explicit about everything around types as mentioned in many of the other answers here.

How do you change text to bold in Android?

4 ways to make Android TextView bold- Full answer is here.

  1. Using android:textStyle attribute

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TEXTVIEW 1" android:textStyle="bold" /> Use bold|italic for bold and italic.

  2. using setTypeface() method

    textview2.setTypeface(null, Typeface.BOLD);
    textview2.setText("TEXTVIEW 2");
    
  3. HtmlCompat.fromHtml() method, Html.fromHtml() was deprecated in API level 24.

     String html="This is <b>TEXTVIEW 3</b>";
     textview3.setText(HtmlCompat.fromHtml(html,Typeface.BOLD));
    

Rails filtering array of objects by attribute value

I'd go about this slightly differently. Structure your query to retrieve only what you need and split from there.

So make your query the following:

#                                vv or Job.find(1) vv
attachments = Attachment.where(job_id: @job.id, file_type: ["logo", "image"])
# or 
Job.includes(:attachments).where(id: your_job_id, attachments: { file_type: ["logo", "image"] })

And then partition the data:

@logos, @images = attachments.partition { |attachment| attachment.file_type == "logo" }

That will get the data you're after in a neat and efficient manner.

What jar should I include to use javax.persistence package in a hibernate based application?

For JPA 2.1 the javax.persistence package can be found in here:

<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.1-api</artifactId>
   <version>1.0.0.Final</version>
</dependency>

See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions

The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.3.7.Final</version>
</dependency>

how to get date of yesterday using php?

there you go

date('d.m.Y',strtotime("-1 days"));

this will work also if month change

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

As mentioned earlier,

  1. right click on the pom.xml

enter image description here

  1. Add As Maven Project

enter image description here

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

A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.

Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.

Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).

The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.

Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.

How to select a single child element using jQuery?

Not jQuery, as the question asks for, but natively (i.e., no libraries required) I think the better tool for the job is querySelector to get a single instance of a selector:

let el = document.querySelector('img');
console.log(el);

For all matching instances, use document.querySelectorAll(), or for those within another element you can chain as follows:

// Get some wrapper, with class="parentClassName"
let parentEl = document.querySelector('.parentClassName');
// Get all img tags within the parent element by parentEl variable
let childrenEls = parentEl.querySelectorAll('img');

Note the above is equivalent to:

let childrenEls = document.querySelector('.parentClassName').querySelectorAll('img');

Invert match with regexp

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

PHP Echo a large block of text

$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);

How to get a string between two characters?

Try it like this

String s="test string(67)";
String requiredString = s.substring(s.indexOf("(") + 1, s.indexOf(")"));

The method's signature for substring is:

s.substring(int start, int end);

Replace a value in a data frame based on a conditional (`if`) statement

stata.replace<-function(data,replacevar,replacevalue,ifs) {
  ifs=parse(text=ifs)
  yy=as.numeric(eval(ifs,data,parent.frame()))
  x=sum(yy)
  data=cbind(data,yy)
  data[yy==1,replacevar]=replacevalue
  message=noquote(paste0(x, " replacement are made"))
  print(message)
  return(data[,1:(ncol(data)-1)])
}

Call this function using below line.

d=stata.replace(d,"under20",1,"age<20")

What is a segmentation fault?

To be honest, as other posters have mentioned, Wikipedia has a very good article on this so have a look there. This type of error is very common and often called other things such as Access Violation or General Protection Fault.

They are no different in C, C++ or any other language that allows pointers. These kinds of errors are usually caused by pointers that are

  1. Used before being properly initialised
  2. Used after the memory they point to has been realloced or deleted.
  3. Used in an indexed array where the index is outside of the array bounds. This is generally only when you're doing pointer math on traditional arrays or c-strings, not STL / Boost based collections (in C++.)

Mockito : how to verify method was called on an object created within a method?

Solution for your example code using PowerMockito.whenNew

  • mockito-all 1.10.8
  • powermock-core 1.6.1
  • powermock-module-junit4 1.6.1
  • powermock-api-mockito 1.6.1
  • junit 4.12

FooTest.java

package foo;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

//Both @PrepareForTest and @RunWith are needed for `whenNew` to work 
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Foo.class })
public class FooTest {

    // Class Under Test
    Foo cut;

    @Mock
    Bar barMock;

    @Before
    public void setUp() throws Exception {
        cut = new Foo();

    }

    @After
    public void tearDown() {
        cut = null;

    }

    @Test
    public void testFoo() throws Exception {

        // Setup
        PowerMockito.whenNew(Bar.class).withNoArguments()
                .thenReturn(this.barMock);

        // Test
        cut.foo();

        // Validations
        Mockito.verify(this.barMock, Mockito.times(1)).someMethod();

    }

}

JUnit Output JUnit Output

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

Find a string between 2 known values

  Regex regex = new Regex("<tag1>(.*)</tag1>");
  var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata");
  string s = v.Groups[1].ToString();

Or (as mentioned in the comments) to match the minimal subset:

  Regex regex = new Regex("<tag1>(.*?)</tag1>");

Regex class is in System.Text.RegularExpressions namespace.

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

Different class for the last element in ng-repeat

<div ng-repeat="file in files" ng-class="!$last ? 'class-for-last' : 'other'">
   {{file.name}}
</div>

That works for me! Good luck!

Check if null Boolean is true results in exception

Or with the power of Java 8 Optional, you also can do such trick:

Optional.ofNullable(boolValue).orElse(false)

:)

Xcode 10, Command CodeSign failed with a nonzero exit code

What worked for me - found elsewhere - was very simple:

flutter clean

(run it in Terminal from the base dir of the project)

Note that Clean Project in XCode did not make a difference, tried that first.

How to insert DECIMAL into MySQL database

I noticed something else about your coding.... look

INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')

in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be

'0',

you put

0,

lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)

UPDATE.....

I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

I had this issue on Windows 2003 with SQL 2005. I had to take ownership of the files as my Windows user account and I got the database to attache that way.

You have to right click on the file, select Properties, click OK to get past the information screen, click the Advanced button, select your account from the listing of available accounts or groups, apply that change, and Click OK on the Properties screen. Once you have done all that you will be able to manage the file permissions.

I logged into SSMS with Windows Authentication and I was able to attach the database without error.

Cheers!

Reference alias (calculated in SELECT) in WHERE clause

It's actually possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.

A cross join doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does - and treats nulls more transparently.

SELECT
    vars.BalanceDue
FROM
    Entity e
OUTER APPLY (
    SELECT
        -- variables   
        BalanceDue = e.EntityTypeId,
        Variable2 = ...some..long..complex..expression..etc...
    ) vars
WHERE
    vars.BalanceDue > 0

Kudos to Syed Mehroz Alam.

jQuery: click function exclude children.

I personally would add a click handler to the child element that did nothing but stop the propagation of the click. So it would look something like:

$('.example > div').click(function (e) {
    e.stopPropagation();
});

Creating all possible k combinations of n items in C++

I assume you're asking about combinations in combinatorial sense (that is, order of elements doesn't matter, so [1 2 3] is the same as [2 1 3]). The idea is pretty simple then, if you understand induction / recursion: to get all K-element combinations, you first pick initial element of a combination out of existing set of people, and then you "concatenate" this initial element with all possible combinations of K-1 people produced from elements that succeed the initial element.

As an example, let's say we want to take all combinations of 3 people from a set of 5 people. Then all possible combinations of 3 people can be expressed in terms of all possible combinations of 2 people:

comb({ 1 2 3 4 5 }, 3) =
{ 1, comb({ 2 3 4 5 }, 2) } and
{ 2, comb({ 3 4 5 }, 2) } and
{ 3, comb({ 4 5 }, 2) }

Here's C++ code that implements this idea:

#include <iostream>
#include <vector>

using namespace std;

vector<int> people;
vector<int> combination;

void pretty_print(const vector<int>& v) {
  static int count = 0;
  cout << "combination no " << (++count) << ": [ ";
  for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
  cout << "] " << endl;
}

void go(int offset, int k) {
  if (k == 0) {
    pretty_print(combination);
    return;
  }
  for (int i = offset; i <= people.size() - k; ++i) {
    combination.push_back(people[i]);
    go(i+1, k-1);
    combination.pop_back();
  }
}

int main() {
  int n = 5, k = 3;

  for (int i = 0; i < n; ++i) { people.push_back(i+1); }
  go(0, k);

  return 0;
}

And here's output for N = 5, K = 3:

combination no 1:  [ 1 2 3 ] 
combination no 2:  [ 1 2 4 ] 
combination no 3:  [ 1 2 5 ] 
combination no 4:  [ 1 3 4 ] 
combination no 5:  [ 1 3 5 ] 
combination no 6:  [ 1 4 5 ] 
combination no 7:  [ 2 3 4 ] 
combination no 8:  [ 2 3 5 ] 
combination no 9:  [ 2 4 5 ] 
combination no 10: [ 3 4 5 ] 

PHP Error: Function name must be a string

A useful explanation to how braces are used (in addition to Filip Ekberg's useful answer, above) can be found in the short paper Parenthesis in Programming Languages.

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.

The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here

Run PostgreSQL queries from the command line

I also noticed that the query

SELECT * FROM tablename;

gives an error on the psql command prompt and

SELECT * FROM "tablename";

runs fine, really strange, so don't forget the double quotes. I always liked databases :-(

Purpose of ESI & EDI registers?

Opcodes like MOVSB and MOVSW that efficiently copy data from the memory pointed to by ESI to the memory pointed to by EDI. Thus,

mov esi, source_address
mov edi, destination_address
mov ecx, byte_count
cld
rep movsb ; fast!

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

JavaScript "cannot read property "bar" of undefined

You can safeguard yourself either of these two ways:

function myFunc(thing) {
    if (thing && thing.foo && thing.foo.bar) {
        // safe to use thing.foo.bar here
    }
}

function myFunc(thing) {
    try {
        var x = thing.foo.bar;
        // do something with x
    } catch(e) {
        // do whatever you want when thing.foo.bar didn't work
    }
}

In the first example, you explicitly check all the possible elements of the variable you're referencing to make sure it's safe before using it so you don't get any unplanned reference exceptions.

In the second example, you just put an exception handler around it. You just access thing.foo.bar assuming it exists. If it does exist, then the code runs normally. If it doesn't exist, then it will throw an exception which you will catch and ignore. The end result is the same. If thing.foo.bar exists, your code using it executes. If it doesn't exist that code does not execute. In all cases, the function runs normally.

The if statement is faster to execute. The exception can be simpler to code and use in complex cases where there may be many possible things to protect against and your code is structured so that throwing an exception and handling it is a clean way to skip execution when some piece of data does not exist. Exceptions are a bit slower when the exception is thrown.

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

How to `wget` a list of URLs in a text file?

Run it in parallel with

cat text_file.txt | parallel --gnu "wget {}"

Is "&#160;" a replacement of "&nbsp;"?

&#160; is the numeric reference for the entity reference &nbsp; — they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.

See the Wikipedia page for the non-breaking space.

How do I install imagemagick with homebrew?

The quickest fix for me was doing the following:

cd /usr/local
git reset --hard FETCH_HEAD

Then I retried brew install imagemagick and it correctly pulled the package from the new mirror, instead of adamv.

If that does not work, ensure that /Library/Caches/Homebrew does not contain any imagemagick files or folders. Delete them if it does.

How to download Visual Studio 2017 Community Edition for offline installation?

No, there should be an .exe file (vs_Community_xxxxx.exe) directly in you f:\vs2017c directory !

Just start from the this directory, not from a longer path. the packages downloaded are partly having very long path names, it fails if you start from a longer path.

Is it possible to create a temporary table in a View and drop it after select?

You can achieve what you are trying to do, using a Stored Procedure which returns a query result. Views are not suitable / developed for operations like this one.

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

Where to get "UTF-8" string literal in Java?

In case this page comes up in someones web search, as of Java 1.7 you can now use java.nio.charset.StandardCharsets to get access to constant definitions of standard charsets.

How to expand 'select' option width after the user wants to select an option

Okay, this option is pretty hackish but should work.

$(document).ready( function() {
$('#select').change( function() {
    $('#hiddenDiv').html( $('#select').val() );
    $('#select').width( $('#hiddenDiv').width() );
 }
 }

Which would offcourse require a hidden div.

<div id="hiddenDiv" style="visibility:hidden"></div>

ohh and you will need jQuery

How to convert vector to array

We can do this using data() method. C++11 provides this method.

Code Snippet

#include<bits/stdc++.h>
using namespace std;


int main()
{
  ios::sync_with_stdio(false);

  vector<int>v = {7, 8, 9, 10, 11};
  int *arr = v.data();

  for(int i=0; i<v.size(); i++)
  {
    cout<<arr[i]<<" ";
  }

  return 0;
}

SQL Server replace, remove all after certain character

For situations when I need to replace or match(find) something against string I prefer using regular expressions.

Since, the regular expressions are not fully supported in T-SQL you can implement them using CLR functions. Furthermore, you do not need any C# or CLR knowledge at all as all you need is already available in the MSDN String Utility Functions Sample.

In your case, the solution using regular expressions is:

SELECT [dbo].[RegexReplace] ([MyColumn], '(;.*)', '')
FROM [dbo].[MyTable]

But implementing such function in your database is going to help you solving more complex issues at all.


The example below shows how to deploy only the [dbo].[RegexReplace] function, but I will recommend to you to deploy the whole String Utility class.

  1. Enabling CLR Integration. Execute the following Transact-SQL commands:

    sp_configure 'clr enabled', 1
    GO
    RECONFIGURE
    GO  
    
  2. Bulding the code (or creating the .dll). Generraly, you can do this using the Visual Studio or .NET Framework command prompt (as it is shown in the article), but I prefer to use visual studio.

    • create new class library project:

      enter image description here

    • copy and paste the following code in the Class1.cs file:

      using System;
      using System.IO;
      using System.Data.SqlTypes;
      using System.Text.RegularExpressions;
      using Microsoft.SqlServer.Server;
      
      public sealed class RegularExpression
      {
          public static string Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
          {
              string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
              string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
              string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
              return Regex.Replace(input, pattern, replacement);
          }
      }
      
    • build the solution and get the path to the created .dll file:

      enter image description here

    • replace the path to the .dll file in the following T-SQL statements and execute them:

      IF OBJECT_ID(N'RegexReplace', N'FS') is not null
      DROP Function RegexReplace;
      GO
      
      IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'StringUtils')
      DROP ASSEMBLY StringUtils;
      GO
      
      DECLARE @SamplePath nvarchar(1024)
      -- You will need to modify the value of the this variable if you have installed the sample someplace other than the default location.
      Set @SamplePath = 'C:\Users\gotqn\Desktop\StringUtils\StringUtils\StringUtils\bin\Debug\'
      CREATE ASSEMBLY [StringUtils] 
      FROM @SamplePath + 'StringUtils.dll'
      WITH permission_set = Safe;
      GO
      
      
      CREATE FUNCTION [RegexReplace] (@input nvarchar(max), @pattern nvarchar(max), @replacement nvarchar(max))
      RETURNS nvarchar(max)
      AS EXTERNAL NAME [StringUtils].[RegularExpression].[Replace]
      GO
      
    • That's it. Test your function:

      declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
      insert into @MyTable ([id], MyText)
      select 1, 'some text; some more text'
      union all select 2, 'text again; even more text'
      union all select 3, 'text without a semicolon'
      union all select 4, null -- test NULLs
      union all select 5, '' -- test empty string
      union all select 6, 'test 3 semicolons; second part; third part'
      union all select 7, ';' -- test semicolon by itself    
      
      SELECT [dbo].[RegexReplace] ([MyText], '(;.*)', '')
      FROM @MyTable
      
      select * from @MyTable
      

When should an IllegalArgumentException be thrown?

As specified in oracle official tutorial , it states that:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..

Apply style to only first level of td tags

I think, It will work.

.Myclass tr td:first-child{ }

 or 

.Myclass td:first-child { }

Set Icon Image in Java

Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.

e.g.,

// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);

// use icon here
game.frame.setIconImage(myImg);

Split column at delimiter in data frame

@Taesung Shin is right, but then just some more magic to make it into a data.frame. I added a "x|y" line to avoid ambiguities:

df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
foo <- data.frame(do.call('rbind', strsplit(as.character(df$FOO),'|',fixed=TRUE)))

Or, if you want to replace the columns in the existing data.frame:

within(df, FOO<-data.frame(do.call('rbind', strsplit(as.character(FOO), '|', fixed=TRUE))))

Which produces:

  ID FOO.X1 FOO.X2
1 11      a      b
2 12      b      c
3 13      x      y

Android, landscape only orientation?

You can try with

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

Select from multiple tables without a join?

The UNION ALL operator may be what you are looking for.

With this operator, you can concatenate the resultsets from multiple queries together, preserving all of the rows from each. Note that a UNION operator (without the ALL keyword) will eliminate any "duplicate" rows which exist in the resultset. The UNION ALL operator preserves all of the rows from each query (and will likely perform better since it doesn't have the overhead of performing the duplicate check and removal operation).

The number of columns and data type of each column must match in each of the queries. If one of the queries has more columns than the other, we sometimes include dummy expressions in the other query to make the columns and datatypes "match". Often, it's helpful to include an expression (an extra column) in the SELECT list of each query that returns a literal, to reveal which of the queries was the "source" of the row.

SELECT 'q1' AS source, a, b, c, d FROM t1 WHERE ...
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2 JOIN t3 ON ...
UNION ALL
SELECT 'q3', '1', '2', buckle, my_shoe FROM t4

You can wrap a query like this in a set of parenthesis, and use it as an inline view (or "derived table", in MySQL lingo), so that you can perform aggregate operations on all of the rows.

SELECT t.a
     , SUM(t.b)
     , AVG(t.c)
  FROM (
         SELECT 'q1' AS source, a, b, c, d FROM t1
          UNION ALL
         SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
       ) t
 GROUP BY t.a
 ORDER BY t.a

Truncate string in Laravel blade templates

In Laravel 4 & 5 (up to 5.7), you can use str_limit, which limits the number of characters in a string.

While in Laravel 5.8 up, you can use the Str::limit helper.

//For Laravel 4 to Laravel 5.5
{{ str_limit($string, $limit = 150, $end = '...') }}
//For Laravel 5.5 upwards
{{ \Illuminate\Support\Str::limit($string, 150, $end='...') }}

For more Laravel helper functions http://laravel.com/docs/helpers#strings

Split (explode) pandas dataframe string entry to separate rows

I had a similar problem, my solution was converting the dataframe to a list of dictionaries first, then do the transition. Here is the function:

import re
import pandas as pd

def separate_row(df, column_name):
    ls = []
    for row_dict in df.to_dict('records'):
        for word in re.split(',', row_dict[column_name]):
            row = row_dict.copy()
            row[column_name]=word
            ls.append(row)
    return pd.DataFrame(ls)

Example:

>>> from pandas import DataFrame
>>> import numpy as np
>>> a = DataFrame([{'var1': 'a,b,c', 'var2': 1},
               {'var1': 'd,e,f', 'var2': 2}])
>>> a
    var1  var2
0  a,b,c     1
1  d,e,f     2
>>> separate_row(a, "var1")
  var1  var2
0    a     1
1    b     1
2    c     1
3    d     2
4    e     2
5    f     2

You can also change the function a bit to support separating list type rows.

iOS 7 status bar overlapping UI

Many thanks man. It worked fine on:

MAC OS X 10.9.1 - Xcode 5.0.2 - cordova 3.3 - jQuery mobile 1.3.2.

Tomcat 7: How to set initial heap size correctly?

Just came across this and I've implemented Nathan's solution:

add the line (changing the values as required):

export JAVA_OPTS="-Xms512M -Xmx1024M"

to /usr/share/tomcat7/bin/setenv.sh

If that file doesn't exists then create it and

chown root:root it
chmod 755 it

And then restart tomcat and check it with

ps aux | grep logging

Which should just pick up the instance and show the java parms

What is the difference between "screen" and "only screen" in media queries?

The following is from Adobe docs.


The media queries specification also provides the keyword only, which is intended to hide media queries from older browsers. Like not, the keyword must come at the beginning of the declaration. For example:

media="only screen and (min-width: 401px) and (max-width: 600px)"

Browsers that don't recognize media queries expect a comma-separated list of media types, and the specification says they should truncate each value immediately before the first nonalphanumeric character that isn't a hyphen. So, an old browser should interpret the preceding example as this:

media="only"

Because there is no such media type as only, the stylesheet is ignored. Similarly, an old browser should interpret

media="screen and (min-width: 401px) and (max-width: 600px)"

as

media="screen"

In other words, it should apply the style rules to all screen devices, even though it doesn't know what the media queries mean.

Unfortunately, IE 6–8 failed to implement the specification correctly.

Instead of applying the styles to all screen devices, it ignores the style sheet altogether.

In spite of this behavior, it's still recommended to prefix media queries with only if you want to hide the styles from other, less common browsers.


So, using

media="only screen and (min-width: 401px)"

and

media="screen and (min-width: 401px)"

will have the same effect in IE6-8: both will prevent those styles from being used. They will, however, still be downloaded.

Also, in browsers that support CSS3 media queries, both versions will load the styles if the viewport width is larger than 401px and the media type is screen.

I'm not entirely sure which browsers that don't support CSS3 media queries would need the only version

media="only screen and (min-width: 401px)" 

as opposed to

media="screen and (min-width: 401px)"

to make sure it is not interpreted as

media="screen"

It would be a good test for someone with access to a device lab.

Better way to find control in ASP.NET

If you're looking for a specific type of control you could use a recursive loop like this one - http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx

Here's an example I made that returns all controls of the given type

/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control 
{
    private readonly List<T> _foundControls = new List<T>();
    public IEnumerable<T> FoundControls
    {
        get { return _foundControls; }
    }    

    public void FindChildControlsRecursive(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            if (childControl.GetType() == typeof(T))
            {
                _foundControls.Add((T)childControl);
            }
            else
            {
                FindChildControlsRecursive(childControl);
            }
        }
    }
}

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

What's the difference between window.location and document.location in JavaScript?

The canonical way to get the current location object is window.location (see this MSDN page from 1996 and the W3C draft from 2006).

Compare this to document.location, which originally only returned the current URL as a string (see this page on MSDN). Probably to avoid confusion, document.location was replaced with document.URL (see here on MSDN), which is also part of DOM Level 1.

As far as I know, all modern browsers map document.location to window.location, but I still prefer window.location as that's what I've used since I wrote my first DHTML.

Making a drop down list using swift?

A 'drop down menu' is a web control / term. In iOS we don't have these. You might be better looking at UIPopoverController. Check out this tutorial for a bit of an insight to PopoverControllers

http://www.raywenderlich.com/29472/ipad-for-iphone-developers-101-in-ios-6-uipopovercontroller-tutorial

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

How to run C program on Mac OS X using Terminal?

1) First you need to install a GCC Compiler for mac (Google it and install it from the net )

2) Remember the path where you are storing the C file

3) Go to Terminal and set the path

e.g- if you have saved in a new folder ProgramC in Document folder

   then type this in Terminal
    cd Document
    cd ProgramC

4) Now you can see that you are in folder where you have saved your C program (let you saved your program as Hello.c)

5) Now Compile your program

   make Hello
   ./hello

"The system cannot find the file specified"

Server Error in '/' Application.

The system cannot find the file specified

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified

Source Error:

     {
                   SqlCommand cmd = new SqlCommand("select * from tblemployee",con);
                   con.Open();
                   GridView1.DataSource = cmd.ExecuteReader();
                   GridView1.DataBind();

Source File: d:\C# programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line: 23

if your error is same like mine..just do this

right click on your table in sqlserver object explorer,choose properties in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..

Facebook Open Graph not clearing cache

It is a cache, ofc it refreshes, that's what cache is ment to do once in a while. So waiting will eventually work but sometimes you need to do that faster. Changing the filename works.

Spring Data JPA and Exists query

It's gotten a lot easier these days!

@Repository
public interface PageRepository extends JpaRepository<Page, UUID> {

    Boolean existsByName(String name); //Checks if there are any records by name
    Boolean existsBy(); // Checks if there are any records whatsoever

}

AndroidStudio: Failed to sync Install build tools

In case you have error regarding 'SDK build-tools failed' while installing Android Studio, Then you can Download build-tools from - https://androidsdkmanager.azurewebsites.net/Buildtools

How can I slice an ArrayList out of an ArrayList in Java?

Although this post is very old. In case if somebody is looking for this..

Guava facilitates partitioning the List into sublists of a specified size

List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);

How to filter for multiple criteria in Excel?

Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.

The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.

=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")

Like I said, not as elegant as the advanced filters but options are always good.

Load arrayList data into JTable

You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.

 PingScan p = new PingScan();
 List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
                for (final Future<String> f : scanResult) {
                    try {
                        if (f.get() instanceof String) {
                            String ip = f.get();
                            Object[] data = {ip};
                            tableModel.addRow(data);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

How can I format the output of a bash command in neat columns

column(1) is your friend.

$ column -t <<< '"option-y"      yank-pop
> "option-z"      execute-last-named-cmd
> "option-|"      vi-goto-column
> "option-~"      _bash_complete-word
> "option-control-?"      backward-kill-word
> "control-_"     undo
> "control-?"     backward-delete-char
> '
"option-y"          yank-pop
"option-z"          execute-last-named-cmd
"option-|"          vi-goto-column
"option-~"          _bash_complete-word
"option-control-?"  backward-kill-word
"control-_"         undo
"control-?"         backward-delete-char

batch to copy files with xcopy

If the requirement is to copy all files in "\Publish\Appfolder" into the parent "\Publish\" folder (inclusive of any subfolders, following works for me) The switch '/s' allows copying of all subfolders, recursively.

xcopy src\main\Publish\Appfolder\*.* /s src\main\Publish\

Get the difference between two dates both In Months and days in sql

Find out Year - Month- Day between two Days in Orale Sql


select 
trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12) years ,
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))) 
-
(trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12))*12
months,
             round(To_date('20120101', 'YYYYMMDD')-add_months(to_date('19910228','YYYYMMDD'),
                           trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))))) days
        from dual;

How to get .app file of a xcode application

You can find the .app file here:

~/Library/Developer/Xcode/DerivedData/{app name}/Build/Products/Deployment/ 

credit for path goes to this answer

SIDENOTE: I had a lot of fun trying to get this into my iPad after that. It worked however. Using Snow Leopard + Xcode 4.2 + iPad with IOS 5.1.1 :) - I used the iPhone configuration utility to get the app into the ipad (you have to add the app, then click on the device, then click "install" behind the app you just added in the "application library" of iphone configuration utility) and had to create a Distribution Provisioning Profile and get the WWDR certificate and finally change the build settings in Xcode after all the certificates were in place. See here

But after much fun I am now looking at my first app on my iPad :) - btw, for getting apps into the app store you need to create a app store Distribution Provisioning Profile, while for ad hoc installs like these you create an ad hoc one. There is a bit more to it, but I think these are the most important and tricky steps. Enjoy.

PS. Just remembered that you also have to set the build type (top left of Xcode) to "iOS device", otherwise it will never sign your application. So the path name above only has limited value: yes, it will have the .app file in it, but no you can't upload it (at least not using the iPhone configuration utility) since it is not code signed - you will get an "Could not copy validate signature" error. So change it to "iOS device" and build (remember to select the right certificates in the build section of Xcode as per the url info above). In that same build section, you can also set the "Installation Build Products Location" to a different path, so that you can determine where the .app (the one that is properly code signed) ends up.

Store text file content line by line into array

When you do str = in.readLine()) != null you read one line into str variable and if it's not null execute the while block. You do not need to read the line one more time in arr[i] = in.readLine();. Also use lists instead of arrays when you do not know the exact size of the input file (number of lines).

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;

List<String> output = new LinkedList<String>();

while((str = in.readLine()) != null){
    output.add(str);
}

String[] arr = output.toArray(new String[output.size()]);

How to get all values from python enum class?

Use _member_names_ for a quick easy result if it is just the names, i.e.

Color._member_names_

Also, you have _member_map_ which returns an ordered dictionary of the elements. This function returns a collections.OrderedDict, so you have Color._member_names_.items() and Color._member_names_.values() to play with. E.g.

return list(map(lambda x: x.value, Color._member_map_.values()))

will return all the valid values of Color

Logical operator in a handlebars.js {{#if}} conditional

taking this one up a notch, for those of you who live on the edge.

gist: https://gist.github.com/akhoury/9118682 Demo: Code snippet below

Handlebars Helper: {{#xif EXPRESSION}} {{else}} {{/xif}}

a helper to execute an IF statement with any expression

  1. EXPRESSION is a properly escaped String
  2. Yes you NEED to properly escape the string literals or just alternate single and double quotes
  3. you can access any global function or property i.e. encodeURIComponent(property)
  4. this example assumes you passed this context to your handlebars template( {name: 'Sam', age: '20' } ), notice age is a string, just for so I can demo parseInt() later in this post

Usage:

<p>
 {{#xif " name == 'Sam' && age === '12' " }}
   BOOM
 {{else}}
   BAMM
 {{/xif}}
</p>

Output

<p>
  BOOM
</p>

JavaScript: (it depends on another helper- keep reading)

 Handlebars.registerHelper("xif", function (expression, options) {
    return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);
  });

Handlebars Helper: {{x EXPRESSION}}

A helper to execute javascript expressions

  1. EXPRESSION is a properly escaped String
  2. Yes you NEED to properly escape the string literals or just alternate single and double quotes
  3. you can access any global function or property i.e. parseInt(property)
  4. this example assumes you passed this context to your handlebars template( {name: 'Sam', age: '20' } ), age is a string for demo purpose, it can be anything..

Usage:

<p>Url: {{x "'hi' + name + ', ' + window.location.href + ' <---- this is your href,' + ' your Age is:' + parseInt(this.age, 10)"}}</p>

Output:

<p>Url: hi Sam, http://example.com <---- this is your href, your Age is: 20</p>

JavaScript:

This looks a little large because I expanded syntax and commented over almost each line for clarity purposes

_x000D_
_x000D_
Handlebars.registerHelper("x", function(expression, options) {_x000D_
  var result;_x000D_
_x000D_
  // you can change the context, or merge it with options.data, options.hash_x000D_
  var context = this;_x000D_
_x000D_
  // yup, i use 'with' here to expose the context's properties as block variables_x000D_
  // you don't need to do {{x 'this.age + 2'}}_x000D_
  // but you can also do {{x 'age + 2'}}_x000D_
  // HOWEVER including an UNINITIALIZED var in a expression will return undefined as the result._x000D_
  with(context) {_x000D_
    result = (function() {_x000D_
      try {_x000D_
        return eval(expression);_x000D_
      } catch (e) {_x000D_
        console.warn('•Expression: {{x \'' + expression + '\'}}\n•JS-Error: ', e, '\n•Context: ', context);_x000D_
      }_x000D_
    }).call(context); // to make eval's lexical this=context_x000D_
  }_x000D_
  return result;_x000D_
});_x000D_
_x000D_
Handlebars.registerHelper("xif", function(expression, options) {_x000D_
  return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);_x000D_
});_x000D_
_x000D_
var data = [{_x000D_
  firstName: 'Joan',_x000D_
  age: '21',_x000D_
  email: '[email protected]'_x000D_
}, {_x000D_
  firstName: 'Sam',_x000D_
  age: '18',_x000D_
  email: '[email protected]'_x000D_
}, {_x000D_
  firstName: 'Perter',_x000D_
  lastName: 'Smith',_x000D_
  age: '25',_x000D_
  email: '[email protected]'_x000D_
}];_x000D_
_x000D_
var source = $("#template").html();_x000D_
var template = Handlebars.compile(source);_x000D_
$("#main").html(template(data));
_x000D_
h1 {_x000D_
  font-size: large;_x000D_
}_x000D_
.content {_x000D_
  padding: 10px;_x000D_
}_x000D_
.person {_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.min.js"></script>_x000D_
_x000D_
<script id="template" type="text/x-handlebars-template">_x000D_
  <div class="content">_x000D_
    {{#each this}}_x000D_
    <div class="person">_x000D_
      <h1>{{x  "'Hi ' + firstName"}}, {{x 'lastName'}}</h1>_x000D_
      <div>{{x '"you were born in " + ((new Date()).getFullYear() - parseInt(this.age, 10)) '}}</div>_x000D_
      {{#xif 'parseInt(age) >= 21'}} login here:_x000D_
      <a href="http://foo.bar?email={{x 'encodeURIComponent(email)'}}">_x000D_
         http://foo.bar?email={{x 'encodeURIComponent(email)'}}_x000D_
        </a>_x000D_
      {{else}} Please go back when you grow up. {{/xif}}_x000D_
    </div>_x000D_
    {{/each}}_x000D_
  </div>_x000D_
</script>_x000D_
_x000D_
<div id="main"></div>
_x000D_
_x000D_
_x000D_

Moar

if you want access upper level scope, this one is slightly different, the expression is the JOIN of all arguments, usage: say context data looks like this:

// data
{name: 'Sam', age: '20', address: { city: 'yomomaz' } }

// in template
// notice how the expression wrap all the string with quotes, and even the variables
// as they will become strings by the time they hit the helper
// play with it, you will immediately see the errored expressions and figure it out

{{#with address}}
    {{z '"hi " + "' ../this.name '" + " you live with " + "' city '"' }}
{{/with}}

Javascript:

Handlebars.registerHelper("z", function () {
    var options = arguments[arguments.length - 1]
    delete arguments[arguments.length - 1];
    return Handlebars.helpers["x"].apply(this, [Array.prototype.slice.call(arguments, 0).join(''), options]);
});

Handlebars.registerHelper("zif", function () {
    var options = arguments[arguments.length - 1]
    delete arguments[arguments.length - 1];
    return Handlebars.helpers["x"].apply(this, [Array.prototype.slice.call(arguments, 0).join(''), options]) ? options.fn(this) : options.inverse(this);
});

onchange event on input type=range is not triggering in firefox while dragging

I'm posting this as an answer in case you are like me and cannot figure out why the range type input doesn't work on ANY mobile browsers. If you develop mobile apps on your laptop and use the responsive mode to emulate touch, you will notice the range doesn't even move when you have the touch simulator activated. It starts moving when you deactivate it. I went on for 2 days trying every piece of code I could find on the subject and could not make it work for the life of me. I provide a WORKING solution in this post.

Mobile Browsers And Hybrid Apps

Mobile browsers run using a component called Webkit for iOS and WebView for Android. The WebView/WebKit enables you to embed a web browser, which does not have any chrome or firefox (browser) controls including window frames, menus, toolbars and scroll bars into your activity layout. In other words, mobile browsers lack a lot of web components normally found in regular browsers. This is the problem with the range type input. If the user's browser doesn't support range type, it will fall back and treat it as a text input. This is why you cannot move the range when the touch simulator is activated.

Read more here on browser compatibility

jQuery Slider

jQuery provides a slider that somehow works with touch simulation but it is choppy and not very smooth. It wasn't satisfying to me and it probably wont be for you either but you can make it work more smoothly if you combine it with jqueryUi.

Best Solution : Range Touch

If you develop hybrid apps on your laptop, there is a simple and easy library you can use to enable range type input to work with touch events.

This library is called Range Touch.

DEMO

For more information on this issue check this thread here

Recreating the HTML5 range input for Mobile Safari (webkit)?

Add text at the end of each line

You could try using something like:

sed -n 's/$/:80/' ips.txt > new-ips.txt

Provided that your file format is just as you have described in your question.

The s/// substitution command matches (finds) the end of each line in your file (using the $ character) and then appends (replaces) the :80 to the end of each line. The ips.txt file is your input file... and new-ips.txt is your newly-created file (the final result of your changes.)


Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:

sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt

So, for example, if your input file looked something like this (note the :80):

127.0.0.1
128.0.0.0:80
121.121.33.111

The final result would look something like this:

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

#pragma mark in Swift?

For those who are interested in using extensions vs pragma marks (as mentioned in the first comment), here is how to implement it from a Swift Engineer:

import UIKit

class SwiftTableViewController: UITableViewController {

    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

extension SwiftTableViewController {
    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
        let cell = tableView?.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell;

        cell.textLabel.text = "Hello World"

        return cell
    }

}

It's also not necessarily the best practice, but this is how you do it if you like.

How to print a string at a fixed width?

>>> print(f"{'123':<4}56789")
123 56789

How do you create different variable names while in a loop?

Don't do this use a dictionary

import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
    setattr(this, 'string%s' % x, 'Hello')

print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8

don't do this use a dict

globals() has risk as it gives you what the namespace is currently pointing to but this can change and so modifying the return from globals() is not a good idea

How do I add an integer value with javascript (jquery) to a value that's returning a string?

to increment by one you can do something like

  var newValue = currentValue ++;

How to include static library in makefile

CXXFLAGS = -O3 -o prog -rdynamic -D_GNU_SOURCE -L./libmine
LIBS = libmine.a -lpthread 

customize Android Facebook Login button

//call Facebook onclick on your customized button on click by the following

FacebookSdk.sdkInitialize(this.getApplicationContext());

        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Log.d("Success", "Login");

                    }

                    @Override
                    public void onCancel() {
                        Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

        setContentView(R.layout.activity_main);

        Button mycustomizeedbutton=(Button)findViewById(R.id.mycustomizeedbutton);

        mycustomizeedbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                  LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
            }
        });

    }

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

How to add Certificate Authority file in CentOS 7

Complete instruction is as follow:

  1. Extract Private Key from PFX

openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes

  1. Extract Certificate from PFX

openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem

  1. install certificate

yum install -y ca-certificates,

cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem ,

update-ca-trust ,

update-ca-trust force-enable

Hope to be useful

Detect whether Office is 32bit or 64bit via the registry

@clatonh: this is the path of the registry on my PC: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Registration{90140000-002A-0000-1000-0000000FF1CE} and it's definitely a 32-bit-installation on a 64-bit OS.

Nested lists python

Try this setup:

a = [["a","b","c",],["d","e"],["f","g","h"]]

To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]

The first brackets reference which nested list you're accessing, the second pair references the item in that list.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST.

That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.

Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a CORS request, your browser:

  • Will first send an OPTION request to the target URL
  • And then only if the server response to that OPTION contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

I was able to achieve this result using the Jenkins Dynamic Parameter Plug-in. I used the Dynamic Choice Parameter option and, for the choices script, I used the following:

proc1 = ['/bin/bash', '-c', "/usr/bin/git ls-remote -h ssh://[email protected]/path/to/repo.git"].execute()
proc2 = ['/bin/bash', '-c', "awk '{print \$2}'"].execute()
proc3 = ['/bin/bash', '-c', "sed s%^refs/heads%origin%"].execute()

all = proc1 | proc2 | proc3
String result = all.text

String filename = "/tmp/branches.txt"
boolean success = new File(filename).write(result) 

def multiline = "cat /tmp/branches.txt".execute().text
def list = multiline.readLines()

How can I open a URL in Android's web browser from my application?

A short code version...

 if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
     strUrl= "http://" + strUrl;
 }


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));

What is the best place for storing uploaded images, SQL database or disk file system?

For security reasons, it is also best practise to avoid problems caused by IE's Content Sniffing which can allow attackers to upload JavaScript inside image files, which might get executed in the context of your site. So you might want to transform the images (crop/resize them) somehow before storing them to prevent this sort of attack. This answer has some other ideas.

Responsive image map

It depends, you can use jQuery to adjust the ranges proportionally I think. Why do you use an image map by the way? Can't you use scaling divs or other elements for it?

Why use $_SERVER['PHP_SELF'] instead of ""

The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".

There is no reason to use $_SERVER['PHP_SELF'], and # doesn't submit the form at all (unless there is a submit event handler attached that handles the submission).

MySQL date format DD/MM/YYYY select query?

If the hour is important, I used str_to_date(date, '%d/%m/%Y %T' ), the %T shows the hour in the format hh:mm:ss.

How can I set the aspect ratio in matplotlib?

A simple option using plt.gca() to get current axes and set aspect

        plt.gca().set_aspect('equal')

in place of your last line

Default FirebaseApp is not initialized

use com.google.gms:google-services:4.0.1' instead of 4.1.0

PHP append one array to another (not array_push or +)

if you want to merge empty array with existing new value. You must initialize it first.

$products = array();
//just example
for($brand_id=1;$brand_id<=3;$brand_id++){
  array_merge($products,getByBrand($brand_id));
}
// it will create empty array
print_r($a);

//check if array of products is empty
for($brand_id=1;$brand_id<=3;$brand_id++){
  if(empty($products)){
    $products = getByBrand($brand_id);
  }else{
    array_merge($products,getByBrand($brand_id));
  }
}
// it will create array of products

Hope its help.

Change the Blank Cells to "NA"

I suspect everyone has an answer already, though in case someone comes looking, dplyr na_if() would be (from my perspective) the more efficient of those mentioned:

# Import CSV, convert all 'blank' cells to NA
dat <- read.csv("data2.csv") %>% na_if("")

Here is an additional approach leveraging readr's read_delim function. I just picked-up (probably widely know, but I'll archive here for future users). This is very straight forward and more versatile than the above, as you can capture all types of blank and NA related values in your csv file:

dat <- read_csv("data2.csv", na = c("", "NA", "N/A"))

Note the underscore in readr's version versus Base R "." in read_csv.

Hopefully this helps someone who wanders upon the post!

android pick images from gallery

U can do it easier than this answers :

Uri Selected_Image_Uri = data.getData();
ImageView imageView = (ImageView) findViewById(R.id.loadedimg);
imageView.setImageURI(Selected_Image_Uri);

How can I upload files asynchronously?

I recommend using the Fine Uploader plugin for this purpose. Your JavaScript code would be:

$(document).ready(function() {
  $("#uploadbutton").jsupload({
    action: "addFile.do",
    onComplete: function(response){
      alert( "server response: " + response);
    }
  });
});

How to convert a JSON string to a Map<String, String> with Jackson JSON

JavaType javaType = objectMapper.getTypeFactory().constructParameterizedType(Map.class, Key.class, Value.class);
Map<Key, Value> map=objectMapper.readValue(jsonStr, javaType);

i think this will solve your problem.

Move top 1000 lines from text file to a new file using Unix shell commands

Out of curiosity, I found a box with a GNU version of sed (v4.1.5) and tested the (uncached) performance of two approaches suggested so far, using an 11M line text file:

$ wc -l input
11771722 input

$ time head -1000 input > output; time tail -n +1000 input > input.tmp; time cp input.tmp input; time rm input.tmp

real    0m1.165s
user    0m0.030s
sys     0m1.130s

real    0m1.256s
user    0m0.062s
sys     0m1.162s

real    0m4.433s
user    0m0.033s
sys     0m1.282s

real    0m6.897s
user    0m0.000s
sys     0m0.159s

$ time head -1000 input > output && time sed -i '1,+999d' input

real    0m0.121s
user    0m0.000s
sys     0m0.121s

real    0m26.944s
user    0m0.227s
sys     0m26.624s

This is the Linux I was working with:

$ uname -a
Linux hostname 2.6.18-128.1.1.el5 #1 SMP Mon Jan 26 13:58:24 EST 2009 x86_64 x86_64 x86_64 GNU/Linux

For this test, at least, it looks like sed is slower than the tail approach (27 sec vs ~14 sec).

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.

How can I get the first two digits of a number?

Both of the previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too. Here's a solution for constant time and space:

num // 10 ** (int(math.log(num, 10)) - 1)

Function:

import math

def first_n_digits(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

Output:

>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456

You will need to add some checks if it's possible that your input number has less digits than you want.

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How can I get the named parameters from a URL using Flask?

Use request.args to get parsed contents of query string:

from flask import request

@app.route(...)
def login():
    username = request.args.get('username')
    password = request.args.get('password')

Uninstall mongoDB from ubuntu

Sometimes this works;

sudo apt-get install mongodb-org --fix-missing --fix-broken
sudo apt-get autoremove mongodb-org --fix-missing --fix-broken

Does functional programming replace GoF design patterns?

I think that each paradigm serves a different purpose and as such cannot be compared in this way.

I have not heard that the GoF design patterns are applicable to every language. I have heard that they are applicable to all OOP languages. If you use functional programming then the domain of problems that you solve is different from OO languages.

I wouldn't use functional language to write a user interface, but one of the OO languages like C# or Java would make this job easier. If I were writing a functional language then I wouldn't consider using OO design patterns.

Difference between margin and padding?

There is one important difference:

Margin- is on the outside of the element i.e. one will apply the whitespace shift "after" the element begins. Padding- is on the inside, the other will apply the whitespace "before" the element begins.

How do I efficiently iterate over each entry in a Java Map?

You can search for the key and with the help of the key you can find the associated value of the map as map has unique key, see what happens when key is duplicate here or here.

Demo map :

 Map<String, String> map = new HashMap();
  map.put("name", "Badri Paudel");
  map.put("age", "23");
  map.put("address", "KTM");
  map.put("faculty", "BE");
  map.put("major", "CS");
  map.put("head", "AVD");
 

To get key only, you can use map.keySet(); like this :

for(String key : map.keySet()) {
      System.out.println(key);
  }

To get value only , you can use map.values(); like this:

      for(String value : map.values()) {
      System.out.println(value);
  }

To get both key and its value you still can use map.keySet(); and get its corresponding value, like this :

 //this prints the key value pair
  for (String k : map.keySet()) {
        System.out.println(k + " " + map.get(k) + " ");
    }

map.get(key) gives the value pointed by that key.

How to set proxy for wget?

In Windows - for Fiddler say - using environment variables:

set http_proxy=http://127.0.0.1:8888
set https_proxy=http://127.0.0.1:8888

Best tool for inspecting PDF files?

My sugession is Foxit PDF Reader which is very helpful to do important text editing work on pdf file.

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

sweet-alert display HTML code in text

I was upgrading from old sweetalert and found out how to do it in the new Version (official Docs):

// this is a Node object    
var span = document.createElement("span");
span.innerHTML = "Testno  sporocilo za objekt <b>test</b>";

swal({
    title: "" + txt + "", 
    content: span,
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

How can I specify system properties in Tomcat configuration on startup?

Generally you shouldn't rely on system properties to configure a webapp - they may be used to configure the container (e.g. Tomcat) but not an application running inside tomcat.

cliff.meyers has already mentioned the way you should rather use for your webapplication. That's the standard way, that also fits your question of being configurable through context.xml or server.xml means.

That said, should you really need system properties or other jvm options (like max memory settings) in tomcat, you should create a file named "bin/setenv.sh" or "bin/setenv.bat". These files do not exist in the standard archive that you download, but if they are present, the content is executed during startup (if you start tomcat via startup.sh/startup.bat). This is a nice way to separate your own settings from the standard tomcat settings and makes updates so much easier. No need to tweak startup.sh or catalina.sh.

(If you execute tomcat as windows servive, you usually use tomcat5w.exe, tomcat6w.exe etc. to configure the registry settings for the service.)

EDIT: Also, another possibility is to go for JNDI Resources.

How to convert a string variable containing time to time_t type in c++?

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

How do you format a Date/Time in TypeScript?

I had a similar problem and I solved with this

.format();

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

How do I convert from a money datatype in SQL server?

I had this issue as well, and was tripped up for a while on it. I wanted to display 0.00 as 0 and otherwise keep the decimal point. The following didn't work:

CASE WHEN Amount= 0 THEN CONVERT(VARCHAR(30), Amount, 1) ELSE Amount END

Because the resulting column was forced to be a MONEY column. To resolve it, the following worked

CASE WHEN Amount= 0 THEN CONVERT(VARCHAR(30), '0', 1) ELSE CONVERT (VARCHAR(30), Amount, 1) END

This mattered because my final destination column was a VARCHAR(30), and the consumers of that column would error out if an amount was '0.00' instead of '0'.

Stopping a CSS3 Animation on last frame

Isn't your issue that you're setting the webkitAnimationName back to nothing so that's resetting the CSS for your object back to it's default state. Won't it stay where it ended up if you just remove the setTimeout function that's resetting the state?

Getting the inputstream from a classpath resource (XML file)

I tried proposed solution and forward slash in the file name did not work for me, example: ...().getResourceAsStream("/my.properties"); null was returned

Removing the slash worked: ....getResourceAsStream("my.properties");

Here is from doc API: Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:

    modified_package_name/name 

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e'). 

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

Add click event on div tag using javascript

the document class selector:

document.getElementsByClassName('drill_cursor')[0].addEventListener('click',function(){},false)

also the document query selector https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

document.querySelector(".drill_cursor").addEventListener('click',function(){},false)

PostgreSQL how to see which queries have run

Turn on the server log:

log_statement = all

This will log every call to the database server.

I would not use log_statement = all on a production server. Produces huge log files.
The manual about logging-parameters:

log_statement (enum)

Controls which SQL statements are logged. Valid values are none (off), ddl, mod, and all (all statements). [...]

Resetting the log_statement parameter requires a server reload (SIGHUP). A restart is not necessary. Read the manual on how to set parameters.

Don't confuse the server log with pgAdmin's log. Two different things!

You can also look at the server log files in pgAdmin, if you have access to the files (may not be the case with a remote server) and set it up correctly. In pgadmin III, have a look at: Tools -> Server status. That option was removed in pgadmin4.

I prefer to read the server log files with vim (or any editor / reader of your choice).

How to enable curl in Wamp server

The steps are as follows :

  1. Close WAMP (if running)
  2. Navigate to WAMP\bin\php\(your version of php)\
  3. Edit php.ini
  4. Search for curl, uncomment extension=php_curl.dll
  5. Navigate to WAMP\bin\Apache\(your version of apache)\bin\
  6. Edit php.ini
  7. Search for curl, uncomment extension=php_curl.dll
  8. Save both
  9. Restart WAMP

Delaying AngularJS route change until model loaded to prevent flicker

I worked from Misko's code above and this is what I've done with it. This is a more current solution since $defer has been changed to $timeout. Substituting $timeout however will wait for the timeout period (in Misko's code, 1 second), then return the data hoping it's resolved in time. With this way, it returns asap.

function PhoneListCtrl($scope, phones) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}

PhoneListCtrl.resolve = {

  phones: function($q, Phone) {
    var deferred = $q.defer();

    Phone.query(function(phones) {
        deferred.resolve(phones);
    });

    return deferred.promise;
  }
}

PHP: How do you determine every Nth iteration of a loop?

Going off of @Powerlord's answer,

"There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0."

You can still start your counter at 0 (arrays, querys), but offset it

if (($counter + 1) % 3 == 0) {
  echo 'image file';
}

Best practices for styling HTML emails

'Fraid so. I'd make an HTML page with a stylesheet, then use jQuery to apply the stylesheet to the style attr of each element. Something like this:

var styleAttributes = ['color','font-size']; // all the attributes you've applied in your stylesheet
for (i in styleAttributes) {
    $('body *').css(styleAttributes[i],function () {
        $(this).css(styleAttributes[i]);
    });
}

Then copy the DOM and use that in the email.

Qt. get part of QString

Use the left function:

QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "

Also have a look at mid() if you want more control.

How to access a property of an object (stdClass Object) member/element of an array?

To access an array member you use $array['KEY'];

To access an object member you use $obj->KEY;

To access an object member inside an array of objects:
$array[0] // Get the first object in the array
$array[0]->KEY // then access its key

You may also loop over an array of objects like so:

foreach ($arrayOfObjs as $key => $object) {
    echo $object->object_property;
}

Think of an array as a collection of things. It's a bag where you can store your stuff and give them a unique id (key) and access them (or take the stuff out of the bag) using that key. I want to keep things simple here, but this bag can contain other bags too :)

Update (this might help someone understand better):

An array contains 'key' and 'value' pairs. Providing a key for an array member is optional and in this case it is automatically assigned a numeric key which starts with 0 and keeps on incrementing by 1 for each additional member. We can retrieve a 'value' from the array by it's 'key'.

So we can define an array in the following ways (with respect to keys):

First method:

$colorPallete = ['red', 'blue', 'green'];

The above array will be assigned numeric keys automatically. So the key assigned to red will be 0, for blue 1 and so on.

Getting values from the above array:

$colorPallete[0]; // will output 'red'
$colorPallete[1]; // will output 'blue'
$colorPallete[2]; // will output 'green'

Second method:

$colorPallete = ['love' => 'red', 'trust' => 'blue', 'envy' => 'green']; // we expliicitely define the keys ourself.

Getting values from the above array:

$colorPallete['love']; // will output 'red'
$colorPallete['trust']; // will output 'blue'
$colorPallete['envy']; // will output 'green'

What is the best way to remove a table row with jQuery?

You're right:

$('#myTableRow').remove();

This works fine if your row has an id, such as:

<tr id="myTableRow"><td>blah</td></tr>

If you don't have an id, you can use any of jQuery's plethora of selectors.

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

How to fix git error: RPC failed; curl 56 GnuTLS

You can set some option to resolve the issue

Either at global level: (needed if you clone, don't forget to reset after)

$ git config --global http.sslVerify false
$ git config --global http.postBuffer 1048576000

or on a local repository

$ git config http.sslVerify false
$ git config http.postBuffer 1048576000

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

Android Supports SSL implementation by default except for Android N (API level 24) and below Android 5.1 (API level 22)
I was getting the error when making the API call below API level 22 devices after implementing SSL at the server side; that was while creating OkHttpClient client object, and fixed by adding connectionSpecs() method OkHttpClient.Builder class.

the error received was

response failure: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb8882c00: I/O error during system call, Connection reset by peer

so I fixed this by added the check like

if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
            // Do something for below api level 22
            List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
            if (specsList != null) {
                okb.connectionSpecs(specsList);
            }
        }

Also for the Android N (API level 24); I was getting the error while making the HTTP call like

HTTP FAILED: javax.net.ssl.SSLHandshakeException: Handshake failed

and this is fixed by adding the check for Android 7 particularly, like

if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
            // Do something for naugat ; 7
            okb.connectionSpecs(Collections.singletonList(getSpec()));
        }

So my final OkHttpClient object will be like:

         OkHttpClient client
         HttpLoggingInterceptor httpLoggingInterceptor2 = new
         HttpLoggingInterceptor();
         httpLoggingInterceptor2.setLevel(HttpLoggingInterceptor.Level.BODY);

         OkHttpClient.Builder okb = new OkHttpClient.Builder()
                 .addInterceptor(httpLoggingInterceptor2)
               .addInterceptor(new Interceptor() {
                     @Override
                     public Response intercept(Chain chain) throws IOException {
                         Request request = chain.request();
                         Request request2 = request.newBuilder().addHeader(AUTH_KEYWORD, AUTH_TYPE_JW + " " + password).build();
                         return chain.proceed(request2);
                     }
                 }).connectTimeout(30, TimeUnit.SECONDS)
                 .writeTimeout(30, TimeUnit.SECONDS)
                 .readTimeout(30, TimeUnit.SECONDS);

         if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
             // Do something for naugat ; 7
             okb.connectionSpecs(Collections.singletonList(getSpec()));
         }

         if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
             List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
             if (specsList != null) {
                 okb.connectionSpecs(specsList);
             }
         }

         //init client
         client = okb.build();

getSpecsBelowLollipopMR1 function be like,

   private List<ConnectionSpec> getSpecsBelowLollipopMR1(OkHttpClient.Builder okb) {

        try {

            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, null, null);
            okb.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));

            ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                    .tlsVersions(TlsVersion.TLS_1_2)
                    .build();

            List<ConnectionSpec> specs = new ArrayList<>();
            specs.add(cs);
            specs.add(ConnectionSpec.COMPATIBLE_TLS);

            return specs;

        } catch (Exception exc) {
            Timber.e("OkHttpTLSCompat Error while setting TLS 1.2"+ exc);

            return null;
        }
    }

The Tls12SocketFactory class will be found in below link (comment by gotev):

https://github.com/square/okhttp/issues/2372


For more support adding some links below this will help you in detail,

https://developer.android.com/training/articles/security-ssl

D/OkHttp: <-- HTTP FAILED: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0x64e3c938: I/O error during system call, Connection reset by peer

How to apply a CSS class on hover to dynamically generated submit buttons?

Add the below code

input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

If you need only for these button then you can add id name

#paginate input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

DEMO

How to set Highcharts chart maximum yAxis value

Taking help from above answer link mentioned in the above answer sets the max value with option

yAxis: { max: 100 },

On similar line min value can be set.So if you want to set min-max value then

yAxis: {
   min: 0,     
   max: 100
},

If you are using HighRoller php library for integration if Highchart graphs then you just need to set the option

$series->yAxis->min=0;
$series->yAxis->max=100;

How to print to console in pytest?

Using -s option will print output of all functions, which may be too much.

If you need particular output, the doc page you mentioned offers few suggestions:

  1. Insert assert False, "dumb assert to make PyTest print my stuff" at the end of your function, and you will see your output due to failed test.

  2. You have special object passed to you by PyTest, and you can write the output into a file to inspect it later, like

    def test_good1(capsys):
        for i in range(5):
            print i
        out, err = capsys.readouterr()
        open("err.txt", "w").write(err)
        open("out.txt", "w").write(out)
    

    You can open the out and err files in a separate tab and let editor automatically refresh it for you, or do a simple py.test; cat out.txt shell command to run your test.

That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

python multithreading wait till all threads finished

You need to use join method of Thread object in the end of the script.

t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))

t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()

Thus the main thread will wait till t1, t2 and t3 finish execution.

Convert RGB to Black & White in OpenCV

AFAIK, you have to convert it to grayscale and then threshold it to binary.

1. Read the image as a grayscale image If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:

// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image

// C
IplImage *im_rgb  = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);

// C++
Mat im_rgb  = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

3. Convert to binary You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.

E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):

// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

// C++
Mat img_bw = im_gray > 128;

In the above example, 128 is the threshold.

4. Save to disk

// C
cvSaveImage("image_bw.jpg",img_bw);

// C++
imwrite("image_bw.jpg", img_bw);

DataTables: Cannot read property 'length' of undefined

While the above answers describe the situation well, while troubleshooting the issue check also that browser really gets the format DataTables expects. There maybe other reasons not to get the data. For example, if the user does not have access to the data URL and gets some HTML instead. Or the remote system has some unfortunate "fix-ups" in place. Network tab in the browser's Debug tools helps.

How to load data to hive from HDFS without removing the source file?

I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').

When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.

If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).

SSL peer shut down incorrectly in Java

please close the android studio and remove the file

.gradle

and

.idea

file form your project .Hope so it is helpful

Location:Go to Android studio projects->your project ->see both file remove (.gradle & .idea)

Commit only part of a file in Git

You can use git add --patch <filename> (or -p for short), and git will begin to break down your file into what it thinks are sensible "hunks" (portions of the file). It will then prompt you with this question:

Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?

Here is a description of each option:

  • y stage this hunk for the next commit
  • n do not stage this hunk for the next commit
  • q quit; do not stage this hunk or any of the remaining hunks
  • a stage this hunk and all later hunks in the file
  • d do not stage this hunk or any of the later hunks in the file
  • g select a hunk to go to
  • / search for a hunk matching the given regex
  • j leave this hunk undecided, see next undecided hunk
  • J leave this hunk undecided, see next hunk
  • k leave this hunk undecided, see previous undecided hunk
  • K leave this hunk undecided, see previous hunk
  • s split the current hunk into smaller hunks
  • e manually edit the current hunk
  • ? print hunk help

If the file is not in the repository yet, you can first do git add -N <filename>. Afterwards you can go on with git add -p <filename>.

Afterwards, you can use:

  • git diff --staged to check that you staged the correct changes
  • git reset -p to unstage mistakenly added hunks
  • git commit -v to view your commit while you edit the commit message.

Note this is far different than the git format-patch command, whose purpose is to parse commit data into a .patch files.

Reference for future: Git Tools - Interactive Staging

std::string to float or double

Yes, with a lexical cast. Use a stringstream and the << operator, or use Boost, they've already implemented it.

Your own version could look like:

template<typename to, typename from>to lexical_cast(from const &x) {
  std::stringstream os;
  to ret;

  os << x;
  os >> ret;

  return ret;  
}

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

it works for me Swift 3:

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

and in ViewDidLoad:

    self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true

Oracle database: How to read a BLOB?

SQL Developer can show the blob as an image (at least it works for jpegs). In the Data view, double click on the BLOB field to get the "pencil" icon. Click on the pencil to get a dialog that will allow you to select a "View As Image" checkbox.

Get the current language in device

public class LocalUtils {

    private static final String LANGUAGE_CODE_ENGLISH = "en";


    // returns application language eg: en || fa ...
    public static String getAppLanguage() {
        return Locale.getDefault().getLanguage();
    }

    // returns device language eg: en || fa ...
    public static String getDeviceLanguage() {
        return ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getLanguage();
    }

    public static boolean isDeviceEnglish() {
        return getDeviceLanguage().equals(new Locale(LANGUAGE_CODE_ENGLISH).getLanguage());
    }

    public static boolean isAppEnglish() {
        return getAppLanguage().equals(new Locale(LANGUAGE_CODE_ENGLISH).getLanguage());
    }


}

Log.i("AppLanguage: ",     LocalUtils.getAppLanguage());
Log.i("DeviceLanguage: ",  LocalUtils.getDeviceLanguage());
Log.i("isDeviceEnglish: ", String.valueOf(LocalUtils.isDeviceEnglish()));
Log.i("isAppEnglish: ",    String.valueOf(LocalUtils.isAppEnglish()));

How to use KeyListener

In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):

@Override
public void setFocusable(boolean b) {
    super.setFocusable(b);
}

And by adding this to your constructor:

setFocusable(true);

Or, if you are calling the function from a parent class/container:

JComponent childComponent = new JComponent();
childComponent.setFocusable(true);

And then doing all the KeyListener stuff mentioned by others.

onchange file input change img src and change image color

Simple Solution. No Jquery

_x000D_
_x000D_
<img id="output" src="" width="100" height="100">_x000D_
_x000D_
<input name="photo" type="file" accept="image/*" onchange="document.getElementById('output').src = window.URL.createObjectURL(this.files[0])">
_x000D_
_x000D_
_x000D_

min and max value of data type in C

"But glyph", I hear you asking, "what if I have to determine the maximum value for an opaque type whose maximum might eventually change?" You might continue: "What if it's a typedef in a library I don't control?"

I'm glad you asked, because I just spent a couple of hours cooking up a solution (which I then had to throw away, because it didn't solve my actual problem).

You can use this handy maxof macro to determine the size of any valid integer type.

#define issigned(t) (((t)(-1)) < ((t) 0))

#define umaxof(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | \
                    (0xFULL << ((sizeof(t) * 8ULL) - 4ULL)))

#define smaxof(t) (((0x1ULL << ((sizeof(t) * 8ULL) - 1ULL)) - 1ULL) | \
                    (0x7ULL << ((sizeof(t) * 8ULL) - 4ULL)))

#define maxof(t) ((unsigned long long) (issigned(t) ? smaxof(t) : umaxof(t)))

You can use it like so:

int main(int argc, char** argv) {
    printf("schar: %llx uchar: %llx\n", maxof(char), maxof(unsigned char));
    printf("sshort: %llx ushort: %llx\n", maxof(short), maxof(unsigned short));
    printf("sint: %llx uint: %llx\n", maxof(int), maxof(unsigned int));
    printf("slong: %llx ulong: %llx\n", maxof(long), maxof(unsigned long));
    printf("slong long: %llx ulong long: %llx\n",
           maxof(long long), maxof(unsigned long long));
    return 0;
}

If you'd like, you can toss a '(t)' onto the front of those macros so they give you a result of the type that you're asking about, and you don't have to do casting to avoid warnings.

How to call a View Controller programmatically?

Swift

This gets a view controller from the storyboard and presents it.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewControllerId") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)

Change the storyboard name, view controller name, and view controller id as appropriate.

Convert Text to Date?

This code is working for me

Dim N As Long, r As Range
N = Cells(Rows.Count, "B").End(xlUp).Row
For i = 1 To N
    Set r = Cells(i, "B")
    r.Value = CDate(r.Value)
Next i

Try it changing the columns to suit your sheet

How can I get Docker Linux container information from within the container itself?

awk -F'[:/]' '(($4 == "docker") && (lastId != $NF)) { lastId = $NF; print $NF; }' /proc/self/cgroup

How do I render a shadow?

I'm using Styled Components and created a helper function for myself.

It takes the given Android elevation and creates a fairly equivalent iOS shadow.

stylingTools.js

import { css } from 'styled-components/native';

/*
 REMINDER!!!!!!!!!!!!!
 Shadows do not show up on iOS if `overflow: hidden` is used.
 https://react-native.canny.io/feature-requests/p/shadow-does-not-appear-if-overflow-hidden-is-set-on-ios
*/

// eslint-disable-next-line import/prefer-default-export
export const crossPlatformElevation = (elevation: number = 0) => css`
  /* Android - native default is 4, we're setting to 0 to match iOS. */
  elevation: ${elevation};

  /* iOS - default is no shadow. Only add if above zero */
  ${elevation > 0
    && css`
      shadow-color: black;
      shadow-offset: 0px ${0.5 * elevation}px;
      shadow-opacity: 0.3;
      shadow-radius: ${0.8 * elevation}px;
    `}
`;

To use

import styled from 'styled-components/native';
import { crossPlatformElevation } from "../../lib/stylingTools";

export const ContentContainer = styled.View`
  background: white;
  ${crossPlatformElevation(10)};
`;