Programs & Examples On #Amazon simpledb

Highly available schema-less attribute database that is part of the Amazon Web Services offering. Enables storage and retrieval of named items consisting of one or more key/value string pairs organized into domains. Item retrieval is done either by item name gets or through a sql-like language. Pay for what you use model with no minimum fees or startup costs.

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

If you’re using TortoiseSVN…

From your commit window in the “Changes Made” section you can select all the offending files, then right-click and select delete. Finish the commit and the files will be removed from the scheduled additions.

In Java, how to append a string more efficiently?

java.lang.StringBuilder. Use int constructor to create an initial size.

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

How do I link to Google Maps with a particular longitude and latitude?

To open the google maps app in android:-

geo:<lat>,<lng>?z=<zoom>

open app with marker for give location:-

geo:<lat>,<lng>?q=<lat>,<lng>(Label,Name)

open google map in ios:-

comgooglemaps://?q=<lat>,<lng>

open google maps in browser with following parameters:-

http://maps.google.com/maps?z=12&t=m&q=<lat>,<lng>
  • z is the zoom level (1-21)
  • t is the map type ("m" map, "k" satellite, "h" hybrid, "p" terrain, "e" GoogleEarth)
  • q is the search query

How to use an existing database with an Android application

I had trouble with the other DatabaseHelpers regarding this problem, not sure why.
This is what worked for me:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

  private static final String TAG = DatabaseHelper.class.getSimpleName();

  private final Context context;
  private final String assetPath;
  private final String dbPath;

  public DatabaseHelper(Context context, String dbName, String assetPath)
      throws IOException {
    super(context, dbName, null, 1);
    this.context = context;
    this.assetPath = assetPath;
    this.dbPath = "/data/data/"
        + context.getApplicationContext().getPackageName() + "/databases/"
        + dbName;
    checkExists();
  }

  /**
   * Checks if the database asset needs to be copied and if so copies it to the
   * default location.
   * 
   * @throws IOException
   */
  private void checkExists() throws IOException {
    Log.i(TAG, "checkExists()");

    File dbFile = new File(dbPath);

    if (!dbFile.exists()) {

      Log.i(TAG, "creating database..");

      dbFile.getParentFile().mkdirs();
      copyStream(context.getAssets().open(assetPath), new FileOutputStream(
          dbFile));

      Log.i(TAG, assetPath + " has been copied to " + dbFile.getAbsolutePath());
    }

  }

  private void copyStream(InputStream is, OutputStream os) throws IOException {
    byte buf[] = new byte[1024];
    int c = 0;
    while (true) {
      c = is.read(buf);
      if (c == -1)
        break;
      os.write(buf, 0, c);
    }
    is.close();
    os.close();
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
}

What does asterisk * mean in Python?

A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.

Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.

def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...

Difference between a User and a Login in SQL Server

I think this is a very useful question with good answer. Just to add my two cents from the MSDN Create a Login page:

A login is a security principal, or an entity that can be authenticated by a secure system. Users need a login to connect to SQL Server. You can create a login based on a Windows principal (such as a domain user or a Windows domain group) or you can create a login that is not based on a Windows principal (such as an SQL Server login).

Note:
To use SQL Server Authentication, the Database Engine must use mixed mode authentication. For more information, see Choose an Authentication Mode.

As a security principal, permissions can be granted to logins. The scope of a login is the whole Database Engine. To connect to a specific database on the instance of SQL Server, a login must be mapped to a database user. Permissions inside the database are granted and denied to the database user, not the login. Permissions that have the scope of the whole instance of SQL Server (for example, the CREATE ENDPOINT permission) can be granted to a login.

How do I do a not equal in Django queryset filtering?

Pending design decision. Meanwhile, use exclude()

The Django issue tracker has the remarkable entry #5763, titled "Queryset doesn't have a "not equal" filter operator". It is remarkable because (as of April 2016) it was "opened 9 years ago" (in the Django stone age), "closed 4 years ago", and "last changed 5 months ago".

Read through the discussion, it is interesting. Basically, some people argue __ne should be added while others say exclude() is clearer and hence __ne should not be added.

(I agree with the former, because the latter argument is roughly equivalent to saying Python should not have != because it has == and not already...)

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

I know this is a very old question, but I've been asked by someone else something similar.

I don't have TeraData, but can't you do the following?

SELECT employee_number,
       course_code,
       MAX(course_completion_date)                                     AS max_course_date,
       MAX(course_completion_date) OVER (PARTITION BY employee_number) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

The GROUP BY now ensures one row per course per employee. This means that you just need a straight MAX() to get the max_course_date.

Before your GROUP BY was just giving one row per employee, and the MAX() OVER() was trying to give multiple results for that one row (one per course).

Instead, you now need the OVER() clause to get the MAX() for the employee as a whole. This is now legitimate because each individual row gets just one answer (as it is derived from a super-set, not a sub-set). Also, for the same reason, the OVER() clause now refers to a valid scalar value, as defined by the GROUP BY clause; employee_number.


Perhaps a short way of saying this would be that an aggregate with an OVER() clause must be a super-set of the GROUP BY, not a sub-set.

Create your query with a GROUP BY at the level that represents the rows you want, then specify OVER() clauses if you want to aggregate at a higher level.

SQL get the last date time record

SELECT TOP 1 * FROM foo ORDER BY Dates DESC

Will return one result with the latest date.

SELECT * FROM foo WHERE foo.Dates = (SELECT MAX(Dates) FROM foo)

Will return all results that have the same maximum date, to the milissecond.

This is for SQL Server. I'll leave it up to you to use the DATEPART function if you want to use dates but not times.

Convert a CERT/PEM certificate to a PFX certificate

Here is how to do this on Windows without third-party tools:

  1. Import certificate to the certificate store. In Windows Explorer select "Install Certificate" in context menu. enter image description here Follow the wizard and accept default options "Local User" and "Automatically".

  2. Find your certificate in certificate store. On Windows 10 run the "Manage User Certificates" MMC. On Windows 2013 the MMC is called "Certificates". On Windows 10 by default your certificate should be under "Personal"->"Certificates" node.

  3. Export Certificate. In context menu select "Export..." menu: enter image description here

    Select "Yes, export the private key": enter image description here

    You will see that .PFX option is enabled in this case: enter image description here

    Specify password for private key.

Efficient way to update all rows in a table

You could drop any indexes on the table, then do your insert, and then recreate the indexes.

Delete last N characters from field in a SQL Server database

This should do it, removing characters from the left by one or however many needed.

lEFT(columnX,LEN(columnX) - 1) AS NewColumnName

How to use greater than operator with date?

In my case my column was a datetime it kept giving me all records. What I did is to include time, see below example

SELECT * FROM my_table where start_date > '2011-01-01 01:01:01';

Media Queries - In between two widths

_x000D_
_x000D_
.class {_x000D_
    display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
    .class {_x000D_
        display: block; /* just an example display property */_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Regarding C++ Include another class

you need to forward declare the name of the class if you don't want a header:

class ClassTwo;

Important: This only works in some cases, see Als's answer for more information..

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:

select Detail.ReceiptDate AS 'DATE',
       SUM(TotalMailed),
       SUM(TotalReturnMail),
       SUM(TraceReturnedMail)

from
(

select SentDate AS 'ReceiptDate', 
       count('TotalMailed') AS TotalMailed, 
       0 as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate

UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       count(TotalReturnMail) as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY  MDE.ReturnMailDate

UNION ALL

select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       0 as TotalReturnMail, 
       count(TraceReturnedMail) as TraceReturnedMail

from MailDataExtract MDE
    inner join DTSharedData.dbo.ScanData SD 
        ON SD.ScanDataID = MDE.ReturnScanDataID
   where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate

) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1

select a value where it doesn't exist in another table

This would select 4 in your case

SELECT ID FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)

This would delete them

DELETE FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)

How to get the height of a body element

Set

html { height: 100%; }
body { min-height: 100%; }

instead of height: 100%.

The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.

What is the difference between Step Into and Step Over in a debugger

Step Into The next expression on the currently-selected line to be executed is invoked, and execution suspends at the next executable line in the method that is invoked.

Step Over The currently-selected line is executed and suspends on the next executable line.

Changing every value in a hash in Ruby

One method that doesn't introduce side-effects to the original:

h = {:a => 'a', :b => 'b'}
h2 = Hash[h.map {|k,v| [k, '%' + v + '%']}]

Hash#map may also be an interesting read as it explains why the Hash.map doesn't return a Hash (which is why the resultant Array of [key,value] pairs is converted into a new Hash) and provides alternative approaches to the same general pattern.

Happy coding.

[Disclaimer: I am not sure if Hash.map semantics change in Ruby 2.x]

Can two applications listen to the same port?

You can make two applications listen for the same port on the same network interface.

There can only be one listening socket for the specified network interface and port, but that socket can be shared between several applications.

If you have a listening socket in an application process and you fork that process, the socket will be inherited, so technically there will be now two processes listening the same port.

How to recover a dropped stash in Git?

I want to add to the accepted solution another good way to go through all the changes, when you either don't have gitk available or no X for output.

git fsck --no-reflog | awk '/dangling commit/ {print $3}' > tmp_commits

for h in `cat tmp_commits`; do git show $h | less; done

Then you get all the diffs for those hashes displayed one after another. Press 'q' to get to the next diff.

How to auto adjust the <div> height according to content in it?

simply set the height to auto, that should fix the problem, because div are block elements so they stretch out to full width and height of any element contained in it. if height set to auto not working then simple don't add the height, it should adjust and make sure that the div is not inheriting any height from it's parent element as well...

How to remove a class from elements in pure JavaScript?

This might help

let allElements = Array.from(document.querySelectorAll('.widget.hover'))
for (let element of allElements) {
  element.classList.remove('hover')
}

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

1) Add the following line to /etc/security/limits.conf

webuser hard nofile 64000

then login as webuser

su - webuser

2) Edit following two files for webuser

append .bashrc and .bash_profile file by running

echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile

3) Log out, then log back in and verify that the changes have been made correctly:

$ ulimit -a | grep open
open files                      (-n) 64000

Thats it and them boom, boom boom.

Syntax error: Illegal return statement in JavaScript

If you want to return some value then wrap your statement in function

function my_function(){ 

 return my_thing; 
}

Problem is with the statement on the 1st line if you are trying to use PHP

var ask = confirm ('".$message."'); 

IF you are trying to use PHP you should use

 var ask = confirm (<?php echo "'".$message."'" ?>); //now message with be the javascript string!!

Center Triangle at Bottom of Div

Can't you just set left to 50% and then have margin-left set to -25px to account for it's width: http://jsfiddle.net/9AbYc/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to change a field name in JSON using Jackson

Be aware that there is org.codehaus.jackson.annotate.JsonProperty in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.

What is a stack trace, and how can I use it to debug my application errors?

The other posts describe what a stack trace is, but it can still be hard to work with.

If you get a stack trace and want to trace the cause of the exception, a good start point in understanding it is to use the Java Stack Trace Console in Eclipse. If you use another IDE there may be a similar feature, but this answer is about Eclipse.

First, ensure that you have all of your Java sources accessible in an Eclipse project.

Then in the Java perspective, click on the Console tab (usually at the bottom). If the Console view is not visible, go to the menu option Window -> Show View and select Console.

Then in the console window, click on the following button (on the right)

Consoles button

and then select Java Stack Trace Console from the drop-down list.

Paste your stack trace into the console. It will then provide a list of links into your source code and any other source code available.

This is what you might see (image from the Eclipse documentation):

Diagram from Eclipse documentation

The most recent method call made will be the top of the stack, which is the top line (excluding the message text). Going down the stack goes back in time. The second line is the method that calls the first line, etc.

If you are using open-source software, you might need to download and attach to your project the sources if you want to examine. Download the source jars, in your project, open the Referenced Libraries folder to find your jar for your open-source module (the one with the class files) then right click, select Properties and attach the source jar.

VMware Workstation and Device/Credential Guard are not compatible

If you are someone who maintains an open customized "Run as administrator" command prompt or powershell command line window at all the times you can optionally setup the following aliases / macros to simplify executing the commands mentioned by @gue22 for simply disabling hyper-v hypervisor when needing to use vmware player or workstation and then enabling it again when done.

doskey hpvEnb = choice /c:yn /cs /d n /t 30 /m "Are you running from elevated command prompt" ^& if not errorlevel 2 ( bcdedit /set hypervisorlaunchtype auto ^& echo.^&echo now reboot to enable hyper-v hypervisor )
doskey hpvDis = choice /c:yn /cs /d n /t 30 /m "Are you running from elevated command prompt" ^& if not errorlevel 2 ( bcdedit /set hypervisorlaunchtype off ^& echo.^&echo now reboot to disable hyper-v hypervisor )
doskey bcdL = bcdedit /enum ^& echo.^&echo now see boot configuration data store {current} boot loader settings

With the above in place you just type "hpvenb" [ hypervisor enabled at boot ], "hpvdis" [ hypervisor disabled at boot ] and "bcdl" [ boot configuration devices list ] commands to execute the on, off, list commands.

Using CSS to align a button bottom of the screen using relative positions

This will work for any resolution,

button{
    position:absolute;
    bottom: 5%;
    right:20%;
}

http://jsfiddle.net/BUuSr/

How do you clear your Visual Studio cache on Windows Vista?

The accepted answer gave two locations:

here

C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache

and possibly here

C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache

Did you try those?

Edited to add

On my Windows Vista machine, it's located in

%Temp%\VWDWebCache

and in

%LocalAppData%\Microsoft\WebsiteCache

From your additional information (regarding team edition) this comes from Clear Client TFS Cache:

Clear Client TFS Cache

Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.

To solve it..

For Windows Vista delete contents of this folder

%LocalAppData%\Microsoft\Team Foundation\1.0\Cache

PHP - how to create a newline character?

Actually \r\n is for the html side of the output. With those chars you can just create a newline in the html code to make it more readable:

echo "<html>First line \r\n Second line</html>";

will output:

<html>First line
Second line</html>

that viewing the page will be:

First line Second line

If you really meant this you have just to fix the single quote with the "" quote:

echo "\r\n";

Otherwise if you mean to split the text, in our sample 'First line' and 'Second line' you have to use the html code: <br />:

First line<br />Second line

that will output:

First line
Second line

Also it would be more readable if you replace the entire script with:

echo "$clientid $lastname \r\n";

Return list using select new in LINQ

try this solution for me its working

     public List<ProjectInfo> GetProjectForCombo()
      {
    using (MyDataContext db = new MyDataContext 
    (DBHelper.GetConnectionString()))
         {
        return  (from pro in db.Projects
                    select new { query  }.query).ToList();
        }
      }

What does "javascript:void(0)" mean?

Usage of javascript:void(0) means that the author of the HTML is misusing the anchor element in place of the button element.

Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. These values cause unexpected behavior when copying/dragging links, opening links in a new tabs/windows, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a <button> instead. In general you should only use an anchor for navigation using a proper URL.

Source: MDN's <a> Page.

Get a DataTable Columns DataType

You could always use typeof in the if statement. It is better than working with string values like the answer of Natarajan.

if (dt.Columns[0].DataType == typeof(DateTime))
{
}

Python Pandas iterate over rows and access column names

How to iterate efficiently

If you really have to iterate a Pandas dataframe, you will probably want to avoid using iterrows(). There are different methods and the usual iterrows() is far from being the best. itertuples() can be 100 times faster.

In short:

  • As a general rule, use df.itertuples(name=None). In particular, when you have a fixed number columns and less than 255 columns. See point (3)
  • Otherwise, use df.itertuples() except if your columns have special characters such as spaces or '-'. See point (2)
  • It is possible to use itertuples() even if your dataframe has strange columns by using the last example. See point (4)
  • Only use iterrows() if you cannot the previous solutions. See point (1)

Different methods to iterate over rows in a Pandas dataframe:

Generate a random dataframe with a million rows and 4 columns:

    df = pd.DataFrame(np.random.randint(0, 100, size=(1000000, 4)), columns=list('ABCD'))
    print(df)

1) The usual iterrows() is convenient, but damn slow:

start_time = time.clock()
result = 0
for _, row in df.iterrows():
    result += max(row['B'], row['C'])

total_elapsed_time = round(time.clock() - start_time, 2)
print("1. Iterrows done in {} seconds, result = {}".format(total_elapsed_time, result))

2) The default itertuples() is already much faster, but it doesn't work with column names such as My Col-Name is very Strange (you should avoid this method if your columns are repeated or if a column name cannot be simply converted to a Python variable name).:

start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row.B, row.C)

total_elapsed_time = round(time.clock() - start_time, 2)
print("2. Named Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))

3) The default itertuples() using name=None is even faster but not really convenient as you have to define a variable per column.

start_time = time.clock()
result = 0
for(_, col1, col2, col3, col4) in df.itertuples(name=None):
    result += max(col2, col3)

total_elapsed_time = round(time.clock() - start_time, 2)
print("3. Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))

4) Finally, the named itertuples() is slower than the previous point, but you do not have to define a variable per column and it works with column names such as My Col-Name is very Strange.

start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])

total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))

Output:

         A   B   C   D
0       41  63  42  23
1       54   9  24  65
2       15  34  10   9
3       39  94  82  97
4        4  88  79  54
...     ..  ..  ..  ..
999995  48  27   4  25
999996  16  51  34  28
999997   1  39  61  14
999998  66  51  27  70
999999  51  53  47  99

[1000000 rows x 4 columns]

1. Iterrows done in 104.96 seconds, result = 66151519
2. Named Itertuples done in 1.26 seconds, result = 66151519
3. Itertuples done in 0.94 seconds, result = 66151519
4. Polyvalent Itertuples working even with special characters in the column name done in 2.94 seconds, result = 66151519

This article is a very interesting comparison between iterrows and itertuples

MySQL error 1449: The user specified as a definer does not exist

If the user exists, then:

mysql> flush privileges;

Can I define a class name on paragraph using Markdown?

It should also be mentioned that <span> tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...

This is a superfluous paragraph thing.

<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>

And thus with that I conclude.

I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.

Is an empty href valid?

Although this question is already answered (tl;dr: yes, an empty href value is valid), none of the existing answers references the relevant specifications.

An empty string can’t be a URI. However, the href attribute doesn’t only take URIs as value, but also URI references. An empty string may be a URI reference.

HTML 4.01

HTML 4.01 uses RFC 2396, where it says in section 4.2. Same-document References (bold emphasis mine):

A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document.

RFC 2396 is obsoleted by RFC 3986 (which is currently IETF’s URI standard), which essentially says the same.

HTML5

HTML5 uses (valid URL potentially surrounded by spaces ? valid URL) W3C’s URL spec, which has been discontinued. WHATWG’s URL Standard should be used instead (see the last section).

HTML 5.1

HTML 5.1 uses (valid URL potentially surrounded by spaces ? valid URL) WHATWG’s URL Standard (see the next section).

WHATWG HTML

WHATWG’s HTML uses (valid URL potentially surrounded by spaces) the definition of valid URL string from WHATWG’s URL Standard, where it says that it can be a relative-URL-with-fragment string, which must at least be a relative-URL string, which can be a path-relative-scheme-less-URL string, which is a path-relative-URL string that doesn’t start with a scheme string followed by :, and its definition says (bold emphasis mine):

A path-relative-URL string must be zero or more URL-path-segment strings, separated from each other by U+002F (/), and not start with U+002F (/).

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Have you tried editing the shell entry in account settings.

Go to the Accounts preferences, unlock, and right-click on your user account for the Advanced Settings dialog. Your shell should be /bin/zsh, and you can edit that invocation appropriately (i.e. add the --login argument).

How to split a string in shell and get the last field

echo "a:b:c:d:e"|xargs -d : -n1|tail -1

First use xargs split it using ":",-n1 means every line only have one part.Then,pring the last part.

How to get access to raw resources that I put in res folder?

This worked for for me: getResources().openRawResource(R.raw.certificate)

DateTime fields from SQL Server display incorrectly in Excel

Here's a simple macro that can be run after pasting data from SSMS. It's easiest if you copy it to your PERSONAL.XLSB file and add a button to the Quick Access Toolbar or a new custom group/tab in the ribbon. Run the macro immediately after pasting while the data is still selected. It can also be run if a single cell is selected within the data - it will automatically select the current area before running (same as ctrl-a). To run the macro on only a subset of data, select the desired subset before running. It can handle the data including or excluding headers, but assumes there at at least 2 rows in the current area.

It efficiently tests each column to see if the first non-NULL value looks to be a date/time value in the strange format. If it is, it sets the entire column to the default system date/time format, even if your date format is 'd/m/y'.

Sub FixSSMSDateFormats()

'Intended for copied data from SSMS and handles headers included
'For selection or current area, checks each column...
'   If the first non-NULL value is in strange time format, then change entire column to system date/time format

Dim values As Variant, r As Long, c As Long

If Selection.Count = 1 Then Selection.CurrentRegion.Select

values = Selection.Value

For c = 1 To UBound(values, 2)

    For r = 2 To UBound(values, 1)
    
        If TypeName(values(r, c)) = "Double" Then
            If values(r, c) > 1 And Selection(r, c).NumberFormat = "mm:ss.0" Then
                Selection.Columns(c).NumberFormat = "m/d/yyyy h:mm"
            End If
            Exit For
        ElseIf values(r, c) <> "NULL" Then
            Exit For
        End If
    
    Next

Next

End Sub

Returning value from Thread

Usually you would do it something like this

 public class Foo implements Runnable {
     private volatile int value;

     @Override
     public void run() {
        value = 2;
     }

     public int getValue() {
         return value;
     }
 }

Then you can create the thread and retrieve the value (given that the value has been set)

Foo foo = new Foo();
Thread thread = new Thread(foo);
thread.start();
thread.join();
int value = foo.getValue();

tl;dr a thread cannot return a value (at least not without a callback mechanism). You should reference a thread like an ordinary class and ask for the value.

How To change the column order of An Existing Table in SQL Server 2008

This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).

Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.

The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:

a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns

OR

b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along

The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.

I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue

How do I remove trailing whitespace using a regular expression?

[ |\t]+$ with an empty replace works. \s+($) with a $1 replace also works. At least in Visual Studio Code...

Android: why is there no maxHeight for a View?

if you guys want to make a non-overflow scrollview or listview, just but it on a RelativeLayout with a topview and bottomview on top and bottom for it:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/topview"
    android:layout_below="@+id/bottomview" >

JPA - Returning an auto generated id after persist()

em.persist(abc);
em.refresh(abc);
return abc;

Using Math.round to round to one decimal place?

Your method is right, all you have to do is add a .0 after both the tens and it will fix your problem!

double example = Math.round((187/35) * 10.0) / 10.0;

The output would be:

5.3

How to mock location on device?

I wrote an App that runs a WebServer (REST-Like) on your Android Phone, so you can set the GPS position remotely. The website provides an Map on which you can click to set a new position, or use the "wasd" keys to move in any direction. The app was a quick solution so there is nearly no UI nor Documentation, but the implementation is straight forward and you can look everything up in the (only four) classes.

Project repository: https://github.com/juliusmh/RemoteGeoFix

How to change progress bar's progress color in Android

ProgressBar bar;

private Handler progressBarHandler = new Handler();

GradientDrawable progressGradientDrawable = new GradientDrawable(
        GradientDrawable.Orientation.LEFT_RIGHT, new int[]{
                0xff1e90ff,0xff006ab6,0xff367ba8});
ClipDrawable progressClipDrawable = new ClipDrawable(
        progressGradientDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
Drawable[] progressDrawables = {
        new ColorDrawable(0xffffffff),
        progressClipDrawable, progressClipDrawable};
LayerDrawable progressLayerDrawable = new LayerDrawable(progressDrawables);


int status = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // TODO Auto-generated method stub
    setContentView(R.layout.startup);

    bar = (ProgressBar) findViewById(R.id.start_page_progressBar);
    bar.setProgress(0);
    bar.setMax(100);

    progressLayerDrawable.setId(0, android.R.id.background);
    progressLayerDrawable.setId(1, android.R.id.secondaryProgress);
    progressLayerDrawable.setId(2, android.R.id.progress);

    bar.setProgressDrawable(progressLayerDrawable);
}

This helped me to set a custom color to progressbar through code. Hope it helps

If Browser is Internet Explorer: run an alternative script instead

You can do something like this to include IE-specific javascript:

<!--[IF IE]>
    <script type="text/javascript">
        // IE stuff
    </script>
<![endif]-->

Get the short Git version hash

I have Git version 2.7.4 with the following settings:

git config --global log.abbrevcommit yes
git config --global core.abbrev 8

Now when I do:

git log --pretty=oneline

I get an abbreviated commit id of eight digits:

ed054a38 add project based .gitignore
30a3fa4c add ez version
0a6e9015 add logic for shifting days
af4ab954 add n days ago
...

Python def function: How do you specify the end of the function?

Python is white-space sensitive in regard to the indentation. Once the indentation level falls back to the level at which the function is defined, the function has ended.

Return a value of '1' a referenced cell is empty

Since required quite often it might as well be brief:

=1*(A1="")

This will not return 1 if the cell appears empty but contains say a space or a formula of the kind =IF(B1=3,"Yes","") where B1 does not contain 3.

=A1="" will return either TRUE or FALSE but those in an equation are treated as 1 and 0 respectively so multiplying TRUE by 1 returns 1.

Much the same can be achieved with the double unary --:

=--(A1="")  

where when A1 is empty one minus negates TRUE into -1 and the other negates that to 1 (just + in place of -- however does not change TRUE to 1).

How can I convert a std::string to int?

If you wot hard code :)

bool strCanBeInt(std::string string){
    for (char n : string) {
        if (n != '0' && n != '1' && n != '2' && n != '3' && n != '4' && n != '5'
            && n != '6' && n != '7' && n != '8' && n != '9') {
            return false;
        }
    }
    return true;
}

int strToInt(std::string string) {
    int integer = 0;
    int numInt;
    for (char n : string) {
        if(n == '0') numInt = 0;
        if(n == '1') numInt = 1;
        if(n == '2') numInt = 2;
        if(n == '3') numInt = 3;
        if(n == '4') numInt = 4;
        if(n == '5') numInt = 5;
        if(n == '6') numInt = 6;
        if(n == '7') numInt = 7;
        if(n == '8') numInt = 8;
        if(n == '9') numInt = 9;
        if (integer){
            integer *= 10;
        }
        integer += numInt;
    }
    return integer;
}

Trigger back-button functionality on button click in Android

If you are inside the fragment then you write the following line of code inside your on click listener, getActivity().onBackPressed(); this works perfectly for me.

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

It should also be noted that one key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the top level package. It shares a format with npm-shrinkwrap.json(5), which is essentially the same file, but allows publication. This is not recommended unless deploying a CLI tool or otherwise using the publication process for producing production packages.

If both package-lock.json and npm-shrinkwrap.json are present in the root of a package, package-lock.json will be completely ignored.

Progress Bar with HTML and CSS

_x000D_
_x000D_
#progressbar {_x000D_
  background-color: black;_x000D_
  border-radius: 13px;_x000D_
  /* (height of inner div) / 2 + padding */_x000D_
  padding: 3px;_x000D_
}_x000D_
_x000D_
#progressbar>div {_x000D_
  background-color: orange;_x000D_
  width: 40%;_x000D_
  /* Adjust with JavaScript */_x000D_
  height: 20px;_x000D_
  border-radius: 10px;_x000D_
}
_x000D_
<div id="progressbar">_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

(EDIT: Changed Syntax highlight; changed descendant to child selector)

Check for false

Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.

if(!(borrar() === false))

or

if(borrar() === true)

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

Intellij idea subversion checkout error: `Cannot run program "svn"`

Check my solution, It will work.

Solutions:

First Download Subversion 1.8.13 ( 1.8 ) Download link ( https://www.visualsvn.com/downloads/ )

enter image description here

Then unzipped in a folder. There will have one folder "bin".

Then

Go to settings - > Version control -> Subversion

Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.

follow the pic:

enter image description here

Don't forget to give the end name like svn.exe last as per image.

Apply -> Ok

Restart your android studio now.

Happy Coding!

Resource files not found from JUnit test cases

My mistake, the resource files WERE actually copied to target/test-classes. The problem seemed to be due to spaces in my project name, e.g. Project%20Name.

I'm now loading the file as follows and it works:

org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);

Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):

myClass().getResource("resourceFile.txt")??.toURI();

ASP.net vs PHP (What to choose)

There are a couple of topics that might provide you with an answer. You could also run some tests yourself. Doesn't see too hard to get some loops started and adding a timer to calculate the execution time ;-)

how to get the value of css style using jquery

I doubt css understands left by itself. You need to use it specifying position. You are using .css() correctly

position: relative/absolute/whatever;
left: 900px;

heres a fiddle of it working

http://jsfiddle.net/gFLZe/

and without the position here's what you get

http://jsfiddle.net/gkkm5/

Change your if statement to be like this - with quotes around -900px

var n = $("items").css("left");

if(n == '-900px'){
    $(".items span").fadeOut("slow");
}

http://jsfiddle.net/gFLZe/1/

String field value length in mongoDB

Here is one of the way in mongodb you can achieve this.

db.usercollection.find({ $where: 'this.name.length < 4' })

How to change resolution (DPI) of an image?

DPI should not be stored in an bitmap image file, as most sources of data for bitmaps render it meaningless.

A bitmap image is stored as pixels. Pixels have no inherent size in any respect. It's only at render time - be it monitor, printer, or automated crossstitching machine - that DPI matters.

A 800x1000 pixel bitmap image, printed at 100 dpi, turns into a nice 8x10" photo. Printed at 200 dpi, the EXACT SAME bitmap image turns into a 4x5" photo.

Capture an image with a digital camera, and what does DPI mean? It's certainly not the size of the area focused onto the CCD imager - that depends on the distance, and with NASA returning images of galaxies that are 100,000 light years across, and 2 million light years apart, in the same field of view, what kind of DPI do you get from THAT information?

Don't fall victim to the idea of the DPI of a bitmap image - it's a mistake. A bitmap image has no physical dimensions (save for a few micrometers of storage space in RAM or hard drive). It's only a displayed image, or a printed image, that has a physical size in inches, or millimeters, or furlongs.

Java default constructor

A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.

Per The Java Language Specification Third Edition:

8.8.9 Default Constructor

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided...

Catch KeyError in Python

Try print(e.message) this should be able to print your exception.

try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print(e.message)

Automatically scroll down chat div

Dont have to mix jquery and javascript. Use like this,

function getMessages(letter) {
    var message=$('#messages');
    $.get('msg_show.php', function(data) {
        message.html(data);
        message.scrollTop(message[0].scrollHeight);
    });
}

setInterval(function() {
    getMessages("letter");
}, 100)

Put the scrollTop() inside get() method.

Also you missed a parameter in the getMessage method call..

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

I encountered the same problem using Siebel REXPIMP (registry import) when using the latest Instant Client driver. To fix the issues, use the Siebel provided Data Direct driver instead. The DLL is SEOR823.DLL

How do I provide a username and password when running "git clone [email protected]"?

I prefer to use GIT_ASKPASS environment for providing HTTPS credentials to git.
Provided that login and password are exported in USR and PSW variables, the following script does not leave traces of password in history and disk + it is not vulnerable to special characters in the password:

GIT_ASKPASS=$(mktemp) && chmod a+rx $GIT_ASKPASS && export GIT_ASKPASS

cat > $GIT_ASKPASS <<'EOF'
#!/bin/sh
exec echo "$PSW"
EOF

git clone https://${USR}@example.com/repo.git

Note single quotes around heredoc marker 'EOF' which means that temporary script holds literally $PSW characters, not the password

What is the way of declaring an array in JavaScript?

If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length); is appropriate.

eg-

String.prototype.repeat= function(n){
    n= n || 1;
    return Array(n+1).join(this);
}

Clear contents of cells in VBA using column reference

I just came up with this very simple method of clearing an entire sheet.

Sub ClearThisSheet()

ActiveSheet.UsedRange.ClearContents

End Sub

C++ initial value of reference to non-const must be an lvalue

When you call test with &nKByte, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.

Either do not use a reference for the argument, or better yet don't use a pointer.

cat, grep and cut - translated to python

For Translating the command to python refer below:-

1)Alternative of cat command is open refer this. Below is the sample

>>> f = open('workfile', 'r')
>>> print f

2)Alternative of grep command refer this

3)Alternative of Cut command refer this

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

In my case, resetting ADB didn't make a difference. I also needed to delete my existing virtual devices, which were pretty old, and create new ones.

Find out which remote branch a local branch is tracking

git branch -vv | grep 'BRANCH_NAME'

git branch -vv : This part will show all local branches along with their upstream branch .

grep 'BRANCH_NAME' : It will filter the current branch from the branch list.

How to connect to Mysql Server inside VirtualBox Vagrant?

Here are the steps that worked for me after logging into the box:

Locate MySQL configuration file:

$ mysql --help | grep -A 1 "Default options"

Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf

On Ubuntu 16, the path is typically /etc/mysql/mysql.conf.d/mysqld.cnf

Change configuration file for bind-address:

If it exists, change the value as follows. If it doesn't exist, add it anywhere in the [mysqld] section.

bind-address = 0.0.0.0

Save your changes to the configuration file and restart the MySQL service.

service mysql restart

Create / Grant access to database user:

Connect to the MySQL database as the root user and run the following SQL commands:

mysql> CREATE USER 'username'@'%' IDENTIFIED BY 'password';

mysql> GRANT ALL PRIVILEGES ON mydb.* TO 'username'@'%';

cocoapods - 'pod install' takes forever

Just go through the below step-by-step:

Download https://github.com/CocoaPods/Specs/archive/master.zip

RUN the Below commands in terminal:

pod setup --verbose

Open new tab in the terminal and RUN

mv ~/.cocoapods/repos/master/.git ~/tempSpecsGitFolder

open master.zip (unzipping it)

mv Specs-master ~/.cocoapods/repos/master

mv ~/tempSpecsGitFolder ~/.cocoapods/repos/master/.git

cd [project folder]

pod install --no-repo-update

Address already in use: JVM_Bind

As an aside, under Windows, ProcessExplorer is fantastic for observing the existing TCP/IP connections for each process.

Getting a union of two arrays in JavaScript

I would first concatenate the arrays, then I would return only the unique value.

You have to create your own function to return unique values. Since it is a useful function, you might as well add it in as a functionality of the Array.

In your case with arrays array1 and array2 it would look like this:

  1. array1.concat(array2) - concatenate the two arrays
  2. array1.concat(array2).unique() - return only the unique values. Here unique() is a method you added to the prototype for Array.

The whole thing would look like this:

_x000D_
_x000D_
Array.prototype.unique = function () {_x000D_
    var r = new Array();_x000D_
    o: for(var i = 0, n = this.length; i < n; i++)_x000D_
    {_x000D_
        for(var x = 0, y = r.length; x < y; x++)_x000D_
        {_x000D_
            if(r[x]==this[i])_x000D_
            {_x000D_
                continue o;_x000D_
            }_x000D_
        }_x000D_
        r[r.length] = this[i];_x000D_
    }_x000D_
    return r;_x000D_
}_x000D_
var array1 = [34,35,45,48,49];_x000D_
var array2 = [34,35,45,48,49,55];_x000D_
_x000D_
// concatenate the arrays then return only the unique values_x000D_
console.log(array1.concat(array2).unique());
_x000D_
_x000D_
_x000D_

json call with C#

Its just a sample of how to post Json data and get Json data to/from a Rest API in BIDS 2008 using System.Net.WebRequest and without using newtonsoft. This is just a sample code and definitely can be fine tuned (well tested and it works and serves my test purpose like a charm). Its just to give you an Idea. I wanted this thread but couldn't find hence posting this.These were my major sources from where I pulled this. Link 1 and Link 2

Code that works(unit tested)

           //Get Example
            var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "GET";

            var username = "usernameForYourApi";
            var password = "passwordForYourApi";

            var bytes = Encoding.UTF8.GetBytes(username + ":" + password);
            httpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
            var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
            using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
                Dts.Events.FireInformation(3, "result from readng stream", result, "", 0, ref fireagain);
            }


            //Post Example
            var httpWebRequestPost = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
            httpWebRequestPost.ContentType = "application/json";
            httpWebRequestPost.Method = "POST";
            bytes = Encoding.UTF8.GetBytes(username + ":" + password);
            httpWebRequestPost.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));

            //POST DATA newtonsoft didnt worked with BIDS 2008 in this test package
            //json https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net
            // fill File model with some test data
            CSharpComplexClass fileModel = new CSharpComplexClass();
            fileModel.CarrierID = 2;
            fileModel.InvoiceFileDate = DateTime.Now;
            fileModel.EntryMethodID = EntryMethod.Manual;
            fileModel.InvoiceFileStatusID = FileStatus.NeedsReview;
            fileModel.CreateUserID = "37f18f01-da45-4d7c-a586-97a0277440ef";
            string json = new JavaScriptSerializer().Serialize(fileModel);
            Dts.Events.FireInformation(3, "reached json", json, "", 0, ref fireagain);
            byte[] byteArray = Encoding.UTF8.GetBytes(json);
            httpWebRequestPost.ContentLength = byteArray.Length;
            // Get the request stream.  
            Stream dataStream = httpWebRequestPost.GetRequestStream();
            // Write the data to the request stream.  
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.  
            dataStream.Close();
            // Get the response.  
            WebResponse response = httpWebRequestPost.GetResponse();
            // Display the status.  
            //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            Dts.Events.FireInformation(3, "Display the status", ((HttpWebResponse)response).StatusDescription, "", 0, ref fireagain);
            // Get the stream containing content returned by the server.  
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.  
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.  
            string responseFromServer = reader.ReadToEnd();
            Dts.Events.FireInformation(3, "responseFromServer ", responseFromServer, "", 0, ref fireagain);

References in my test script task inside BIDS 2008(having SP1 and 3.5 framework) enter image description here

How to fit in an image inside span tag?

Try this.

<span style="padding-right:3px; padding-top: 3px; display:inline-block;">

<img class="manImg" src="images/ico_mandatory.gif"></img>

</span>

TNS Protocol adapter error while starting Oracle SQL*Plus

You are getting ORA-12560: TNS:protocol adaptor error becuase you didn't start the Oracle database.

You can start Oracle database like this. From START-> select Oracle Database 11g Express Edition( 11g or what ever your database type.you can find this from All Programs). Then inside this folder there is a DB icon with green color spot.Start Database icon It is the Start Service icon.Click it.Then it will take some seconds and start the service. connection success

After getting the above message,again try to connect through the SQL plus command line by giving user name and password. enter image description here

Change the color of a bullet in a html list?

You could use CSS to attain this. By specifying the list in the color and style of your choice, you can then also specify the text as a different color.

Follow the example at http://www.echoecho.com/csslists.htm.

What does "if (rs.next())" mean?

First thing, you don't need to write

ResultSet rs = stmt.executeQuery(sql);

just write

ResultSet rs = stmt.executeQuery();

The above mentioned syntax is used for Statements not for PreparedStatement.

Second thing, rs.next() checks if the result set contains any values or not. It returns a boolean value as well as it moves the cursor to the first value in the result set because initially it is at BEFORE FIRST Position. So if you want to access first value in result set, you need to write rs.next().

How to enable C++17 compiling in Visual Studio?

Visual studio 2019 version:

The drop down menu was moved to:

  • Right click on project (not solution)
  • Properties (or Alt + Enter)
  • From the left menu select Configuration Properties
  • General
  • In the middle there is an option called "C++ Language Standard"
  • Next to it is the drop down menu
  • Here you can select Default, ISO C++ 14, 17 or latest

SQL Data Reader - handling Null column values

One way to do it is to check for db nulls:

employee.FirstName = (sqlreader.IsDBNull(indexFirstName) 
    ? ""
    : sqlreader.GetString(indexFirstName));

PHP regular expressions: No ending delimiter '^' found in

PHP regex strings need delimiters. Try:

$numpattern="/^([0-9]+)$/";

Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/.

Example: http://ideone.com/Ec3zh

See also: PHP - Delimiters

Support for "border-radius" in IE

<!DOCTYPE html> without this tag border-radius doesn't works in IE9, no need of meta tags.

Create Local SQL Server database

After installation you need to connect to Server Name : localhost to start using the local instance of SQL Server.

Once you are connected to the local instance, right click on Databases and create a new database.

Angularjs loading screen on ajax request

Also, there is a nice demo that shows how can you use Angularjs animation in your project.

The link is here (See the top left corner).

It's an open source. Here is the link to download

And here is the link for tutorial;

My point is, go ahead and download the source files and then see how they have implemented the spinner. They might have used a little better aproach. So, checkout this project.

How to use Lambda in LINQ select statement

Lambda Expression result

var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();

Reorder / reset auto increment primary key

To reset the IDs of my User table, I use the following SQL query. It's been said above that this will ruin any relationships you may have with any other tables.

ALTER TABLE `users` DROP `id`;
ALTER TABLE `users` AUTO_INCREMENT = 1;
ALTER TABLE `users` ADD `id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

Remove IE10's "clear field" X button on certain inputs?

I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:

input[type=text]::-ms-clear { display: none; }

One can even get less specific by using just:

::-ms-clear { display: none; }

I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.

What's the best strategy for unit-testing database-driven applications?

I'm always running tests against an in-memory DB (HSQLDB or Derby) for these reasons:

  • It makes you think which data to keep in your test DB and why. Just hauling your production DB into a test system translates to "I have no idea what I'm doing or why and if something breaks, it wasn't me!!" ;)
  • It makes sure the database can be recreated with little effort in a new place (for example when we need to replicate a bug from production)
  • It helps enormously with the quality of the DDL files.

The in-memory DB is loaded with fresh data once the tests start and after most tests, I invoke ROLLBACK to keep it stable. ALWAYS keep the data in the test DB stable! If the data changes all the time, you can't test.

The data is loaded from SQL, a template DB or a dump/backup. I prefer dumps if they are in a readable format because I can put them in VCS. If that doesn't work, I use a CSV file or XML. If I have to load enormous amounts of data ... I don't. You never have to load enormous amounts of data :) Not for unit tests. Performance tests are another issue and different rules apply.

Finding moving average from data points in Python

As numpy.convolve is pretty slow, those who need a fast performing solution might prefer an easier to understand cumsum approach. Here is the code:

cumsum_vec = numpy.cumsum(numpy.insert(data, 0, 0)) 
ma_vec = (cumsum_vec[window_width:] - cumsum_vec[:-window_width]) / window_width

where data contains your data, and ma_vec will contain moving averages of window_width length.

On average, cumsum is about 30-40 times faster than convolve.

Get all inherited classes of an abstract class

Assuming they are all defined in the same assembly, you can do:

IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
    .Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
    .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

How do I execute .js files locally in my browser?

Around 1:51 in the video, notice how she puts a <script> tag in there? The way it works is like this:

Create an html file (that's just a text file with a .html ending) somewhere on your computer. In the same folder that you put index.html, put a javascript file (that's just a textfile with a .js ending - let's call it game.js). Then, in your index.html file, put some html that includes the script tag with game.js, like Mary did in the video. index.html should look something like this:

<html>
    <head>
        <script src="game.js"></script>
    </head>
</html>

Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).

Good luck on your journey, hope it's as fun for you as it has been for me so far :)

Copying and pasting data using VBA code

Use the PasteSpecial method:

sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues

BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

insert echo into the specific html element like div which has an id or class

if yo want to place in an div like i have same work and i do it like

<div id="content>
<?php
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';  
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
?>
</div>

How to display multiple images in one figure correctly?

Here is my approach that you may try:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

The resulting image:

output_image

(Original answer date: Oct 7 '17 at 4:20)

Edit 1

Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-

  1. access to individual axes of subplots
  2. possibility to plot more features on selected axes/subplot

New code:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot

The resulting plot:

enter image description here

Edit 2

In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots.

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

The resulting plot:

plot3

Java: how do I check if a Date is within a certain range?

Doesnn't care which date boundry is which.

Math.abs(date1.getTime() - date2.getTime()) == 
    Math.abs(date1.getTime() - dateBetween.getTime()) + Math.abs(dateBetween.getTime() - date2.getTime());

Convert DataSet to List

I couldn't get Nitin Sawant's answer to work, but I was able to modify his code to work for me. Essentially I needed to use GetRuntimeFields instead of GetProperties. Here's what I ended up with:

public static class Extensions
{
    public static List<T> ToList<T>(this DataTable table) where T : new()
    {
        IList<FieldInfo> fields = typeof(T).GetRuntimeFields().ToList();
        List<T> result = new List<T>();
        if (row.Table.Columns.Contains(field.Name))
        {
            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, fields);
                result.Add(item);
            }
        }

        return result;
    }

    private static T CreateItemFromRow<T>(DataRow row, IList<FieldInfo> fields) where T : new()
    {
        T item = new T();

        foreach (var field in fields)
        {
            if (row[field.Name] == DBNull.Value)
                field.SetValue(item, null);
            else
                field.SetValue(item, row[field.Name]);
        }
        return item;
    }
}

mysql_config not found when installing mysqldb python interface

In centos 7 this works for me :

yum install mariadb-devel
pip install mysqlclient

MySQL: update a field only if condition is met

Another variation:

UPDATE test
SET field = IF ( {condition}, {new value}, field )
WHERE id = 123

This will update the field with {new value} only if {condition} is met

VBA Excel 2-Dimensional Arrays

In fact I would not use any REDIM, nor a loop for transferring data from sheet to array:

dim arOne()
arOne = range("A2:F1000")

or even

arOne = range("A2").CurrentRegion

and that's it, your array is filled much faster then with a loop, no redim.

Difference between text and varchar (character varying)

As "Character Types" in the documentation points out, varchar(n), char(n), and text are all stored the same way. The only difference is extra cycles are needed to check the length, if one is given, and the extra space and time required if padding is needed for char(n).

However, when you only need to store a single character, there is a slight performance advantage to using the special type "char" (keep the double-quotes — they're part of the type name). You get faster access to the field, and there is no overhead to store the length.

I just made a table of 1,000,000 random "char" chosen from the lower-case alphabet. A query to get a frequency distribution (select count(*), field ... group by field) takes about 650 milliseconds, vs about 760 on the same data using a text field.

How can I merge two MySQL tables?

If you need to do it manually, one time:

First, merge in a temporary table, with something like:

create table MERGED as select * from table 1 UNION select * from table 2

Then, identify the primary key constraints with something like

SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1

Where PK is the primary key field...

Solve the duplicates.

Rename the table.

[edited - removed brackets in the UNION query, which was causing the error in the comment below]

ReactJS Two components communicating

There are multiple ways to make components communicate. Some can be suited to your usecase. Here is a list of some I've found useful to know.

React

Parent / Child direct communication

const Child = ({fromChildToParentCallback}) => (
  <div onClick={() => fromChildToParentCallback(42)}>
    Click me
  </div>
);

class Parent extends React.Component {
  receiveChildValue = (value) => {
    console.log("Parent received value from child: " + value); // value is 42
  };
  render() {
    return (
      <Child fromChildToParentCallback={this.receiveChildValue}/>
    )
  }
}

Here the child component will call a callback provided by the parent with a value, and the parent will be able to get the value provided by the children in the parent.

If you build a feature/page of your app, it's better to have a single parent managing the callbacks/state (also called container or smart component), and all childs to be stateless, only reporting things to the parent. This way you can easily "share" the state of the parent to any child that need it.


Context

React Context permits to hold state at the root of your component hierarchy, and be able to inject this state easily into very deeply nested components, without the hassle to have to pass down props to every intermediate components.

Until now, context was an experimental feature, but a new API is available in React 16.3.

const AppContext = React.createContext(null)

class App extends React.Component {
  render() {
    return (
      <AppContext.Provider value={{language: "en",userId: 42}}>
        <div>
          ...
          <SomeDeeplyNestedComponent/>
          ...
        </div>
      </AppContext.Provider>
    )
  }
};

const SomeDeeplyNestedComponent = () => (
  <AppContext.Consumer>
    {({language}) => <div>App language is currently {language}</div>}
  </AppContext.Consumer>
);

The consumer is using the render prop / children function pattern

Check this blog post for more details.

Before React 16.3, I'd recommend using react-broadcast which offer quite similar API, and use former context API.


Portals

Use a portal when you'd like to keep 2 components close together to make them communicate with simple functions, like in normal parent / child, but you don't want these 2 components to have a parent/child relationship in the DOM, because of visual / CSS constraints it implies (like z-index, opacity...).

In this case you can use a "portal". There are different react libraries using portals, usually used for modals, popups, tooltips...

Consider the following:

<div className="a">
    a content
    <Portal target="body">
        <div className="b">
            b content
        </div>
    </Portal>
</div>

Could produce the following DOM when rendered inside reactAppContainer:

<body>
    <div id="reactAppContainer">
        <div className="a">
             a content
        </div>
    </div>
    <div className="b">
         b content
    </div>
</body>

More details here


Slots

You define a slot somewhere, and then you fill the slot from another place of your render tree.

import { Slot, Fill } from 'react-slot-fill';

const Toolbar = (props) =>
  <div>
    <Slot name="ToolbarContent" />
  </div>

export default Toolbar;

export const FillToolbar = ({children}) =>
  <Fill name="ToolbarContent">
    {children}
  </Fill>

This is a bit similar to portals except the filled content will be rendered in a slot you define, while portals generally render a new dom node (often a children of document.body)

Check react-slot-fill library


Event bus

As stated in the React documentation:

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event.

There are many things you can use to setup an event bus. You can just create an array of listeners, and on event publish, all listeners would receive the event. Or you can use something like EventEmitter or PostalJs


Flux

Flux is basically an event bus, except the event receivers are stores. This is similar to the basic event bus system except the state is managed outside of React

Original Flux implementation looks like an attempt to do Event-sourcing in a hacky way.

Redux is for me the Flux implementation that is the closest from event-sourcing, an benefits many of event-sourcing advantages like the ability to time-travel. It is not strictly linked to React and can also be used with other functional view libraries.

Egghead's Redux video tutorial is really nice and explains how it works internally (it really is simple).


Cursors

Cursors are coming from ClojureScript/Om and widely used in React projects. They permit to manage the state outside of React, and let multiple components have read/write access to the same part of the state, without needing to know anything about the component tree.

Many implementations exists, including ImmutableJS, React-cursors and Omniscient

Edit 2016: it seems that people agree cursors work fine for smaller apps but it does not scale well on complex apps. Om Next does not have cursors anymore (while it's Om that introduced the concept initially)


Elm architecture

The Elm architecture is an architecture proposed to be used by the Elm language. Even if Elm is not ReactJS, the Elm architecture can be done in React as well.

Dan Abramov, the author of Redux, did an implementation of the Elm architecture using React.

Both Redux and Elm are really great and tend to empower event-sourcing concepts on the frontend, both allowing time-travel debugging, undo/redo, replay...

The main difference between Redux and Elm is that Elm tend to be a lot more strict about state management. In Elm you can't have local component state or mount/unmount hooks and all DOM changes must be triggered by global state changes. Elm architecture propose a scalable approach that permits to handle ALL the state inside a single immutable object, while Redux propose an approach that invites you to handle MOST of the state in a single immutable object.

While the conceptual model of Elm is very elegant and the architecture permits to scale well on large apps, it can in practice be difficult or involve more boilerplate to achieve simple tasks like giving focus to an input after mounting it, or integrating with an existing library with an imperative interface (ie JQuery plugin). Related issue.

Also, Elm architecture involves more code boilerplate. It's not that verbose or complicated to write but I think the Elm architecture is more suited to statically typed languages.


FRP

Libraries like RxJS, BaconJS or Kefir can be used to produce FRP streams to handle communication between components.

You can try for example Rx-React

I think using these libs is quite similar to using what the ELM language offers with signals.

CycleJS framework does not use ReactJS but uses vdom. It share a lot of similarities with the Elm architecture (but is more easy to use in real life because it allows vdom hooks) and it uses RxJs extensively instead of functions, and can be a good source of inspiration if you want to use FRP with React. CycleJs Egghead videos are nice to understand how it works.


CSP

CSP (Communicating Sequential Processes) are currently popular (mostly because of Go/goroutines and core.async/ClojureScript) but you can use them also in javascript with JS-CSP.

James Long has done a video explaining how it can be used with React.

Sagas

A saga is a backend concept that comes from the DDD / EventSourcing / CQRS world, also called "process manager". It is being popularized by the redux-saga project, mostly as a replacement to redux-thunk for handling side-effects (ie API calls etc). Most people currently think it only services for side-effects but it is actually more about decoupling components.

It is more of a compliment to a Flux architecture (or Redux) than a totally new communication system, because the saga emit Flux actions at the end. The idea is that if you have widget1 and widget2, and you want them to be decoupled, you can't fire action targeting widget2 from widget1. So you make widget1 only fire actions that target itself, and the saga is a "background process" that listens for widget1 actions, and may dispatch actions that target widget2. The saga is the coupling point between the 2 widgets but the widgets remain decoupled.

If you are interested take a look at my answer here


Conclusion

If you want to see an example of the same little app using these different styles, check the branches of this repository.

I don't know what is the best option in the long term but I really like how Flux looks like event-sourcing.

If you don't know event-sourcing concepts, take a look at this very pedagogic blog: Turning the database inside out with apache Samza, it is a must-read to understand why Flux is nice (but this could apply to FRP as well)

I think the community agrees that the most promising Flux implementation is Redux, which will progressively allow very productive developer experience thanks to hot reloading. Impressive livecoding ala Bret Victor's Inventing on Principle video is possible!

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

Laravel Eloquent inner join with multiple conditions

You can see the following code to solved the problem

return $query->join('kg_shops', function($join)
{
    $join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
    $join->where('kg_shops.active','=', 1);
});

Or another way to solved it

 return $query->join('kg_shops', function($join)
{
    $join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
    $join->on('kg_shops.active','=', DB::raw('1'));
});

Convert JSON string to array of JSON objects in Javascript

I know a lot of people are saying use eval. the eval() js function will call the compiler, and that can offer a series of security risks. It is best to avoid its usage where possible. The parse function offers a more secure alternative.

What does jQuery.fn mean?

In the jQuery source code we have jQuery.fn = jQuery.prototype = {...} since jQuery.prototype is an object the value of jQuery.fn will simply be a reference to the same object that jQuery.prototype already references.

To confirm this you can check jQuery.fn === jQuery.prototype if that evaluates true (which it does) then they reference the same object

Non-static variable cannot be referenced from a static context

Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.

Static variables are marked as static and instance variables doesn't have specific keyword.

How to preview selected image in input type="file" in popup using jQuery?

If your are using HTML5 then try following code snippet

<img id="uploadPreview" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<script type="text/javascript">

    function PreviewImage() {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

        oFReader.onload = function (oFREvent) {
            document.getElementById("uploadPreview").src = oFREvent.target.result;
        };
    };

</script>

MySQL Error 1264: out of range value for column

The value 3172978990 is greater than 2147483647 – the maximum value for INT – hence the error. MySQL integer types and their ranges are listed here.

Also note that the (10) in INT(10) does not define the "size" of an integer. It specifies the display width of the column. This information is advisory only.

To fix the error, change your datatype to VARCHAR. Phone and Fax numbers should be stored as strings. See this discussion.

How to auto-format code in Eclipse?

CTRL + SHIFT + F will auto format your code(whether it is highlighted or non highlighted).

How to sort the letters in a string alphabetically in Python

You can use reduce

>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'

Ubuntu says "bash: ./program Permission denied"

Sounds like you don't have the execute flag set on the file permissions, try:

chmod u+x program_name

Linq where clause compare only date value without time value

In similar case I used the following code:

DateTime upperBound = DateTime.Today.AddDays(1); // If today is October 9, then upperBound is set to 2012-10-10 00:00:00
return var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
        && x.DateTimeValueColumn < upperBound) // Accepts all dates earlier than October 10, time of day doesn't matter here
    .Select(x => x);

Tkinter example code for multiple windows, why won't buttons load correctly?

#!/usr/bin/env python
import Tkinter as tk

from Tkinter import *

class windowclass():

        def __init__(self,master):
                self.master = master
                self.frame = tk.Frame(master)
                self.lbl = Label(master , text = "Label")
                self.lbl.pack()
                self.btn = Button(master , text = "Button" , command = self.command )
                self.btn.pack()
                self.frame.pack()

        def command(self):
                print 'Button is pressed!'

                self.newWindow = tk.Toplevel(self.master)
                self.app = windowclass1(self.newWindow)

class windowclass1():

        def __init__(self , master):
                self.master = master
                self.frame = tk.Frame(master)
                master.title("a")
                self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
                self.quitButton.pack()
                self.frame.pack()


        def close_window(self):
                self.master.destroy()


root = Tk()

root.title("window")

root.geometry("350x50")

cls = windowclass(root)

root.mainloop()

How to create and download a csv file from php script?

You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
    fputcsv($f, $line);
}

To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):

header('Content-Disposition: attachment; filename="filename.csv";');

Putting it all together:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

And you can use it like this:

array_to_csv_download(array(
  array(1,2,3,4), // this array is going to be the first row
  array(1,2,3,4)), // this array is going to be the second row
  "numbers.csv"
);

Update:
Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');

    // open the "output" stream
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}   

How to get milliseconds from LocalDateTime in Java 8

Date and time as String to Long (millis):

String dateTimeString = "2020-12-12T14:34:18.000Z";

DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);

LocalDateTime localDateTime = LocalDateTime
        .parse(dateTimeString, formatter);

Long dateTimeMillis = localDateTime
        .atZone(ZoneId.systemDefault())
        .toInstant()
        .toEpochMilli();

Visual Studio opens the default browser instead of Internet Explorer

You may debug by firefox also.

Follow these steps: Tool->Attach to process and select firefox.exe or your default browser. Then debugger will work with this browser. But I had some trouble when firefox is 32 bit and and VS2010 is 64 bit.

Anyway right click the current document, browse with --> than choose your browser, than set it as default. This way is better. B'cause firefox's process id may change, so you will be annoyed for attaching the process again.

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Well, there are two types of wait: explicit and implicit wait. The idea of explicit wait is

WebDriverWait.until(condition-that-finds-the-element);

The concept of implicit wait is

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

You can get difference in details here.

In such situations I'd prefer using explicit wait (fluentWait in particular):

public WebElement fluentWait(final By locator) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(30, TimeUnit.SECONDS)
            .pollingEvery(5, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);

    WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    });

    return  foo;
};

fluentWait function returns your found web element. From the documentation on fluentWait: An implementation of the Wait interface that may have its timeout and polling interval configured on the fly. Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page. Details you can get here

Usage of fluentWait in your case be the following:

WebElement textbox = fluentWait(By.id("textbox"));

This approach IMHO better as you do not know exactly how much time to wait and in polling interval you can set arbitrary timevalue which element presence will be verified through . Regards.

Is there a way to get version from package.json in nodejs code?

There is another way of fetching certain information from your package.json file namely using pkginfo module.

Usage of this module is very simple. You can get all package variables using:

require('pkginfo')(module);

Or only certain details (version in this case)

require('pkginfo')(module, 'version');

And your package variables will be set to module.exports (so version number will be accessible via module.exports.version).

You could use the following code snippet:

require('pkginfo')(module, 'version');
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, module.exports.version

This module has very nice feature - it can be used in any file in your project (e.g. in subfolders) and it will automatically fetch information from your package.json. So you do not have to worry where you package.json is.

I hope that will help.

Username and password in command for git push

It is possible but, before git 2.9.3 (august 2016), a git push would print the full url used when pushing back to the cloned repo.
That would include your username and password!

But no more: See commit 68f3c07 (20 Jul 2016), and commit 882d49c (14 Jul 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 71076e1, 08 Aug 2016)

push: anonymize URL in status output

Commit 47abd85 (fetch: Strip usernames from url's before storing them, 2009-04-17, Git 1.6.4) taught fetch to anonymize URLs.
The primary purpose there was to avoid sticking passwords in merge-commit messages, but as a side effect, we also avoid printing them to stderr.

The push side does not have the merge-commit problem, but it probably should avoid printing them to stderr. We can reuse the same anonymizing function.

Note that for this to come up, the credentials would have to appear either on the command line or in a git config file, neither of which is particularly secure.
So people should be switching to using credential helpers instead, which makes this problem go away.

But that's no excuse not to improve the situation for people who for whatever reason end up using credentials embedded in the URL.

Selecting text in an element (akin to highlighting with your mouse)

This thread (dead now) contains really wonderful stuff. But I'm not able to do it right on this page using FF 3.5b99 + FireBug due to "Security Error".

Yipee!! I was able to select whole right hand sidebar with this code hope it helps you:

    var r = document.createRange();
    var w=document.getElementById("sidebar");  
    r.selectNodeContents(w);  
    var sel=window.getSelection(); 
    sel.removeAllRanges(); 
    sel.addRange(r); 

PS:- I was not able to use objects returned by jquery selectors like

   var w=$("div.welovestackoverflow",$("div.sidebar"));
   
   //this throws **security exception**

   r.selectNodeContents(w);

undefined offset PHP error

How to reproduce this error in PHP:

Create an empty array and ask for the value given a key like this:

php> $foobar = array();

php> echo gettype($foobar);
array

php> echo $foobar[0];

PHP Notice:  Undefined offset: 0 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What happened?

You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.

It looked for your key in the array, and found undefined.

How to make the error not happen?

Ask if the key exists first before you go asking for its value.

php> echo array_key_exists(0, $foobar) == false;
1

If the key exists, then get the value, if it doesn't exist, no need to query for its value.

How to define Singleton in TypeScript

This is a typescript decorator checking if multiple instances were accidentaly created against a service class that is designed to be singleton:

https://www.npmjs.com/package/singleton-checker

Auto increment primary key in SQL Server Management Studio 2012

Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?

Example:

CREATE SCHEMA blah.
GO

CREATE SEQUENCE blah.blahsequence
START WITH 1
INCREMENT BY 1
NO CYCLE;

CREATE TABLE blah.de_blah_blah
(numbers bigint PRIMARY KEY NOT NULL
......etc

When referencing the squence in say an INSERT command just use:

NEXT VALUE FOR blah.blahsequence

More information and options for SEQUENCE

In c# what does 'where T : class' mean?

'T' represents a generic type. It means it can accept any type of class. The following article might help:

http://www.15seconds.com/issue/031024.htm

"import datetime" v.s. "from datetime import datetime"

datetime is a module which contains a type that is also called datetime. You appear to want to use both, but you're trying to use the same name to refer to both. The type and the module are two different things and you can't refer to both of them with the name datetime in your program.

If you need to use anything from the module besides the datetime type (as you apparently do), then you need to import the module with import datetime. You can then refer to the "date" type as datetime.date and the datetime type as datetime.datetime.

You could also do this:

from datetime import datetime, date
today_date = date.today()
date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Here you import only the names you need (the datetime and date types) and import them directly so you don't need to refer to the module itself at all.

Ultimately you have to decide what names from the module you need to use, and how best to use them. If you are only using one or two things from the module (e.g., just the date and datetime types), it may be okay to import those names directly. If you're using many things, it's probably better to import the module and access the things inside it using dot syntax, to avoid cluttering your global namespace with date-specific names.

Note also that, if you do import the module name itself, you can shorten the name to ease typing:

import datetime as dt
today_date = dt.date.today()
date_time = dt.datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Is it possible to disable the network in iOS Simulator?

If your app is connecting to a specific domain, you can simply add it to your /etc/hosts file and route it to a non-existing IP in your local network... For the application it will be the same as if there was no internet connection or the server is not reachable.

sudo nano /etc/hosts

add the following line:

192.168.1.123   example.com

or use 127.0.0.1 if you are not running a webserver on your local machine.

How do I trim whitespace from a string?

If you want to trim specified number of spaces from left and right, you could do this:

def remove_outer_spaces(text, num_of_leading, num_of_trailing):
    text = list(text)
    for i in range(num_of_leading):
        if text[i] == " ":
            text[i] = ""
        else:
            break

    for i in range(1, num_of_trailing+1):
        if text[-i] == " ":
            text[-i] = ""
        else:
            break
    return ''.join(text)

txt1 = "   MY name is     "
print(remove_outer_spaces(txt1, 1, 1))  # result is: "  MY name is    "
print(remove_outer_spaces(txt1, 2, 3))  # result is: " MY name is  "
print(remove_outer_spaces(txt1, 6, 8))  # result is: "MY name is"

psql - save results of command to a file

Approach for docker

via psql command

 docker exec -i %containerid% psql -U %user% -c '\dt' > tables.txt

or query from sql file

docker exec -i %containerid% psql -U %user% < file.sql > data.txt

Upgrading React version and it's dependencies by reading package.json

you can update all of the dependencies to their latest version by npm update

Subclipse svn:ignore

In case you're using TortoiseSVN and the file is already commited, go to your files project folder, right click on the file/folder you want to ignore, TortoiseSVN -> Unversion and add to ignore list. Then you delete the folder/file (click on it and then push DELETE on your keyboard), right click on your project folder, -> SVN Commit... This will delete the folder from the repository.... Now you can create your folder/file again and then it will be ignored.

Expand and collapse with angular js

I just wrote a simple zippy/collapsable using Angular using ng-show, ng-click and ng-init. Its implemented to one level but can be expanded to multiple levels easily.

Assign a boolean variable to ng-show and toggle it on click of header.

Check it out here enter image description here

Get data from php array - AJAX - jQuery

When you echo $array;, the result is Array, result[0] then represents the first character in Array which is A.

One way to handle this problem would be like this:

ajax.php

<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
    echo $a.",";
?>

jquery code

$(function(){ /* short for $(document).ready(function(){ */

    $('#prev').click(function(){

        $.ajax({type:    'POST',
                 url:     'ajax.php',
                 data:    'id=testdata',
                 cache:   false,
                 success: function(data){
                     var tmp = data.split(",");
                     $('#content1').html(tmp[0]);
                 }
                });
    });

});

How to write to a file in Scala?

If you are anyways having Akka Streams in your project, it provides a one-liner:

def writeToFile(p: Path, s: String)(implicit mat: Materializer): Unit = {
  Source.single(ByteString(s)).runWith(FileIO.toPath(p))
}

Akka docs > Streaming File IO

How to change Elasticsearch max memory size

For anyone looking to do this on Centos 7 or with another system running SystemD, you change it in

/etc/sysconfig/elasticsearch 

Uncomment the ES_HEAP_SIZE line, and set a value, eg:

# Heap Size (defaults to 256m min, 1g max)
ES_HEAP_SIZE=16g

(Ignore the comment about 1g max - that's the default)

Directly assigning values to C Pointers

The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.

You need to create an int variable somewhere in memory for the int * variable to point at.

Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:

int main(){
    int variable;
    int *ptr = &variable;
    *ptr = 20;
    printf("%d", *ptr);
    return 0;
}

Here, the int variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20. The key is that the pointer is initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

Concrete Javascript Regex for Accented Characters (Diacritics)

/^[\pL\pM\p{Zs}.-]+$/u

Explanation:

  • \pL - matches any kind of letter from any language
  • \pM - atches a character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.)
  • \p{Zs} - matches a whitespace character that is invisible, but does take up space
  • u - Pattern and subject strings are treated as UTF-8

Unlike other proposed regex (such as [A-Za-zÀ-ÖØ-öø-ÿ]), this will work with all language specific characters, e.g. Šš is matched by this rule, but not matched by others on this page.

Unfortunately, natively JavaScript does not support these classes. However, you can use xregexp, e.g.

const XRegExp = require('xregexp');

const isInputRealHumanName = (input: string): boolean => {
  return XRegExp('^[\\pL\\pM-]+ [\\pL\\pM-]+$', 'u').test(input);
};

How can I get a list of all classes within current module in Python?

import Foo 
dir(Foo)

import collections
dir(collections)

How to set Oracle's Java as the default Java in Ubuntu?

If you're doing any sort of development you need to point to the JDK (Java Development Kit). Otherwise, you can point to the JRE (Java Runtime Environment).

The JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.

You should set JAVA_HOME based on current Java you are using. readlink will print value of a symbolic link for current Java and sed will adjust it to JRE directory:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

If you want to set up JAVA_HOME to JDK you should go up one folder more:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")

Render a string in HTML and preserve spaces and linebreaks

You would want to replace all spaces with &nbsp; (non-breaking space) and all new lines \n with <br> (line break in html). This should achieve the result you're looking for.

body = body.replace(' ', '&nbsp;').replace('\n', '<br>');

Something of that nature.

server error:405 - HTTP verb used to access this page is not allowed

In my case, IIS was fine but.. uh.. all the files in the folder except web.config had been deleted (a manual deployment half-done on a test site).

How to Sign an Already Compiled Apk

fastest way is by signing with the debug keystore:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore app.apk androiddebugkey -storepass android

or on Windows:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore %USERPROFILE%/.android/debug.keystore test.apk androiddebugkey -storepass android

How can I select item with class within a DIV?

try this instead $(".video-divs.focused"). This works if you are looking for video-divs that are focused.

what is .subscribe in angular?

subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.

Toggle input disabled attribute using jQuery

This is fairly simple with the callback syntax of attr:

$("#product1 :checkbox").click(function(){
  $(this)
   .closest('tr') // find the parent row
       .find(":input[type='text']") // find text elements in that row
           .attr('disabled',function(idx, oldAttr) {
               return !oldAttr; // invert disabled value
           })
           .toggleClass('disabled') // enable them
       .end() // go back to the row
       .siblings() // get its siblings
           .find(":input[type='text']") // find text elements in those rows
               .attr('disabled',function(idx, oldAttr) {
                   return !oldAttr; // invert disabled value
               })
               .removeClass('disabled'); // disable them
});

How can I search sub-folders using glob.glob module?

Here is a adapted version that enables glob.glob like functionality without using glob2.

def find_files(directory, pattern='*'):
    if not os.path.exists(directory):
        raise ValueError("Directory not found {}".format(directory))

    matches = []
    for root, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            full_path = os.path.join(root, filename)
            if fnmatch.filter([full_path], pattern):
                matches.append(os.path.join(root, filename))
    return matches

So if you have the following dir structure

tests/files
+-- a0
¦   +-- a0.txt
¦   +-- a0.yaml
¦   +-- b0
¦       +-- b0.yaml
¦       +-- b00.yaml
+-- a1

You can do something like this

files = utils.find_files('tests/files','**/b0/b*.yaml')
> ['tests/files/a0/b0/b0.yaml', 'tests/files/a0/b0/b00.yaml']

Pretty much fnmatch pattern match on the whole filename itself, rather than the filename only.

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

How to place and center text in an SVG rectangle

alignment-baseline is not the right attribute to use here. The correct answer is to use a combination of dominant-baseline="central" and text-anchor="middle":

_x000D_
_x000D_
<svg width="200" height="100">_x000D_
    <g>_x000D_
        <rect x="0" y="0" width="200" height="100" style="stroke:red; stroke-width:3px; fill:white;"/>_x000D_
        <text x="50%" y="50%" style="dominant-baseline:central; text-anchor:middle; font-size:40px;">TEXT</text>_x000D_
    </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Update a local branch with the changes from a tracked remote branch

You have set the upstream of that branch

(see:

git branch -f --track my_local_branch origin/my_remote_branch
# OR (if my_local_branch is currently checked out):
$ git branch --set-upstream-to my_local_branch origin/my_remote_branch

(git branch -f --track won't work if the branch is checked out: use the second command git branch --set-upstream-to instead, or you would get "fatal: Cannot force update the current branch.")

That means your branch is already configured with:

branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch

Git already has all the necessary information.
In that case:

# if you weren't already on my_local_branch branch:
git checkout my_local_branch 
# then:
git pull

is enough.


If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch', then a simple git push -u origin my_local_branch:my_remote_branch would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull or git push would, again, have been enough.

Warning: date_format() expects parameter 1 to be DateTime

You need to pass DateTime object to this func. See manual: php

string date_format ( DateTime $object , string $format )

You can try using:

date_format (new DateTime($time), 'd-m-Y');

Or you can also use:

$date = date_create('2000-01-01');
echo date_format($date, 'Y-m-d H:i:s');

How to make ng-repeat filter out duplicate results

If you want to list categories, I think you should explicitly state your intention in the view.

<select ng-model="orderProp" >
  <option ng-repeat="category in categories"
          value="{{category}}">
    {{category}}
  </option>
</select>

in the controller:

$scope.categories = $scope.places.reduce(function(sum, place) {
  if (sum.indexOf( place.category ) < 0) sum.push( place.category );
  return sum;
}, []);

What is The difference between ListBox and ListView

A ListView let you define a set of views for it and gives you a native way (WPF binding support) to control the display of ListView by using defined views.

Example:

XAML

<ListView ItemsSource="{Binding list}" Name="listv" MouseEnter="listv_MouseEnter" MouseLeave="listv_MouseLeave">
        <ListView.Resources>
            <GridView x:Key="one">
                <GridViewColumn Header="ID" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding id}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
            <GridView x:Key="two">                    
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.Resources>
        <ListView.Style>
            <Style TargetType="ListView">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ViewType}" Value="1">
                        <Setter Property="View" Value="{StaticResource one}" />
                    </DataTrigger>
                </Style.Triggers>
                <Setter Property="View" Value="{StaticResource two}" />
            </Style>
        </ListView.Style>  

Code Behind:

private int viewType;

public int ViewType
{
    get { return viewType; }
    set 
    { 
        viewType = value;
        UpdateProperty("ViewType");
    }
}        

private void listv_MouseEnter(object sender, MouseEventArgs e)
{
    ViewType = 1;
}

private void listv_MouseLeave(object sender, MouseEventArgs e)
{
    ViewType = 2;
}

OUTPUT:

Normal View: View 2 in above XAML

Normal

MouseOver View: View 1 in above XAML

Mouse Over

If you try to achieve above in a ListBox, probably you'll end up writing a lot more code forControlTempalate/ItemTemplate of ListBox.

How to stop a setTimeout loop?

I am not sure, but might be what you want:

var c = 0;
function setBgPosition()
{
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run()
    {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<=numbers.length)
        {
            setTimeout(run, 200);
        }
        else
        {
            Ext.get('common-spinner').setStyle('background-position', numbers[0] + 'px 0px');
        }
    }
    setTimeout(run, 200);
}
setBgPosition();

Finding duplicate rows in SQL Server

 /*To get duplicate data in table */

 SELECT COUNT(EmpCode),EmpCode FROM tbl_Employees WHERE Status=1 
  GROUP BY EmpCode HAVING COUNT(EmpCode) > 1

Check if a Python list item contains a string inside another string

I am new to Python. I got the code below working and made it easy to understand:

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for str in my_list:
    if 'abc' in str:
       print(str)

Trim string in JavaScript?

Here's a very simple way:

function removeSpaces(string){
return string.split(' ').join('');
}

C# Get/Set Syntax Usage

I do not understand what this is unclear

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.

In this example, the class TimePeriod stores a time period. Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}

Properties Overview

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

The value keyword is used to define the value being assigned by the set indexer.

Properties that do not implement a set method are read only.

http://msdn.microsoft.com/en-US/library/x9fsa0sw%28v=vs.80%29.aspx

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

I get this fairly regularily. Currently what's working for me (with Photon) is:

  • Close project
  • Open project

If this doesn't work :

  • Close project
  • Exit Eclipse
  • Restart Eclipse
  • Open Project

I know, stupid isn't it.

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

Try this:

Write mongodb instead of mongod

sudo service mongodb status

Create Test Class in IntelliJ

  1. Right click on project then select new->directory. Create a new directory and name it "test".
  2. Right click on "test" folder then select Mark Directory As->Test Sources Root
  3. Click on Navigate->Test->Create New Test
    Select Testing library(JUnit4 or any)
    Specify Class Name
    Select Member

That's it. We can modify the directory structure as per our need. Good luck!

Real differences between "java -server" and "java -client"?

The most visible immediate difference in older versions of Java would be the memory allocated to a -client as opposed to a -server application. For instance, on my Linux system, I get:

$ java -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'
uintx AdaptivePermSizeWeight               = 20               {product}
uintx ErgoHeapSizeLimit                    = 0                {product}
uintx InitialHeapSize                     := 66328448         {product}
uintx LargePageHeapSizeThreshold           = 134217728        {product}
uintx MaxHeapSize                         := 1063256064       {product}
uintx MaxPermSize                          = 67108864         {pd product}
uintx PermSize                             = 16777216         {pd product}
java version "1.6.0_24"

as it defaults to -server, but with the -client option I get:

$ java -client -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'
uintx AdaptivePermSizeWeight               = 20               {product}
uintx ErgoHeapSizeLimit                    = 0                {product}
uintx InitialHeapSize                     := 16777216         {product}
uintx LargePageHeapSizeThreshold           = 134217728        {product}
uintx MaxHeapSize                         := 268435456        {product}
uintx MaxPermSize                          = 67108864         {pd product}
uintx PermSize                             = 12582912         {pd product}
java version "1.6.0_24"

so with -server most of the memory limits and initial allocations are much higher for this java version.

These values can change for different combinations of architecture, operating system and jvm version however. Recent versions of the jvm have removed flags and re-moved many of the distinctions between server and client.

Remember too that you can see all the details of a running jvm using jvisualvm. This is useful if you have users who or modules which set JAVA_OPTS or use scripts which change command line options. This will also let you monitor, in real time, heap and permgen space usage along with lots of other stats.

C++ multiline string literal

Just to elucidate a bit on @emsr's comment in @unwind's answer, if one is not fortunate enough to have a C++11 compiler (say GCC 4.2.1), and one wants to embed the newlines in the string (either char * or class string), one can write something like this:

const char *text =
  "This text is pretty long, but will be\n"
  "concatenated into just a single string.\n"
  "The disadvantage is that you have to quote\n"
  "each part, and newlines must be literal as\n"
  "usual.";

Very obvious, true, but @emsr's short comment didn't jump out at me when I read this the first time, so I had to discover this for myself. Hopefully, I've saved someone else a few minutes.

Clear android application user data

This command worked for me:

adb shell pm clear packageName

Android View shadow

I know this is stupidly hacky,
but if you want to support under v21, here are my achievements.

rectangle_with_10dp_radius_white_bg_and_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Shadow layers -->
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_1" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_2" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_3" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_4" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_5" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_6" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_7" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_8" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_9" />
        </shape>
    </item>
    <item
        android:left="1dp"
        android:right="1dp"
        android:top="3dp">
        <shape>
            <corners android:radius="10dp" />
            <padding
                android:bottom="1.8dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
            <solid android:color="@color/shadow_hack_level_10" />
        </shape>
    </item>

    <!-- Background layer -->
    <item>
        <shape>
            <solid android:color="@android:color/white" />
            <corners android:radius="10dp" />
        </shape>
    </item>

</layer-list>

rectangle_with_10dp_radius_white_bg_and_shadow.xml (v21)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="10dp" />
</shape>

view_incoming.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rectangle_with_10dp_radius_white_bg_and_shadow"
    android:elevation="7dp"
    android:gravity="center"
    android:minWidth="240dp"
    android:minHeight="240dp"
    android:orientation="horizontal"
    android:padding="16dp"
    tools:targetApi="lollipop">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="Hello World !" />

</LinearLayout>

Here is result:

Under v21 (this is which you made with xml) enter image description here

Above v21 (real elevation rendering) enter image description here

  • The one significant difference is it will occupy the inner space from the view so your actual content area can be smaller than >= lollipop devices.

React.js: Identifying different inputs with one onChange handler

Hi have improved ssorallen answer. You don't need to bind function because you can access to the input without it.

var Hello = React.createClass({
    render: function() {
        var total = this.state.input1 + this.state.input2;
        return (
             <div>{total}<br/>
                  <input type="text" 
                    value={this.state.input1}
                    id="input1"  
                    onChange={this.handleChange} />
                 <input type="text" 
                    value={this.state.input2}
                    id="input2" 
                    onChange={this.handleChange} />
            </div>
       );
   },
   handleChange: function (name, value) {
       var change = {};
       change[name] = value;
       this.setState(change);
   }
});

React.renderComponent(<Hello />, document.getElementById('content'));

Google Chrome forcing download of "f.txt" file

Seems related to https://groups.google.com/forum/#!msg/google-caja-discuss/ite6K5c8mqs/Ayqw72XJ9G8J.

The so-called "Rosetta Flash" vulnerability is that allowing arbitrary yet identifier-like text at the beginning of a JSONP response is sufficient for it to be interpreted as a Flash file executing in that origin. See for more information: http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/

JSONP responses from the proxy servlet now: * are prefixed with "/**/", which still allows them to execute as JSONP but removes requester control over the first bytes of the response. * have the response header Content-Disposition: attachment.

What is default list styling (CSS)?

You cannot. Whenever there is any style sheet being applied that assigns a property to an element, there is no way to get to the browser defaults, for any instance of the element.

The (disputable) idea of reset.css is to get rid of browser defaults, so that you can start your own styling from a clean desk. No version of reset.css does that completely, but to the extent they do, the author using reset.css is supposed to completely define the rendering.

git discard all changes and pull from upstream

There are (at least) two things you can do here–you can reclone the remote repo, or you can reset --hard to the common ancestor and then do a pull, which will fast-forward to the latest commit on the remote master.

To be concrete, here's a simple extension of Nevik Rehnel's original answer:

git reset --hard origin/master
git pull origin master

NOTE: using git reset --hard will discard any uncommitted changes, and it can be easy to confuse yourself with this command if you're new to git, so make sure you have a sense of what it is going to do before proceeding.

Adding <script> to WordPress in <head> element

One way I like to use is Vanilla JavaScript with template literal:

var templateLiteral = [`
    <!-- HTML_CODE_COMES_HERE -->
`]

var head = document.querySelector("head");
head.innerHTML = templateLiteral;

How to use the onClick event for Hyperlink using C# code?

this may help you.

In .cs page,

//Declare a string
   public string usertypeurl = "";
  //check who is the user
       //place your code to check who is the user
       //if it is admin
       usertypeurl = "help/AdminTutorial.html";
       //if it is other 
        usertypeurl = "help/UserTutorial.html";

In .aspx age pass this variabe

  <a href='<%=usertypeurl%>'>Tutorial</a>

How to run TestNG from command line

Prepare MANIFEST.MF file with the following content

Manifest-Version: 1.0
Main-Class: org.testng.TestNG

Pack all test and dependency classes in the same jar, say tests.jar

jar cmf MANIFEST.MF tests.jar -C folder-with-classes/ .

Notice trailing ".", replace folder-with-classes/ with proper folder name or path.

Create testng.xml with content like below

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Tests" verbose="5">
  <test name="Test1">
    <classes>
      <class name="com.example.yourcompany.qa.Test1"/>
    </classes>
  </test>  
</suite>

Replace com.example.yourcompany.qa.Test1 with path to your Test class.

Run your tests

java -jar tests.jar testng.xml

How to move Docker containers between different hosts?

I tried many solutions for this, and this is the one that worked for me :

1.commit/save container to new image :

  1. ++ commit the container:
    # docker stop
    # docker commit CONTAINER_NAME
    # docker save --output IMAGE_NAME.tar IMAGE_NAME:TAG


ps:"Our container CONTAINER_NAME has a mounted volume at '/var/home'" ( you have to inspect your container to specify its volume path : # docker inspect CONTAINER_NAME )

  1. ++ save its volume : we will use an ubuntu image to do the thing.
    # mkdir backup
    # docker run --rm --volumes-from CONTAINER_NAME -v ${pwd}/backup:/backup ubuntu bash -c “cd /var/home && tar cvf /backup/volume_backup.tar .”

Now when you look at ${pwd}/backup , you will find our volume under tar format.
Until now, we have our conatainer's image 'IMAGE_NAME.tar' and its volume 'volume_backup.tar'.

Now you can , recreate the same old container on a new host.

Convert Long into Integer

In addition to @Thilo's accepted answer, Math.toIntExact works also great in Optional method chaining, despite it accepts only an int as an argument

Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

nginx showing blank PHP pages

This solved my issue:

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    include snippets/fastcgi-php.conf;
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
}

Redirect to a page/URL after alert button is pressed

Like that, both of the sentences will be executed even before the page has finished loading.

Here is your error, you are missing a ';' Change:

       echo 'alert("review your answer")'; 
       echo 'window.location= "index.php"';

To:

       echo 'alert("review your answer");';
       echo 'window.location= "index.php";';

Then a suggestion: You really should trigger that logic after some event. So, for instance:

           document.getElementById("myBtn").onclick=function(){
                 alert("review your answer");
                 window.location= "index.php";
           };

Another suggestion, use jQuery

change html input type by JS?

I had to add a '.value' to the end of Evert's code to get it working.

Also I combined it with a browser check so that input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.

if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
    document.getElementById("input_id").attributes["type"].value = "text";

How to search JSON tree with jQuery

You can search on a json object array using $.grep() like this:

var persons = {
    "person": [
        {
            "name": "Peter",
            "age": 43,
            "sex": "male"
        }, {
            "name": "Zara",
            "age": 65,
            "sex": "female"
        }
      ]
   }
};
var result = $.grep(persons.person, function(element, index) {
   return (element.name === 'Peter');
});
alert(result[0].age);

How can I force browsers to print background images in CSS?

it is working in google chrome when you add !important attribute to background image make sure you add attribute first and try again, you can do it like that

    .inputbg {
background: url('inputbg.png') !important;  

}

Why has it failed to load main-class manifest attribute from a JAR file?

I discovered that I was also having this error in NetBeans. I hope the following is helpful.

  1. Make sure that when you go to Project Configuration you set the main class you intend for running.
  2. Do a Build or Clean Build
  3. Place the jar file where you wish and try: java -jar "YourProject.jar" again at the command line.

This was the problem I was getting because I had other "test" programs I was using in NetBeans and I had to make sure the Main Class under the Run portion of the Project configuration was set correctly.

many blessings, John P