Programs & Examples On #Star schema

Star schema is the most basic data warehousing dimensional structure and database schema, consisting of one or more fact tables referencing any number of dimension tables.

Textarea Auto height

I see that this is answered already, but I believe I have a simple jQuery solution ( jQuery is not even really needed; I just enjoy using it ):

I suggest counting the line breaks in the textarea text and setting the rows attribute of the textarea accordingly.

var text = jQuery('#your_textarea').val(),
    // look for any "\n" occurences
    matches = text.match(/\n/g),
    breaks = matches ? matches.length : 2;

jQuery('#your_textarea').attr('rows',breaks + 2);

What is the PostgreSQL equivalent for ISNULL()

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

close vs shutdown socket?

linux: shutdown() causes listener thread select() to awake and produce error. shutdown(); close(); will lead to endless wait.

winsock: vice versa - shutdown() has no effect, while close() is successfully catched.

iOS 7 - Failing to instantiate default view controller

This warning is also reported if you have some code like:

    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = myAwesomeRootViewController
    window?.makeKeyAndVisible()

In this case, go to the first page of target settings and set Main Interface to empty, since you don't need a storyboard entry for your app.

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

NSArray + remove item from array

Here's a more functional approach using Key-Value Coding:

@implementation NSArray (Additions)

- (instancetype)arrayByRemovingObject:(id)object {
    return [self filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != %@", object]];
}

@end

How to export a MySQL database to JSON?

It may be asking too much of MySQL to expect it to produce well formed json directly from a query. Instead, consider producing something more convenient, like CSV (using the INTO OUTFILE '/path/to/output.csv' FIELDS TERMINATED BY ',' snippet you already know) and then transforming the results into json in a language with built in support for it, like python or php.

Edit python example, using the fine SQLAlchemy:

class Student(object):
    '''The model, a plain, ol python class'''
    def __init__(self, name, email, enrolled):
        self.name = name
        self.email = email
        self.enrolled = enrolled

    def __repr__(self):
        return "<Student(%r, %r)>" % (self.name, self.email)

    def make_dict(self):
        return {'name': self.name, 'email': self.email}



import sqlalchemy
metadata = sqlalchemy.MetaData()
students_table = sqlalchemy.Table('students', metadata,
        sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
        sqlalchemy.Column('name', sqlalchemy.String(100)),
        sqlalchemy.Column('email', sqlalchemy.String(100)),
        sqlalchemy.Column('enrolled', sqlalchemy.Date)
    )

# connect the database.  substitute the needed values.
engine = sqlalchemy.create_engine('mysql://user:pass@host/database')

# if needed, create the table:
metadata.create_all(engine)

# map the model to the table
import sqlalchemy.orm
sqlalchemy.orm.mapper(Student, students_table)

# now you can issue queries against the database using the mapping:
non_students = engine.query(Student).filter_by(enrolled=None)

# and lets make some json out of it:
import json
non_students_dicts = ( student.make_dict() for student in non_students)
students_json = json.dumps(non_students_dicts)

Git diff --name-only and copy that list

zip update.zip $(git diff --name-only commit commit)

Calculating powers of integers

base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).

public int power(int base, int n){
   return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));
}

Git merge master into feature branch

Complementing the existing answers, as these commands are recurrent we can do it in a row. Given we are in the feature branch:

git checkout master && git pull && git checkout - && git merge -

Or add them in an alias:

alias merge_with_master="git checkout master && git pull && git checkout - && git merge -"

Jquery to get SelectedText from dropdown

Today, with jQuery, I do this:

$("#foo").change(function(){    
    var foo = $("#foo option:selected").text();
});

\#foo is the drop-down box id.

Read more.

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

How to rebuild docker container in docker-compose.yml?

This should fix your problem:

docker-compose ps # lists all services (id, name)
docker-compose stop <id/name> #this will stop only the selected container
docker-compose rm <id/name> # this will remove the docker container permanently 
docker-compose up # builds/rebuilds all not already built container 

ASP.NET Setting width of DataBound column in GridView

Width can be set to specific column as below: By percentages:

<asp:BoundField HeaderText="UserInfo"  DataField="UserInfo"  
SortExpression="UserInfo" ItemStyle-Width="100%"></asp:BoundField>

OR

By pixel:

<asp:BoundField HeaderText="UserInfo"  DataField="UserInfo"  
SortExpression="UserInfo" ItemStyle-Width="500px"></asp:BoundField>

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

How does one check if a table exists in an Android SQLite database?

Yep, turns out the theory in my edit was right: the problem that was causing the onCreate method not to run, was the fact that SQLiteOpenHelper objects should refer to databases, and not have a separate one for each table. Packing both tables into one SQLiteOpenHelper solved the problem.

Make body have 100% of the browser height

If you don't want the work of editing your own CSS file and define the height rules by yourself, the most typical CSS frameworks also solve this issue with the body element filling the entirety of the page, among other issues, at ease with multiple sizes of viewports.

For example, Tacit CSS framework solves this issue out of the box, where you don't need to define any CSS rules and classes and you just include the CSS file in your HTML.

Maven Modules + Building a Single Specific Module

Any best practices here?

Use the Maven advanced reactor options, more specifically:

-pl, --projects
        Build specified reactor projects instead of all projects
-am, --also-make
        If project list is specified, also build projects required by the list

So just cd into the parent P directory and run:

mvn install -pl B -am

And this will build B and the modules required by B.

Note that you need to use a colon if you are referencing an artifactId which differs from the directory name:

mvn install -pl :B -am

As described here: https://stackoverflow.com/a/26439938/480894

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

How to get last month/year in java?

You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0

    Calendar c = Calendar.getInstance();
    c.set(2011, 2, 1);
    c.add(Calendar.MONTH, -1);
    int month = c.get(Calendar.MONTH) + 1;
    assertEquals(1, month);

How to prevent a file from direct URL Access?

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteCond %{REQUEST_URI} !^http://(www\.)?localhost/(.*)\.(gif|jpg|png|jpeg|mp4)$ [NC] 
RewriteRule . - [F]

How to force Docker for a clean build of an image

In some extreme cases, your only way around recurring build failures is by running:

docker system prune

The command will ask you for your confirmation:

WARNING! This will remove:
    - all stopped containers
    - all volumes not used by at least one container
    - all networks not used by at least one container
    - all images without at least one container associated to them
Are you sure you want to continue? [y/N]

This is of course not a direct answer to the question, but might save some lives... It did save mine.

Best way to get value from Collection by index

I agree that this is generally a bad idea. However, Commons Collections had a nice routine for getting the value by index if you really need to:

CollectionUtils.get(collection, index)

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

How to install Python package from GitHub?

To install Python package from github, you need to clone that repository.

git clone https://github.com/jkbr/httpie.git

Then just run the setup.py file from that directory,

sudo python setup.py install

Iterating through a List Object in JSP

another example with just scriplets, when iterating through an ArrayList that contains Maps.

<%   
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");    

for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>    
</tr>
...
<%}%>

Using $_POST to get select option value from HTML

Depends on if the form that the select is contained in has the method set to "get" or "post".

If <form method="get"> then the value of the select will be located in the super global array $_GET['taskOption'].

If <form method="post"> then the value of the select will be located in the super global array $_POST['taskOption'].

To store it into a variable you would:

$option = $_POST['taskOption']

A good place for more information would be the PHP manual: http://php.net/manual/en/tutorial.forms.php

How to make ng-repeat filter out duplicate results

Or you can write your own filter using lodash.

app.filter('unique', function() {
    return function (arr, field) {
        return _.uniq(arr, function(a) { return a[field]; });
    };
});

How to remove a row from JTable?

A JTable normally forms the View part of an MVC implementation. You'll want to remove rows from your model. The JTable, which should be listening for these changes, will update to reflect this removal. Hence you won't find removeRow() or similar as a method on JTable.

JWT (JSON Web Token) library for Java

https://github.com/networknt/jsontoken

This is a fork of original google jsontoken

It has not been updated since Sep 11, 2012 and depends on some old packages.

What I have done:

Convert from Joda time to Java 8 time. So it requires Java 8.
Covert Json parser from Gson to Jackson as I don't want to include two Json parsers to my projects.
Remove google collections from dependency list as it is stopped long time ago.
Fix thread safe issue with Java Mac.doFinal call.

All existing unit tests passed along with some newly added test cases.

Here is a sample to generate token and verify the token. For more information, please check https://github.com/networknt/light source code for usage.

I am the author of both jsontoken and Omni-Channel Application Framework.

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

How to change JAVA.HOME for Eclipse/ANT

In addition to verifying that the executables are in your path, you should also make sure that Ant can find tools.jar in your JDK. The easiest way to fix this is to add the tools.jar to the Ant classpath:

Adding tools.jar to Ant classpath.

Use jQuery to change an HTML tag?

Once a dom element is created, the tag is immutable, I believe. You'd have to do something like this:

$(this).replaceWith($('<h5>' + this.innerHTML + '</h5>'));

Using :focus to style outer div?

You can tab between div tags. Just add a tab index to the div. It's best to use jQuery and CSS classes to solve this problem. Here's a working sample tested in IE, Firefox, and Chrome (Latest versions... didn't test older).

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            var divParentIdFocus;
            var divParentIdUnfocus = null;

            $(document).ready(function() {              

                    $("div").focus(function() {
                        //$(this).attr("class", "highlight");
                        var curDivId = $(this).attr("id");

                        // This Check needs to be performed when/if div regains focus
                        // from child element.
                        if (divParentIdFocus != curDivId){
                            divParentIdUnfocus = divParentIdFocus;
                            divParentIdFocus = curDivId;
                            refreshHighlight();
                        }

                        divParentIdFocus = curDivId;
                    });


                    $("textarea").focus(function(){
                        var curDivId = $(this).closest("div").attr("id");

                        if(divParentIdFocus != curDivId){
                            divParentIdUnfocus = divParentIdFocus;
                            divParentIdFocus = curDivId;
                            refreshHighlight();
                        }
                    });

                    $("#div1").focus();
            });

            function refreshHighlight()
            {
                if(divParentIdUnfocus != null){
                    $("#" +divParentIdUnfocus).attr("class", "noHighlight");
                    divParentIdUnfocus = null;
                }

                $("#" + divParentIdFocus).attr("class", "highlight");
            }
        </script>
        <style type="text/css">
            .highlight{
                background-color:blue;
                border: 3px solid black;
                font-weight:bold;
                color: white;
            }
            .noHighlight{           
            }
            div, h1,textarea, select { outline: none; }

        </style>
    <head>
    <body>
        <div id = "div1" tabindex="100">
            <h1>Div 1</h1> <br />
            <textarea rows="2" cols="25" tabindex="101">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="102">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="103">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="104">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div2" tabindex="200">
            <h1>Div 2</h1> <br />
            <textarea rows="2" cols="25" tabindex="201">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="202">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="203">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="204">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div3" tabindex="300">
            <h1>Div 3</h1> <br />
            <textarea rows="2" cols="25" tabindex="301">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="302">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="303">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="304">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div4" tabindex="400">
            <h1>Div 4</h1> <br />
            <textarea rows="2" cols="25" tabindex="401">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="402">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="403">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="404">~Your Text Here~</textarea> <br />
        </div>      
    </body>
</html>

Check if a string isn't nil or empty in Lua

Can this code be simplified in one if test instead two?

nil and '' are different values. If you need to test that s is neither, IMO you should just compare against both, because it makes your intent the most clear.

That and a few alternatives, with their generated bytecode:

if not foo or foo == '' then end
     GETGLOBAL       0 -1    ; foo
     TEST            0 0 0
     JMP             3       ; to 7
     GETGLOBAL       0 -1    ; foo
     EQ              0 0 -2  ; - ""
     JMP             0       ; to 7

if foo == nil or foo == '' then end
    GETGLOBAL       0 -1    ; foo
    EQ              1 0 -2  ; - nil
    JMP             3       ; to 7
    GETGLOBAL       0 -1    ; foo
    EQ              0 0 -3  ; - ""
    JMP             0       ; to 7

if (foo or '') == '' then end
   GETGLOBAL       0 -1    ; foo
   TEST            0 0 1
   JMP             1       ; to 5
   LOADK           0 -2    ; ""
   EQ              0 0 -2  ; - ""
   JMP             0       ; to 7

The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.

Accessing Google Account Id /username via Android

I've ran into the same issue and these two links solved for me:

The first one is this one: How do I retrieve the logged in Google account on android phones?

Which presents the code for retrieving the accounts associated with the phone. Basically you will need something like this:

AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();

And to add the permissions in the AndroidManifest.xml

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

Additionally, if you are using the Emulator the following link will help you to set it up with an account : Android Emulator - Trouble creating user accounts

Basically, it says that you must create an android device based on a API Level and not the SDK Version (like is usually done).

Check if a varchar is a number (TSQL)

ISNUMERIC will not do - it tells you that the string can be converted to any of the numeric types, which is almost always a pointless piece of information to know. For example, all of the following are numeric, according to ISNUMERIC:

£, $, 0d0

If you want to check for digits and only digits, a negative LIKE expression is what you want:

not Value like '%[^0-9]%'

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

The other answers here clearly explained what does it mean.I like to explain its use.

You can select an element in the elements tab and switch to console tab in chrome. Just type $0 or $1 or whatever number and press enter and the element will be displayed in the console for your use.

screenshot of chrome dev tools

Get the POST request body from HttpServletRequest

In Java 8, you can do it in a simpler and clean way :

if ("POST".equalsIgnoreCase(request.getMethod())) 
{
   test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}

Unable to connect to SQL Server instance remotely

  • To enable mixed authentication you can change the following registry key:

    HKLM\Software\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer\LoginMode
    

    Update the value to 2 and restart the Sql Server service to allow mixed authentication. Note that MSSQL.1 might need to be updated to reflect the number of the SQL Server Instance you are attempting to change.

  • A reason for connection errors can be a virus scanner installed on the server which blocks sqlserver.exe.

  • Another reason can be that the SQL Server Browser service is not running. When this service is not running you cannot connect on named instances (when they are using dynamic ports).

  • It is also possible that Sql Server is not setup to listen to TCP connections and only allows named pipes.

    1. In the Start Menu, open Programs > Microsoft SQL Server 2008 > Configuration Tools > SQL Server Surface Area Configuration
    2. In the Surface Area Configuration utility, click the link "SQL Server Configuration Manager"
    3. Expand "SQL Server Network Configuration" and select Protocols.
    4. Enable TCP/IP. If you need Named Pipes, then you can enable them here as well.
  • Last but not least, the Windows firewall needs to allow connections to SQL Server

    1. Add an exception for sqlserver.exe when you use the "Dynamic Port" system.
    2. Otherwise you can put exceptions for the SQL Server ports (default port 1433)
    3. Also add an exception for the SQL Server Browser. (udp port 1434)

More information:

As a last note, SqlLocalDB only supports named pipes, so you can not connect to it over the network.

Best way to require all files from a directory in ruby?

Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file| 
  require File.basename(file, File.extname(file))
end

If you don't strip the extension then you may end up requiring the same file twice (ruby won't realize that "foo" and "foo.rb" are the same file). Requiring the same file twice can lead to spurious warnings (e.g. "warning: already initialized constant").

Checking letter case (Upper/Lower) within a string in Java

I have streamlined the answer of @Quirliom above into functions that can be used:

private static boolean hasLength(CharSequence data) {
    if (String.valueOf(data).length() >= 8) return true;
    else return false;
}

private static boolean hasSymbol(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");
    return hasSpecial;
}

private static boolean hasUpperCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasUppercase = !password.equals(password.toLowerCase());
    return hasUppercase;
}

private static boolean hasLowerCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasLowercase = !password.equals(password.toUpperCase());
    return hasLowercase;
}

Convert HTML + CSS to PDF

TCPDF works fine, no dependencies, is free and constantly bugfixed. It has reasonable speed if supplied HTML/CSS contents is well formated. I normally generate from 50 - 300 kB of HTML input (including CSS) and get PDF output within 1-3 secs with 10 - 15 PDF pages.

I strongly recommend using tidy library as HTML pretty formatter before sending anything to TCPDF.

How to put a jar in classpath in Eclipse?

Right click your project in eclipse, build path -> add external jars.

How do I assign a port mapping to an existing Docker container?

In Fujimoto Youichi's example test01 is a container, whereas test02 is an image.

Before doing docker run you can remove the original container and then assign the container the same name again:

$ docker stop container01
$ docker commit container01 image01
$ docker rm container01
$ docker run -d -P --name container01 image01

(Using -P to expose ports to random ports rather than manually assigning).

What is a regular expression which will match a valid domain name without a subdomain?

Just a minor correction - the last part should be up to 6. Hence,

^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}$

The longest TLD is museum (6 chars) - http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

How to read data when some numbers contain commas as thousand separator?

If number is separated by "." and decimals by "," (1.200.000,00) in calling gsub you must set fixed=TRUE as.numeric(gsub(".","",y,fixed=TRUE))

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can implement this with a new Html helper extension function which will then be used similarly to the existing ActionLinks.

public static MvcHtmlString ActionLinkHtml5Data(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, object htmlDataAttributes)
{
    if (string.IsNullOrEmpty(linkText))
    {
        throw new ArgumentException(string.Empty, "linkText");
    }

    var html = new RouteValueDictionary(htmlAttributes);
    var data = new RouteValueDictionary(htmlDataAttributes);

    foreach (var attributes in data)
    {
        html.Add(string.Format("data-{0}", attributes.Key), attributes.Value);
    }

    return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null, actionName, controllerName, new RouteValueDictionary(routeValues), html));
}

And you call it like so ...

<%: Html.ActionLinkHtml5Data("link display", "Action", "Controller", new { id = Model.Id }, new { @class="link" }, new { extra = "some extra info" })  %>

Simples :-)

edit

bit more of a write up here

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

You can do (if you want to test NULL)

$this->db->where_exec('archived IS NULL) 

If you want to test NOT NULL

$this->db->where_exec('archived IS NOT NULL) 

How to format a number as percentage in R?

Even later:

As pointed out by @DzimitryM, percent() has been "retired" in favor of label_percent(), which is a synonym for the old percent_format() function.

label_percent() returns a function, so to use it, you need an extra pair of parentheses.

library(scales)
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
label_percent()(x)
## [1] "-100%"   "0%"      "10%"     "56%"     "100%"    "10 000%"

Customize this by adding arguments inside the first set of parentheses.

label_percent(big.mark = ",", suffix = " percent")(x)
## [1] "-100 percent"   "0 percent"      "10 percent"    
## [4] "56 percent"     "100 percent"    "10,000 percent"

An update, several years later:

These days there is a percent function in the scales package, as documented in krlmlr's answer. Use that instead of my hand-rolled solution.


Try something like

percent <- function(x, digits = 2, format = "f", ...) {
  paste0(formatC(100 * x, format = format, digits = digits, ...), "%")
}

With usage, e.g.,

x <- c(-1, 0, 0.1, 0.555555, 1, 100)
percent(x)

(If you prefer, change the format from "f" to "g".)

Laravel Soft Delete posts

You actually do the normal delete. But on the model you specify that its a softdelete model.

So on your model add the code:

class Contents extends Eloquent {

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

}

Then on your code do the normal delete like:

$id = Contents::find( $id );
$id ->delete();

Also make sure you have the deleted_at column on your table.

Or just see the docs: http://laravel.com/docs/eloquent#soft-deleting

I want to calculate the distance between two points in Java

Math.sqrt returns a double so you'll have to cast it to int as well

distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

How to check if an object implements an interface?

If you want a method like public void doSomething([Object implements Serializable]) you can just type it like this public void doSomething(Serializable serializableObject). You can now pass it any object that implements Serializable but using the serializableObject you only have access to the methods implemented in the object from the Serializable interface.

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

You missed the second statement: 1) NOT LIKE A, AND 2) NOT LIKE B

SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'

jquery dialog save cancel button styling

As of jquery ui version 1.8.16 below is how I got it working.

$('#element').dialog({
  buttons: { 
      "Save": {  
          text: 'Save', 
          class: 'btn primary', 
          click: function () {
              // do stuff
          }
      }
});

Removing an element from an Array (Java)

Nice looking solution would be to use a List instead of array in the first place.

List.remove(index)

If you have to use arrays, two calls to System.arraycopy will most likely be the fastest.

Foo[] result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
    System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}

(Arrays.asList is also a good candidate for working with arrays, but it doesn't seem to support remove.)

C# Error: Parent does not contain a constructor that takes 0 arguments

You need to change your child's constructor to:

public child(int i) : base(i)
{
    // etc...
}

You were getting the error because your parent class's constructor takes a parameter but you are not passing that parameter from the child to the parent.

Constructors are not inherited in C#, you have to chain them manually.

Android refresh current activity

This is a refresh button method, but it works well in my application. in finish() you kill the instances

public void refresh(View view){          //refresh is onClick name given to the button
    onRestart();
}

@Override
protected void onRestart() {

    // TODO Auto-generated method stub
    super.onRestart();
    Intent i = new Intent(lala.this, lala.class);  //your class
    startActivity(i);
    finish();

}

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

How to create <input type=“text”/> dynamically

you can use ES6 back quits

_x000D_
_x000D_
  var inputs = [_x000D_
        `<input type='checkbox' id='chbox0' onclick='checkboxChecked(this);'> <input  type='text' class='noteinputs0'id='note` + 0 + `' placeholder='task0'><button  id='notebtn0'                     >creat</button>`, `<input type='text' class='noteinputs' id='note` + 1 + `' placeholder='task1'><button  class='notebuttons' id='notebtn1' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 2 + `' placeholder='task2'><button  class='notebuttons' id='notebtn2' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 3 + `' placeholder='task3'><button  class='notebuttons' id='notebtn3' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 4 + `' placeholder='task4'><button  class='notebuttons' id='notebtn4' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 5 + `' placeholder='task5'><button  class='notebuttons' id='notebtn5' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 6 + `' placeholder='task6'><button  class='notebuttons' id='notebtn6' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 7 + `' placeholder='task7'><button  class='notebuttons' id='notebtn7' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 8 + `' placeholder='task8'><button  class='notebuttons' id='notebtn8' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 9 + `' placeholder='task9'><button  class='notebuttons' id='notebtn9' >creat</button>`_x000D_
    ].sort().join(" ");_x000D_
   document.querySelector('#hi').innerHTML += `<br>` +inputs;
_x000D_
<div id="hi"></div>
_x000D_
_x000D_
_x000D_

how to show lines in common (reverse diff)?

On *nix, you can use comm. The answer to the question is:

comm -1 -2 file1.sorted file2.sorted 
# where file1 and file2 are sorted and piped into *.sorted

Here's the full usage of comm:

comm [-1] [-2] [-3 ] file1 file2
-1 Suppress the output column of lines unique to file1.
-2 Suppress the output column of lines unique to file2.
-3 Suppress the output column of lines duplicated in file1 and file2. 

Also note that it is important to sort the files before using comm, as mentioned in the man pages.

Writing String to Stream and reading it back does not work

You're using message.Length which returns the number of characters in the string, but you should be using the nubmer of bytes to read. You should use something like:

byte[] messageBytes = uniEncoding.GetBytes(message);
stringAsStream.Write(messageBytes, 0, messageBytes.Length);

You're then reading a single byte and expecting to get a character from it just by casting to char. UnicodeEncoding will use two bytes per character.

As Justin says you're also not seeking back to the beginning of the stream.

Basically I'm afraid pretty much everything is wrong here. Please give us the bigger picture and we can help you work out what you should really be doing. Using a StreamWriter to write and then a StreamReader to read is quite possibly what you want, but we can't really tell from just the brief bit of code you've shown.

Adding author name in Eclipse automatically to existing files

Actually in Eclipse Indigo thru Oxygen, you have to go to the Types template Window -> Preferences -> Java -> Code Style -> Code templates -> (in right-hand pane) Comments -> double-click Types and make sure it has the following, which it should have by default:

/**
 * @author ${user}
 *
 * ${tags}
 */

and as far as I can tell, there is nothing in Eclipse to add the javadoc automatically to existing files in one batch. You could easily do it from the command line with sed & awk but that's another question.

If you are prepared to open each file individually, then selected the class / interface declaration line, e.g. public class AdamsClass { and then hit the key combo Shift + Alt + J and that will insert a new javadoc comment above, along with the author tag for your user. To experiment with other settings, go to Windows->Preferences->Java->Editor->Templates.

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I have encounter this issue too. And I'm running in XP SP3.

The following website http://www.docin.com/p-60410380.html# pointing out the solution. But it's simplified Chinese.

I translated its main idea into English here.

run regedit; open HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DirectX Then you must change the following two items: Item 1: Name: Version, Type:REG_SZ, The value should be a rather little number to make the installation success.

Item 2: Name: SDKVersion. But in your machine, the name can be different, for example, it can be ManagedDirectXVersion. But the type should be REG_SZ. Type:REG_SZ, The value should be a rather little number to make the installation success.

In fact, you can refer to the DirectX.lgo file to find the exact version number.

It works for me.

How to make child process die after parent exits?

I've passed parent pid using environment to the child, then periodically checked if /proc/$ppid exists from the child.

IOError: [Errno 32] Broken pipe: Python

A "Broken Pipe" error occurs when you try to write to a pipe that has been closed on the other end. Since the code you've shown doesn't involve any pipes directly, I suspect you're doing something outside of Python to redirect the standard output of the Python interpreter to somewhere else. This could happen if you're running a script like this:

python foo.py | someothercommand

The issue you have is that someothercommand is exiting without reading everything available on its standard input. This causes your write (via print) to fail at some point.

I was able to reproduce the error with the following command on a Linux system:

python -c 'for i in range(1000): print i' | less

If I close the less pager without scrolling through all of its input (1000 lines), Python exits with the same IOError you have reported.

std::enable_if to conditionally compile a member function

Here is my minimalist example, using a macro. Use double brackets enable_if((...)) when using more complex expressions.

template<bool b, std::enable_if_t<b, int> = 0>
using helper_enable_if = int;

#define enable_if(value) typename = helper_enable_if<value>

struct Test
{
     template<enable_if(false)>
     void run();
}

In a Bash script, how can I exit the entire script if a certain condition occurs?

Try this statement:

exit 1

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

Using LINQ to concatenate strings

Lots of choices here. You can use LINQ and a StringBuilder so you get the performance too like so:

StringBuilder builder = new StringBuilder();
List<string> MyList = new List<string>() {"one","two","three"};

MyList.ForEach(w => builder.Append(builder.Length > 0 ? ", " + w : w));
return builder.ToString();

Python assigning multiple variables to same value? list behavior

Simply put, in the first case, you are assigning multiple names to a list. Only one copy of list is created in memory and all names refer to that location. So changing the list using any of the names will actually modify the list in memory.

In the second case, multiple copies of same value are created in memory. So each copy is independent of one another.

How to write console output to a txt file

to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:

    public class TeePrintStream extends PrintStream {
        private final PrintStream second;

        public TeePrintStream(OutputStream main, PrintStream second) {
            super(main);
            this.second = second;
        }

        /**
         * Closes the main stream. 
         * The second stream is just flushed but <b>not</b> closed.
         * @see java.io.PrintStream#close()
         */
        @Override
        public void close() {
            // just for documentation
            super.close();
        }

        @Override
        public void flush() {
            super.flush();
            second.flush();
        }

        @Override
        public void write(byte[] buf, int off, int len) {
            super.write(buf, off, len);
            second.write(buf, off, len);
        }

        @Override
        public void write(int b) {
            super.write(b);
            second.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            super.write(b);
            second.write(b);
        }
    }

and used as in:

    FileOutputStream file = new FileOutputStream("test.txt");
    TeePrintStream tee = new TeePrintStream(file, System.out);
    System.setOut(tee);

(just an idea, not complete)

Is Android using NTP to sync time?

I have a Samsung Galaxy Tab 2 7.0 with Android 4.1.1. Apparently it does NOT sync to ntp. I loaded an app that says my tablet is 20 seconds off of ntp, but it can't set it unless I root the device.

Bootstrap 3 breakpoints and media queries

You should be able to use those breakpoints if you use http://lesscss.org/ to build your CSS.

/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) {  }

/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) {  }

/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) {  }

From https://getbootstrap.com/docs/3.4/css/#grid-media-queries

In fact @screen-sm-min is a variable than is replaced by the value specified in _variable when building with Less. If you don't use Less, you can replace this variable by the value:

/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) {  }

/* Medium devices (desktops, 992px and up) */
@media (min-width: 992px) {  }

/* Large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) {  }

Bootstrap 3 officially supports Sass: https://github.com/twbs/bootstrap-sass. If you are using Sass (and you should) the syntax is a bit different.

/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

/* Small devices (tablets, 768px and up) */
@media (min-width: $screen-sm-min) { }

/* Medium devices (desktops, 992px and up) */
@media (min-width: $screen-md-min) {  }

/* Large devices (large desktops, 1200px and up) */
@media (min-width: $screen-lg-min) {  }

How can I search an array in VB.NET?

It's not exactly clear how you want to search the array. Here are some alternatives:

Find all items containing the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))

Find all items starting with the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))

Find all items containing any case version of "ra" (returns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))

Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

-

If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.

Example:

Function ContainsRa(s As String) As Boolean
   Return s.Contains("Ra")
End Function

Usage:

Dim result As String() = Array.FindAll(arr, ContainsRa)

Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:

Public Class ArrayComparer

   Private _compareTo As String

   Public Sub New(compareTo As String)
      _compareTo = compareTo
   End Sub

   Function Contains(s As String) As Boolean
      Return s.Contains(_compareTo)
   End Function

   Function StartsWith(s As String) As Boolean
      Return s.StartsWith(_compareTo)
   End Function

End Class

Usage:

Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)

How do I find the date a video (.AVI .MP4) was actually recorded?

I used the following online tool: https://www.get-metadata.com It allows to upload a file and analyze it and then shows all its metadata.

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

Your problem looks like you are mixing DML & DDL operations. See this URL which explains this issue:

http://www.orafaq.com/forum/t/54714/2/

Debugging WebSocket in Google Chrome

As for a tool I started using, I suggest firecamp Its like Postman, but it also supports websockets and socket.io.

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, but you'll need to run it at the database level.

Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.

Screen shot of Advanced Scripting Options

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

Resizing image in Java

Resize image with high quality:

private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {

        try {
            BufferedImage image = ImageIO.read(uploadedInputStream);
            Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);

            int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
            BufferedImage resizedImage = new BufferedImage(width, height, type);

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, width, height, null);
            g2d.dispose();
            g2d.setComposite(AlphaComposite.Src);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            // Something is going wrong while resizing image
            return uploadedInputStream;
        }
    }

iOS change navigation bar title font and color

Don't forget to add the Raw values of the keys to avoid compile errors.

    let textAttributes:[NSAttributedStringKey: Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue):UIColor.blue, NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue):UIFont(name:"OpenSans", size: 17)!]
    navigationController?.navigationBar.titleTextAttributes = textAttributes

R solve:system is exactly singular

I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.

SonarQube Exclude a directory

If you're an Azure DevOps user looking for both where and how to exclude files and folders, here ya go:

  1. Edit your pipeline
  2. Make sure you have the "Prepare analysis on SonarQube" task added. You'll need to look elsewhere if you need help configuring this. Suggestion: Use the UI pipeline editor vs the yaml editor if you are missing the manage link. At present, there is no way to convert to UI from yaml. Just recreate the pipeline. If using git, you can delete the yaml from the root of your repo.
  3. Under the 'Advanced' section of the "Prepare analysis on SonarQube" task, you can add exclusions. See advice given by others for specific exclusion formats.

Example:

# Additional properties that will be passed to the scanner, 
# Put one key=value per line, example:
# sonar.exclusions=**/*.bin
sonar.exclusions=MyProjectName/MyWebContentFolder/**

Note: If you're not sure on the path, you can go into sonarqube, view your project, look at all or new 'Code Smells' and the path you need is listed above each grouping of issues. You can grab the full path to a file or use wilds like these examples:

  • MyProjectName/MyCodeFile.cs
  • MyProjectName/**

If you don't have the 'Run Code Analysis' task added, do that and place it somewhere after the 'Build solution **/*.sln' task.

Save and Queue and then check out your sonarqube server to see if the exclusions worked.

How to pass parameters in GET requests with jQuery

Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].

You should have processData set to true.

processData: true, // You should comment this out if is false or set to true

how to use jQuery ajax calls with node.js

Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.

This is my Client Side code.

$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
  alert(data);
},
function(jqXHR, textStatus, errorThrown) {
    alert('error ' + textStatus + " " + errorThrown);
});

This is my Server side Node.js

var http = require('http');
var querystring = require('querystring');
var url = require('url');

http.createServer(function (req, res) {
    //grab the callback from the query string   
    var pquery = querystring.parse(url.parse(req.url).query);   
    var callback = (pquery.callback ? pquery.callback : '');

    //we probably want to send an object back in response to the request
    var returnObject = {message: "Hello World!"};
    var returnObjectString = JSON.stringify(returnObject);

    //push back the response including the callback shenanigans
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);

How do I tokenize a string sentence in NLTK?

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

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

What is the Regular Expression For "Not Whitespace and Not a hyphen"

In Java:

    String regex = "[^-\\s]";

    System.out.println("-".matches(regex)); // prints "false"
    System.out.println(" ".matches(regex)); // prints "false"
    System.out.println("+".matches(regex)); // prints "true"

The regex [^-\s] works as expected. [^\s-] also works.

See also

D3 transform scale and translate

I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:

http://bl.ocks.org/dustinlarimer/6050773

How to fill a Javascript object literal with many static key/value pairs efficiently?

In ES2015 a.k.a ES6 version of JavaScript, a new datatype called Map is introduced.

let map = new Map([["key1", "value1"], ["key2", "value2"]]);
map.get("key1"); // => value1

check this reference for more info.

How to use NSJSONSerialization

The issue seems to be with autorelease of objects. NSJSONSerialization JSONObjectWithData is obviously creating some autoreleased objects and passing it back to you. If you try to take that on to a different thread, it will not work since it cannot be deallocated on a different thread.

Trick might be to try doing a mutable copy of that dictionary or array and use it.

NSError *e = nil;
id jsonObject = [NSJSONSerialization 
JSONObjectWithData: data 
options: NSJSONReadingMutableContainers 
error: &e] mutableCopy];

Treating a NSDictionary as NSArray will not result in Bad access exception but instead will probably crash when a method call is made.

Also, may be the options do not really matter here but it is better to give NSJSONReadingMutableContainers | NSJSONReadingMutableContainers | NSJSONReadingAllowFragments but even if they are autoreleased objects it may not solve this issue.

How to check compiler log in sql developer?

I can also use

show errors;

In sql worksheet.

When is JavaScript synchronous?

Is synchronous on all cases.

Example of blocking thread with Promises:

  const test = () => new Promise((result, reject) => {
    const time = new Date().getTime() + (3 * 1000);

    console.info('Test start...');

    while (new Date().getTime() < time) {
      // Waiting...
    }

    console.info('Test finish...');
  });

  test()
    .then(() => console.info('Then'))
    .finally(() => console.info('Finally'));

  console.info('Finish!');

The output will be:

Test start...
Test finish...
Finish!

Path of assets in CSS files in Symfony 2

I have came across the very-very-same problem.

In short:

  • Willing to have original CSS in an "internal" dir (Resources/assets/css/a.css)
  • Willing to have the images in the "public" dir (Resources/public/images/devil.png)
  • Willing that twig takes that CSS, recompiles it into web/css/a.css and make it point the image in /web/bundles/mynicebundle/images/devil.png

I have made a test with ALL possible (sane) combinations of the following:

  • @notation, relative notation
  • Parse with cssrewrite, without it
  • CSS image background vs direct <img> tag src= to the very same image than CSS
  • CSS parsed with assetic and also without parsing with assetic direct output
  • And all this multiplied by trying a "public dir" (as Resources/public/css) with the CSS and a "private" directory (as Resources/assets/css).

This gave me a total of 14 combinations on the same twig, and this route was launched from

  • "/app_dev.php/"
  • "/app.php/"
  • and "/"

thus giving 14 x 3 = 42 tests.

Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.

The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.

I observed the following:

Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.

These are the results:

  1. Result launched with /app_dev.php/ Result launched with /app_dev.php/

  2. Result launched with /app.php/ Result launched with /app.php/

  3. Result launched with / enter image description here

So... ONLY - The second image - Div B - Div C are the allowed syntaxes.

Here there is the TWIG code:

<html>
    <head>
            {% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: ABCDEF #}

            <link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets 'bundles/commondirty/css_original/d.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    {# First Row: GHIJKL #}

            <link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
            <link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

            {% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
                <link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
            {% endstylesheets %}

    </head>
    <body>
        <div class="container">
            <p>
                <img alt="Devil" src="../bundles/commondirty/images/devil.png">
                <img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
            </p>
            <p>
                <div class="a">
                    A
                </div>
                <div class="b">
                    B
                </div>
                <div class="c">
                    C
                </div>
                <div class="d">
                    D
                </div>
                <div class="e">
                    E
                </div>
                <div class="f">
                    F
                </div>
            </p>
            <p>
                <div class="g">
                    G
                </div>
                <div class="h">
                    H
                </div>
                <div class="i">
                    I
                </div>
                <div class="j">
                    J
                </div>
                <div class="k">
                    K
                </div>
                <div class="l">
                    L
                </div>
            </p>
        </div>
    </body>
</html>

The container.css:

div.container
{
    border: 1px solid red;
    padding: 0px;
}

div.container img, div.container div 
{
    border: 1px solid green;
    padding: 5px;
    margin: 5px;
    width: 64px;
    height: 64px;
    display: inline-block;
    vertical-align: top;
}

And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.

.a
{
    background: red url('../images/devil.png');
}

The "directories" structure is:

Directories Directories

All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.

But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:

Compilation process Compilation process

Note I do this for the --env=prod environment.

Just a few final thoughts:

  • This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install is executed, then assets:install, then assetic:dump, and then automating the removal of CSS from the public directory after assetic:dump has been executed. This would achive EXACTLY the behaviour desired in the question.

  • Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink option when developing.

  • Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink usage.

BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.

So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.

The winner is C

The winner is C

Command to get nth line of STDOUT

Is Perl easily available to you?

$ perl -n -e 'if ($. == 7) { print; exit(0); }'

Obviously substitute whatever number you want for 7.

C# switch statement limitations - why?

C# 8 allows you to solve this problem elegantly and compactly using an switch expression:

public string GetTypeName(object obj)
{
    return obj switch
    {
        int i => "Int32",
        string s => "String",
        { } => "Unknown",
        _ => throw new ArgumentNullException(nameof(obj))
    };
}

As a result, you get:

Console.WriteLine(GetTypeName(obj: 1));           // Int32
Console.WriteLine(GetTypeName(obj: "string"));    // String
Console.WriteLine(GetTypeName(obj: 1.2));         // Unknown
Console.WriteLine(GetTypeName(obj: null));        // System.ArgumentNullException

You can read more about the new feature here.

How to get span tag inside a div in jQuery and assign a text?

Try this

$("#message span").text("hello world!");

function Errormessage(txt) {
    var elem = $("#message");
    elem.fadeIn("slow");
    // find the span inside the div and assign a text
    elem.children("span").text("your text");

    elem.children("a.close-notify").click(function() {
        elem.fadeOut("slow");
    });
}

How to create a Custom Dialog box in android?

Dialog Fragment is the simplest way of creating a custom Alert Dialog.Follow the above code to create a custom view for your dialog and then implement it using Dialog Fragment. Add the following code to your layout file:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"
    android:background="#3E80B4"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt_dia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Do you realy want to exit ?"
        android:textColor="@android:color/white"
        android:textSize="15dp"
        android:textStyle="bold" />


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#3E80B4"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="Yes"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_marginLeft="5dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="No"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

switch() statement usage

Well, timing to the rescue again. It seems switch is generally faster than if statements. So that, and the fact that the code is shorter/neater with a switch statement leans in favor of switch:

# Simplified to only measure the overhead of switch vs if

test1 <- function(type) {
 switch(type,
        mean = 1,
        median = 2,
        trimmed = 3)
}

test2 <- function(type) {
 if (type == "mean") 1
 else if (type == "median") 2
 else if (type == "trimmed") 3
}

system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs

Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:

> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
           expr  min   lq median   uq      max
1 test1("mean")  709  771    864  951 16122411
2 test2("mean") 1007 1073   1147 1223  8012202

> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
              expr  min   lq median   uq      max
1 test1("trimmed")  733  792    843  944 60440833
2 test2("trimmed") 2022 2133   2203 2309 60814430

Final Update Here's showing how versatile switch is:

switch(type, case1=1, case2=, case3=2.5, 99)

This maps case2 and case3 to 2.5 and the (unnamed) default to 99. For more information, try ?switch

Connect over ssh using a .pem file

For AWS if the user is ubuntu use the following to connect to remote server.

chmod 400 mykey.pem

ssh -i mykey.pem ubuntu@your-ip

Iterating through a variable length array

here is an example, where the length of the array is changed during execution of the loop

import java.util.ArrayList;
public class VariableArrayLengthLoop {

public static void main(String[] args) {

    //create new ArrayList
    ArrayList<String> aListFruits = new ArrayList<String>();

    //add objects to ArrayList
    aListFruits.add("Apple");
    aListFruits.add("Banana");
    aListFruits.add("Orange");
    aListFruits.add("Strawberry");

    //iterate ArrayList using for loop
    for(int i = 0; i < aListFruits.size(); i++){

        System.out.println( aListFruits.get(i) + " i = "+i );
         if ( i == 2 ) {
                aListFruits.add("Pineapple");  
                System.out.println( "added now a Fruit to the List "); 
                }
        }
    }
}

mysql datetime comparison

...this is obviously performing a 'string' comparison

No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:

WHERE int_column = '1'

...where the string value of "1" is converted to an INTeger because int_column's data type is INT, not CHAR/VARCHAR/TEXT.

If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:

WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Java, Shifting Elements in an Array

Write a Java program to create an array of 20 integers, and then implement the process of shifting the array to right for two elements.

public class NewClass3 {
    
     public static void main (String args[]){
     
     int a [] = {1,2,};
    
     int temp ;
     
     for(int i = 0; i<a.length -1; i++){
      
         temp = a[i];
         a[i] = a[i+1];
         a[i+1] = temp;
     
     }
     
     for(int p : a)
     System.out.print(p);
     }
    
}

Preloading CSS Images

If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)

Which is better, return value or out parameter?

What's better, depends on your particular situation. One of the reasons out exists is to facilitate returning multiple values from one method call:

public int ReturnMultiple(int input, out int output1, out int output2)
{
    output1 = input + 1;
    output2 = input + 2;

    return input;
}

So one is not by definition better than the other. But usually you'd want to use a simple return, unless you have the above situation for example.

EDIT: This is a sample demonstrating one of the reasons that the keyword exists. The above is in no way to be considered a best practise.

Center div on the middle of screen

This should work with any div or screen size:

_x000D_
_x000D_
.center-screen {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  text-align: center;_x000D_
  min-height: 100vh;_x000D_
}
_x000D_
 <html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
 <div class="center-screen">_x000D_
 I'm in the center_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

See more details about flex here. This should work on most of the browsers, see compatibility matrix here.

Update: If you don't want the scroll bar, make min-height smaller, for example min-height: 95vh;

Wait until flag=true

In my example, I log a new counter value every second:

_x000D_
_x000D_
var promises_arr = [];_x000D_
var new_cntr_val = 0;_x000D_
_x000D_
// fill array with promises_x000D_
for (let seconds = 1; seconds < 10; seconds++) {_x000D_
    new_cntr_val = new_cntr_val + 5;    // count to 50_x000D_
    promises_arr.push(new Promise(function (resolve, reject) {_x000D_
        // create two timeouts: one to work and one to resolve the promise_x000D_
        setTimeout(function(cntr) {_x000D_
            console.log(cntr);_x000D_
        }, seconds * 1000, new_cntr_val);    // feed setTimeout the counter parameter_x000D_
        setTimeout(resolve, seconds * 1000);_x000D_
    }));_x000D_
}_x000D_
_x000D_
// wait for promises to finish_x000D_
Promise.all(promises_arr).then(function (values) {_x000D_
    console.log("all promises have returned");_x000D_
});
_x000D_
_x000D_
_x000D_

How can I remove an SSH key?

If you're trying to perform an SSH-related operation and get the following error:

$ git fetch
no such identity: <ssh key path>: No such file or directory

You can remove the missing SSH key from your SSH agent with the following:

$ eval `ssh-agent -s`  # start ssh agent
$ ssh-add -D <ssh key path>  # delete ssh key

Convert comma separated string of ints to int array

Let us assume that you will be reading the string from the console. Import System.Linq and try this one:

int[] input = Console.ReadLine()
            .Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(int.Parse)
            .ToArray();

How to select records from last 24 hours using SQL?

SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

How do you do a limit query in JPQL or HQL?

The setFirstResult and setMaxResults Query methods

For a JPA and Hibernate Query, the setFirstResult method is the equivalent of OFFSET, and the setMaxResults method is the equivalent of LIMIT:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "order by p.createdOn ")
.setFirstResult(10)
.setMaxResults(10)
.getResultList();

The LimitHandler abstraction

The Hibernate LimitHandler defines the database-specific pagination logic, and as illustrated by the following diagram, Hibernate supports many database-specific pagination options:

LimitHandler implementations

Now, depending on the underlying relational database system you are using, the above JPQL query will use the proper pagination syntax.

MySQL

SELECT p.id AS id1_0_,
       p.created_on AS created_2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?, ?

PostgreSQL

SELECT p.id AS id1_0_,
       p.created_on AS created_2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?

SQL Server

SELECT p.id AS id1_0_,
       p.created_on AS created_on2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
OFFSET ? ROWS 
FETCH NEXT ? ROWS ONLY

Oracle

SELECT *
FROM (
    SELECT 
        row_.*, rownum rownum_
    FROM (
        SELECT 
            p.id AS id1_0_,
            p.created_on AS created_on2_0_,
            p.title AS title3_0_
        FROM post p
        ORDER BY p.created_on
    ) row_
    WHERE rownum <= ?
)
WHERE rownum_ > ?

The advantage of using setFirstResult and setMaxResults is that Hibernate can generate the database-specific pagination syntax for any supported relational databases.

And, you are not limited to JPQL queries only. You can use the setFirstResult and setMaxResults method seven for native SQL queries.

Native SQL queries

You don't have to hardcode the database-specific pagination when using native SQL queries. Hibernate can add that to your queries.

So, if you're executing this SQL query on PostgreSQL:

List<Tuple> posts = entityManager
.createNativeQuery(
    "SELECT " +
    "   p.id AS id, " +
    "   p.title AS title " +
    "from post p " +
    "ORDER BY p.created_on", Tuple.class)
.setFirstResult(10)
.setMaxResults(10)
.getResultList();

Hibernate will transform it as follows:

SELECT p.id AS id,
       p.title AS title
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?

Cool, right?

Beyond SQL-based pagination

Pagination is good when you can index the filtering and sorting criteria. If your pagination requirements imply dynamic filtering, it's a much better approach to use an inverted-index solution, like ElasticSearch.

Difference between a View's Padding and Margin

Padding is the space inside the border between the border and the actual image or cell contents. Margins are the spaces outside the border, between the border and the other elements next to this object.

How do I create a slug in Django?

You will need to use the slugify function.

>>> from django.template.defaultfilters import slugify
>>> slugify("b b b b")
u'b-b-b-b'
>>>

You can call slugify automatically by overriding the save method:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    
    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(Test, self).save(*args, **kwargs)

Be aware that the above will cause your URL to change when the q field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    
    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.s = slugify(self.q)

        super(Test, self).save(*args, **kwargs)

Execute action when back bar button of UINavigationController is pressed

Swift 5 __ Xcode 11.5

In my case I wanted to make an animation, and when it finished, go back. A way to overwrite the default action of the back button and call your custom action is this:

     override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setBtnBack()
    }

    private func setBtnBack() {
        for vw in navigationController?.navigationBar.subviews ?? [] where "\(vw.classForCoder)" == "_UINavigationBarContentView" {
            print("\(vw.classForCoder)")
            for subVw in vw.subviews where "\(subVw.classForCoder)" == "_UIButtonBarButton" {
                let ctrl = subVw as! UIControl
                ctrl.removeTarget(ctrl.allTargets.first, action: nil, for: .allEvents)
                ctrl.addTarget(self, action: #selector(backBarBtnAction), for: .touchUpInside)
            }
        }
    }


    @objc func backBarBtnAction() {
        doSomethingBeforeBack { [weak self](isEndedOk) in
            if isEndedOk {
                self?.navigationController?.popViewController(animated: true)
            }
        }
    }


    private func doSomethingBeforeBack(completion: @escaping (_ isEndedOk:Bool)->Void ) {
        UIView.animate(withDuration: 0.25, animations: { [weak self] in
            self?.vwTxt.alpha = 0
        }) { (isEnded) in
            completion(isEnded)
        }
    }

NavigationBar view hierarchy

Or you can use this method one time to explore the NavigationBar view hierarchy, and get the indexes to access to the _UIButtonBarButton view, cast to UIControl, remove the target-action, and add your custom targets-actions:

    private func debug_printSubviews(arrSubviews:[UIView]?, level:Int) {
        for (i,subVw) in (arrSubviews ?? []).enumerated() {
            var str = ""
            for _ in 0...level {
                str += "\t"
            }
            str += String(format: "%2d %@",i, "\(subVw.classForCoder)")
            print(str)
            debug_printSubviews(arrSubviews: subVw.subviews, level: level + 1)
        }
    }

    // Set directly the indexs
    private func setBtnBack_method2() {
        // Remove or comment the print lines
        debug_printSubviews(arrSubviews: navigationController?.navigationBar.subviews, level: 0)   
        let ctrl = navigationController?.navigationBar.subviews[1].subviews[0] as! UIControl
        print("ctrl.allTargets: \(ctrl.allTargets)")
        ctrl.removeTarget(ctrl.allTargets.first, action: nil, for: .allEvents)
        print("ctrl.allTargets: \(ctrl.allTargets)")
        ctrl.addTarget(self, action: #selector(backBarBtnAction), for: .touchUpInside)
        print("ctrl.allTargets: \(ctrl.allTargets)")
    }

How do I remove background-image in css?

Since in css3 one might set multiple background images setting "none" will only create a new layer and hide nothing.

http://www.css3.info/preview/multiple-backgrounds/ http://www.w3.org/TR/css3-background/#backgrounds

I have not found a solution yet...

Trim last character from a string

I took the path of writing an extension using the TrimEnd just because I was already using it inline and was happy with it... i.e.:

static class Extensions
{
        public static string RemoveLastChars(this String text, string suffix)
        {            
            char[] trailingChars = suffix.ToCharArray();

            if (suffix == null) return text;
            return text.TrimEnd(trailingChars);
        }

}

Make sure you include the namespace in your classes using the static class ;P and usage is:

string _ManagedLocationsOLAP = string.Empty;
_ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");          

HTML table with fixed headers and a fixed column?

<script>
   $(document).ready(function () {
   $("#GridHeader table").html($('#<%= GridView1.ClientID %>').html());
   $("#GridHeader table tbody .rows").remove();
   $('#<%= GridView1.ClientID %> tr:first th').hide();
});
</script>

<div id="GridHeader">
    <table></table>
</div>

<div style="overflow: auto; height:400px;">
    <asp:GridView ID="GridView1" runat="server" />
</div>

Bootstrap 3: how to make head of dropdown link clickable in navbar

This topic is super old, but I needed a solution that worked on desktop AND mobile and none of these seemed to work for me. Unfortunately, this is the solution I came up with that involves checking the window width and comparing it to the mobile menu breakpoint:

$( 'a.dropdown-toggle' ).on( 'click', function( e ) {
    var $a = $( this ),
        $parent = $a.parent( 'li' ),
        mobile_bp = 767, // Default breakpoint, may need to change this.
        window_width = $( window ).width(),
        is_mobile = window_width <= mobile_bp;

    if ( is_mobile && ! $parent.hasClass( 'open' ) ) {
        e.preventDefault();
        return false;
    }

    location.href = $a.attr( 'href' );
    return true;
});

Web.Config Debug/Release

The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

This will cause each connection string line to find the matching name and update the attributes accordingly.

Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

Here's an example from one of my apps. Here's the web.config file section:

<connectionStrings>
      <add name="EAF" connectionString="[Test Connection String]" />
</connectionString>

And here's the web.config.release section doing the proper transform:

<connectionStrings>
      <add name="EAF" connectionString="[Prod Connection String]"
           xdt:Transform="SetAttributes"
           xdt:Locator="Match(name)" />
</connectionStrings>

One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

For more details you can see the MSDN documentation

https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

How to center a WPF app on screen?

Put this in your window constructor

WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

.NET FrameworkSupported in: 4, 3.5, 3.0

.NET Framework Client ProfileSupported in: 4, 3.5 SP1

How do I use the includes method in lodash to check if an object is in the collection?

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

Cannot find "Package Explorer" view in Eclipse

Try Window > Open Perspective > Java Browsing or some other Java perspectives

What is HEAD in Git?

After reading all of the previous answers, I still wanted more clarity. This blog at the official git website http://git-scm.com/blog gave me what I was looking for:

The HEAD: Pointer to last commit snapshot, next parent

The HEAD in Git is the pointer to the current branch reference, which is in turn a pointer to the last commit you made or the last commit that was checked out into your working directory. That also means it will be the parent of the next commit you do. It's generally simplest to think of it as HEAD is the snapshot of your last commit.

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

Here's a solution using a negative lookahead (not supported in all regex engines):

^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$

Test that it works as expected:

import re
tests = [
   ('a', True),
   ('_', False),
   ('zz', True),
   ('a0', True),
   ('A_', False),
   ('a0_b', True),
   ('a__b', False),
   ('a_1_c', True),
]

regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
   is_match = re.match(regex, test[0]) is not None
   if is_match != test[1]:
       print "fail: "  + test[0]

Can git undo a checkout of unstaged files

Dude,

lets say you're a very lucky guy just like I've been, go back to your editor and do an undo(command + Z for mac), you should see your lost content in the file. Hope it helped you. Of course, this will work only for existing files.

google chrome extension :: console.log() from background page?

It's an old post, with already good answers, but I add my two bits. I don't like to use console.log, I'd rather use a logger that logs to the console, or wherever I want, so I have a module defining a log function a bit like this one

function log(...args) {
  console.log(...args);
  chrome.extension.getBackgroundPage().console.log(...args);
}

When I call log("this is my log") it will write the message both in the popup console and the background console.

The advantage is to be able to change the behaviour of the logs without having to change the code (like disabling logs for production, etc...)

What is the best way to ensure only one instance of a Bash script is running?

i found this in procmail package dependencies:

apt install liblockfile-bin

To run: dotlockfile -l file.lock

file.lock will be created.

To unlock: dotlockfile -u file.lock

Use this to list this package files / command: dpkg-query -L liblockfile-bin

Unable to connect PostgreSQL to remote database using pgAdmin

Connecting to PostgreSQL via SSH Tunneling

In the event that you don't want to open port 5432 to any traffic, or you don't want to configure PostgreSQL to listen to any remote traffic, you can use SSH Tunneling to make a remote connection to the PostgreSQL instance. Here's how:

  1. Open PuTTY. If you already have a session set up to connect to the EC2 instance, load that, but don't connect to it just yet. If you don't have such a session, see this post.
  2. Go to Connection > SSH > Tunnels
  3. Enter 5433 in the Source Port field.
  4. Enter 127.0.0.1:5432 in the Destination field.
  5. Click the "Add" button.
  6. Go back to Session, and save your session, then click "Open" to connect.
  7. This opens a terminal window. Once you're connected, you can leave that alone.
  8. Open pgAdmin and add a connection.
  9. Enter localhost in the Host field and 5433 in the Port field. Specify a Name for the connection, and the username and password. Click OK when you're done.

HTML Code for text checkbox '?'

Use the Unicode Character

&#10004;   =   ✔


formGroup expects a FormGroup instance

There are a few issues in your code

  • <div [formGroup]="form"> outside of a <form> tag
  • <form [formGroup]="form"> but the name of the property containing the FormGroup is loginForm therefore it should be <form [formGroup]="loginForm">
  • [formControlName]="dob" which passes the value of the property dob which doesn't exist. What you need is to pass the string dob like [formControlName]="'dob'" or simpler formControlName="dob"

Plunker example

How to setup FTP on xampp

XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.

Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :

  1. Open a new Linux terminal and ensure you are logged in as root.

  2. Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.

groupadd ftp

  1. Add your account (in this example, susan) to the new group. Add other users if needed.

usermod -a -G ftp susan

  1. Change the ownership and permissions of the htdocs/ subdirectory of the XAMPP installation directory (typically, /opt/lampp) so that it is writable by the the new ftp group.

cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs

  1. Ensure that proFTPD is running in the XAMPP control panel.

You can now transfer files to the XAMPP server using the steps below:

  1. Start an FTP client like winSCP or FileZilla and enter connection details as below.

If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.

Use "21" as the port.

Enter your Linux username and password as your FTP credentials.

Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.

  1. Transfer the file from your home directory to the server using normal FTP transfer conventions. If you’re using a graphical FTP client, you can usually drag and drop the file from one directory to the other. If you’re using a command-line FTP client, you can use the FTP PUT command.

Once the file is successfully transferred, you should be able to see it in action.

Java; String replace (using regular expressions)?

Try this, may not be the best way. but it works

String str = "5 * x^3 - 6 * x^1 + 1";
str = str.replaceAll("(?x)(\\d+)(\\s+?\\*?\\s+?)(\\w+?)(\\^+?)(\\d+?)", "$1$3<sup>$5</sup>");
System.out.println(str);

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

Set selected item of spinner programmatically

public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}

You can use the above like:

selectSpinnerItemByValue(spinnerObject, desiredValue);

& of course you can also select by index directly like

spinnerObject.setSelection(index);

"Series objects are mutable and cannot be hashed" error

gene_name = no_headers.iloc[1:,[1]]

This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:

gene_name[x]

you now have a Series object with a single value. You can't hash the Series.

The solution is to create Series from the start.

gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]

Also, where you have orph_dict[gene_name[x]] =+ 1, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1 to increment the counter.

Java equivalent to Explode and Implode(PHP)

Good alternatives are the String.split and StringUtils.join methods.

Explode :

String[] exploded="Hello World".split(" ");

Implode :

String imploded=StringUtils.join(new String[] {"Hello", "World"}, " ");

Keep in mind though that StringUtils is in an external library.

How to show the text on a ImageButton?

I solved this by putting the ImageButton and TextView inside a LinearLayout with vertical orientation. Works great!

<LinearLayout
    android:id="@+id/linLayout"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageButton
        android:id="@+id/camera_ibtn"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:background="@drawable/camera" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/take_pic"
        android:textColor="#FFFFFF"
        android:textStyle="bold" />

</LinearLayout>

How to fix the height of a <div> element?

If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:

overflow: hidden;

iOS 8 UITableView separator inset 0 not working

iOS introduces the layoutMargins property on cells AND table views.

This property isn't available in iOS 7.0 so you need to make sure you check before assigning it!

However, Apple has added a property called preservesSuperviewLayoutMargins to your cell that will prevent it from inheriting your Table View's margin settings. This way, your cells can configure their own margins independently of the table view. Think of it as an override.

This property is called preservesSuperviewLayoutMargins, and setting it to NO can allow you to override your Table View's layoutMargin settings with your own cell's layoutMargin setting. It both saves time (you don't have to modify the Table View's settings), and is more concise. Please refer to Mike Abdullah's answer for a detailed explanation.

NOTE: this is the proper, less messy implementation, as expressed in Mike Abdullah's answer; setting your cell's preservesSuperviewLayoutMargins=NO will ensure that your Table View does not override the cell settings.

First step - Setup your cell margins:

/*
    Tells the delegate that the table view is about to draw a cell for a particular row.
*/
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath)
{
    // Remove separator inset
    if cell.respondsToSelector("setSeparatorInset:") {
        cell.separatorInset = UIEdgeInsetsZero
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:") {
        cell.preservesSuperviewLayoutMargins = false
    }

    // Explictly set your cell's layout margins
    if cell.respondsToSelector("setLayoutMargins:") {
        cell.layoutMargins = UIEdgeInsetsZero
    }
}

Setting the preservesSuperviewLayoutMargins property on your cell to NO should prevent your table view from overriding your cell margins. In some cases, it seems not to function properly.

Second step - Only if all fails, you may brute-force your Table View margins:

/*
    Called to notify the view controller that its view has just laid out its subviews.
*/
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // Force your tableview margins (this may be a bad idea)
    if self.tableView.respondsToSelector("setSeparatorInset:") {
        self.tableView.separatorInset = UIEdgeInsetsZero
    }

    if self.tableView.respondsToSelector("setLayoutMargins:") {
        self.tableView.layoutMargins = UIEdgeInsetsZero
    }
}

...and there you go! This should work on iOS 8 as well as iOS 7.

Note: tested using iOS 8.1 and 7.1, in my case I only needed to use the first step of this explanation.

The Second Step is only required if you have unpopulated cell beneath the rendered cells, ie. if the table is larger than the number of rows in the table model. Not doing the second step would result in different separator offsets.

How to add constraints programmatically using Swift

Auto layout is realized by applying constraints on images. Use NSLayoutConstraint. It is possible to implement an ideal and beautiful design on all devices. Please try the code below.

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let myImageView:UIImageView = UIImageView()
myImageView.backgroundColor = UIColor.red
myImageView.image = UIImage(named:"sample_dog")!
myImageView.translatesAutoresizingMaskIntoConstraints = false
myImageView.layer.borderColor = UIColor.red.cgColor
myImageView.layer.borderWidth = 10
self.view.addSubview(myImageView)
        
view.removeConstraints(view.constraints)


view.addConstraint(NSLayoutConstraint(
item: myImageView,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1,
constant:100)
    
)

view.addConstraint(NSLayoutConstraint(
item: myImageView,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1,
constant:0)
)
    
view.addConstraint(NSLayoutConstraint(
item: myImageView,
attribute: .height,
relatedBy: .equal,
toItem: view,
attribute: .width,
multiplier: 0.5,
constant:40))
    
view.addConstraint(NSLayoutConstraint(
item: myImageView,
attribute: .width,
relatedBy: .equal,
toItem: view,
attribute: .width,
multiplier: 0.5,
constant:40))
    
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

enter image description here enter image description here

File size exceeds configured limit (2560000), code insight features not available

For those who don't know where to find the file they're talking about. On my machine (OSX) it is in:

  • PyCharm CE: /Applications/PyCharm CE.app/Contents/bin/idea.properties
  • WebStorm: /Applications/WebStorm.app/Contents/bin/idea.properties

How do I make a self extract and running installer

It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.

Jquery - How to get the style display attribute "none / block"

If you're using jquery 1.6.2 you only need to code

$('#theid').css('display')

for example:

if($('#theid').css('display') == 'none'){ 
   $('#theid').show('slow'); 
} else { 
   $('#theid').hide('slow'); 
}

HorizontalScrollView within ScrollView Touch Handling

I think I found a simpler solution, only this uses a subclass of ViewPager instead of (its parent) ScrollView.

UPDATE 2013-07-16: I added an override for onTouchEvent as well. It could possibly help with the issues mentioned in the comments, although YMMV.

public class UninterceptableViewPager extends ViewPager {

    public UninterceptableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean ret = super.onInterceptTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean ret = super.onTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }
}

This is similar to the technique used in android.widget.Gallery's onScroll(). It is further explained by the Google I/O 2013 presentation Writing Custom Views for Android.

Update 2013-12-10: A similar approach is also described in a post from Kirill Grouchnikov about the (then) Android Market app.

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

accessing a docker container from another container

You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -

docker run --net=host --name oracle-wls wls-image:latest

See here

Git: add vs push vs commit

add -in git is used to tell git which files we want to commit, it puts files to the staging area

commit- in git is used to save files on to local machine so that if we make any changes or even delete the files we can still recover our committed files

push - if we commit our files on the local machine they are still prone to be lost if our local machine gets lost, gets damaged, etc, to keep our files safe or to share our files usually we want to keep our files on a remote repository like Github. To save on remote repositories we use push

example Staging a file named index.html git add index.html

Committing a file that is staged git commit -m 'name of your commit'

Pushing a file to Github git push origin master

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

SSRS will not accept duplicated columns so ensure that your query or store procedure is returning unique column names.

How to use classes from .jar files?

You need to add the jar file in the classpath. To compile your java class:

javac -cp .;jwitter.jar MyClass.java

To run your code (provided that MyClass contains a main method):

java -cp .;jwitter.jar MyClass

You can have the jar file anywhere. The above work if the jar file is in the same directory as your java file.

How to include a child object's child object in Entity Framework 5

With EF Core in .NET Core you can use the keyword ThenInclude :

return DatabaseContext.Applications
 .Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);

Include childs from childrens collection :

return DatabaseContext.Applications
 .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
 .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);

Cannot use string offset as an array in php

When you directly print print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>)); then it shows this fatal error Cannot use string offset as an object in. If you print like this

$var = $value['#node']-><YOU_OBJECT>; print_r($var);

You won't get the error!!

Border length smaller than div width?

You can use a linear gradient:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:50px;_x000D_
    display:block;_x000D_
    background-image: linear-gradient(to right, #000 1px, rgba(255,255,255,0) 1px), linear-gradient(to left, #000 0.1rem, rgba(255,255,255,0) 1px);_x000D_
 background-position: bottom;_x000D_
 background-size: 100% 25px;_x000D_
 background-repeat: no-repeat;_x000D_
    border-bottom: 1px solid #000;_x000D_
    border-top: 1px solid red;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Reading and displaying data from a .txt file

public class PassdataintoFile {

    public static void main(String[] args) throws IOException  {
        try {
            PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
            PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
             pw1.println("Hi chinni");
             pw1.print("your succesfully entered text into file");
             pw1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
           String line;
           while((line = br.readLine())!= null)
           {
               System.out.println(line);
           }
           br.close();
    }

}

How to concatenate two strings in SQL Server 2005

DECLARE @COMBINED_STRINGS AS VARCHAR(50),
        @STRING1 AS VARCHAR(20),
        @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;

SELECT @COMBINED_STRINGS;

SELECT '2' + '3';

I typed this in a sql file named TEST.sql and I run it. I got the following out put.

+-------------------+
| @COMBINED_STRINGS |
+-------------------+
|                 0 |
+-------------------+
1 row in set (0.00 sec)

+-----------+
| '2' + '3' |
+-----------+
|         5 |
+-----------+
1 row in set (0.00 sec)

After looking into this issue a bit more I found the best and sure sort way for string concatenation in SQL is by using CONCAT method. So I made the following changes in the same file.

#DECLARE @COMBINED_STRINGS AS VARCHAR(50),
 #       @STRING1 AS VARCHAR(20),
 #       @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
#SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SET @COMBINED_STRINGS = (SELECT CONCAT(@STRING1, @STRING2));

SELECT @COMBINED_STRINGS;

#SELECT '2' + '3';
SELECT CONCAT('2','3');

and after executing the file this was the output.

+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| rupesh'smalviya   |
+-------------------+
1 row in set (0.00 sec)

+-----------------+
| CONCAT('2','3') |
+-----------------+
| 23              |
+-----------------+
1 row in set (0.00 sec)

SQL version I am using is: 14.14

EXC_BAD_ACCESS signal received

Don't forget the @ symbol when creating strings, treating C-strings as NSStrings will cause EXC_BAD_ACCESS.

Use this:

@"Some String"

Rather than this:

"Some String"

PS - typically when populating contents of an array with lots of records.

How do I install a plugin for vim?

I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.

Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).

Store images in a MongoDB database

install below libraries

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

connect ur mongo db :

mongoose.connect(‘url_here’);

Define database Schema

var Item = new ItemSchema({ 
    img: { 
       data: Buffer, 
       contentType: String 
    }
 }
);
var Item = mongoose.model('Clothes',ItemSchema);

using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
  rename: function (fieldname, filename) {
    return filename;
  },
}));

post req to our db

app.post(‘/api/photo’,function(req,res){
  var newItem = new Item();
  newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
  newItem.img.contentType = ‘image/png’;
  newItem.save();
});

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

This error appears in my android project with multiple kind of gfx files. At the end no change in the manifest file was accepted.

Because my lack of knowledge about the android devices I forget that my test device has a second User. This User also has an installed version of my app so I also have to delete the app for this user account and it works.

Convert json data to a html table

Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.

Example:

var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${age}"}
        ]}
    ]}
]};

var data = [
    {'name':'Bob','age':40},
    {'name':'Frank','age':15},
    {'name':'Bill','age':65},
    {'name':'Robert','age':24}
];

$('#target_div').html(json2html.transform(data,transform));

Find and Replace text in the entire table using a MySQL query

Put this in a php file and run it and it should do what you want it to do.

// Connect to your MySQL database.
$hostname = "localhost";
$username = "db_username";
$password = "db_password";
$database = "db_name";

mysql_connect($hostname, $username, $password);

// The find and replace strings.
$find = "find_this_text";
$replace = "replace_with_this_text";

$loop = mysql_query("
    SELECT
        concat('UPDATE ',table_schema,'.',table_name, ' SET ',column_name, '=replace(',column_name,', ''{$find}'', ''{$replace}'');') AS s
    FROM
        information_schema.columns
    WHERE
        table_schema = '{$database}'")
or die ('Cant loop through dbfields: ' . mysql_error());

while ($query = mysql_fetch_assoc($loop))
{
        mysql_query($query['s']);
}

Is there a function to make a copy of a PHP array to another?

If you have only basic types in your array you can do this:

$copy = json_decode( json_encode($array), true);

You won't need to update the references manually
I know it won't work for everyone, but it worked for me

How can I center a div within another div?

Try this one if this is the output you want:

<div id="main_content" >
    <div id="container">
    </div>
</div>
#main_content {
    background-color: #2185C5;
    margin: 0 auto;
}

#container {
    width: 100px;
    height: auto;
    margin: 0 auto;
    padding: 10px;
    background: red;
}

Match whitespace but not newlines

m/ /g just give space in / /, and it will work. Or use \S — it will replace all the special characters like tab, newlines, spaces, and so on.

jQuery select box validation

Since you cannot set value="" within your first option, you'll need to create your own rule using the built-in addMethod() method.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                selectcheck: true
            }
        }
    });

    jQuery.validator.addMethod('selectcheck', function (value) {
        return (value != '0');
    }, "year required");

});

HTML:

<select name="year">
    <option value="0">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Working Demo: http://jsfiddle.net/tPRNd/


Original Answer: (Only if you can set value="" within the first option)

To properly validate a select element with the jQuery Validate plugin simply requires that the first option contains value="". So remove the 0 from value="0" and it's fixed.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                required: true,
            }
        }
    });

});

HTML:

<select name="year">
    <option value="">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Demo: http://jsfiddle.net/XGtEr/

HTML not loading CSS file

This may be a 'special' case but was fiddling with this piece of code:

ForceType application/x-httpd-php SetHandler application/x-httpd-php

As a quick test for extentionless file handling, when a similar problem occurred.

Some but not all php files thereafter treated the css files as php and thus succesfully loaded the css but not handled it as css, thus zero rules were executed when checking f12 style editor.

Perhaps something similar might occur to any-one else here and this tidbit might help.

How to check if a process is running via a batch script

Building on vtrz's answer and Samuel Renkert's answer on an other topic, I came up with the following script that only runs %EXEC_CMD% if it isn't already running:

@echo off
set EXEC_CMD="rsync.exe"
wmic process where (name=%EXEC_CMD%) get commandline | findstr /i %EXEC_CMD%> NUL
if errorlevel 1 (
    %EXEC_CMD% ...
) else (
    @echo not starting %EXEC_CMD%: already running.
)

As was said before, this requires administrative privileges.

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

You must check if result returned by mysql_query is false.

$r = mysql_qyery("...");
if ($r) {
  mysql_fetch_assoc($r);
}

You can use @mysql_fetch_assoc($r) to avoid error displaying.

'int' object has no attribute '__getitem__'

This error could be an indication that variable with the same name has been used in your code earlier, but for other purposes. Possibly, a variable has been given a name that coincides with the existing function used later in the code.

What are my options for storing data when using React Native? (iOS and Android)

Quick and dirty: just use Redux + react-redux + redux-persist + AsyncStorage for react-native.

It fits almost perfectly the react native world and works like a charm for both android and ios. Also, there is a solid community around it, and plenty of information.

For a working example, see the F8App from Facebook.

What are the different options for data persistence?

With react native, you probably want to use redux and redux-persist. It can use multiple storage engines. AsyncStorage and redux-persist-filesystem-storage are the options for RN.

There are other options like Firebase or Realm, but I never used those on a RN project.

For each, what are the limits of that persistence (i.e., when is the data no longer available)? For example: when closing the application, restarting the phone, etc.

Using redux + redux-persist you can define what is persisted and what is not. When not persisted, data exists while the app is running. When persisted, the data persists between app executions (close, open, restart phone, etc).

AsyncStorage has a default limit of 6MB on Android. It is possible to configure a larger limit (on Java code) or use redux-persist-filesystem-storage as storage engine for Android.

For each, are there differences (other than general setup) between implementing in iOS vs Android?

Using redux + redux-persist + AsyncStorage the setup is exactly the same on android and iOS.

How do the options compare for accessing data offline? (or how is offline access typically handled?)

Using redux, offiline access is almost automatic thanks to its design parts (action creators and reducers).

All data you fetched and stored are available, you can easily store extra data to indicate the state (fetching, success, error) and the time it was fetched. Normally, requesting a fetch does not invalidate older data and your components just update when new data is received.

The same apply in the other direction. You can store data you are sending to server and that are still pending and handle it accordingly.

Are there any other considerations I should keep in mind?

React promotes a reactive way of creating apps and Redux fits very well on it. You should try it before just using an option you would use in your regular Android or iOS app. Also, you will find much more docs and help for those.

How to display count of notifications in app launcher icon

Android ("vanilla" android without custom launchers and touch interfaces) does not allow changing of the application icon, because it is sealed in the .apk tightly once the program is compiled. There is no way to change it to a 'drawable' programmatically using standard APIs. You may achieve your goal by using a widget instead of an icon. Widgets are customisable. Please read this :http://www.cnet.com/8301-19736_1-10278814-251.html and this http://developer.android.com/guide/topics/appwidgets/index.html. Also look here: https://github.com/jgilfelt/android-viewbadger. It can help you.

As for badge numbers. As I said before - there is no standard way for doing this. But we all know that Android is an open operating system and we can do everything we want with it, so the only way to add a badge number - is either to use some 3-rd party apps or custom launchers, or front-end touch interfaces: Samsung TouchWiz or Sony Xperia's interface. Other answers use this capabilities and you can search for this on stackoverflow, e.g. here. But I will repeat one more time: there is no standard API for this and I want to say it is a bad practice. App's icon notification badge is an iOS pattern and it should not be used in Android apps anyway. In Andrioid there is a status bar notifications for these purposes:http://developer.android.com/guide/topics/ui/notifiers/notifications.html So, if Facebook or someone other use this - it is not a common pattern or trend we should consider. But if you insist anyway and don't want to use home screen widgets then look here, please:

How does Facebook add badge numbers on app icon in Android?

As you see this is not an actual Facebook app it's TouchWiz. In vanilla android this can be achieved with Nova Launcher http://forums.androidcentral.com/android-applications/199709-how-guide-global-badge-notifications.html So if you will see icon badges somewhere, be sure it is either a 3-rd party launcher or touch interface (frontend wrapper). May be sometime Google will add this capability to the standard Android API.

Import XXX cannot be resolved for Java SE standard classes

Right click on project - >BuildPath - >Configure BuildPath - >Libraries tab - >

Double click on JRE SYSTEM LIBRARY - >Then select alternate JRE

How to change bower's default components folder?

Create a Bower configuration file .bowerrc in the project root (as opposed to your home directory) with the content:

{
  "directory" : "public/components"
}

Run bower install again.

How to compile Go program consisting of multiple files?

Yup! That's very straight forward and that's where the package strategy comes into play. there are three ways to my knowledge. folder structure:

GOPATH/src/ github.com/ abc/ myproject/ adapter/ main.go pkg1 pkg2 warning: adapter can contain package main only and sun directories

  1. navigate to "adapter" folder. Run:
    go build main.go
  1. navigate to "adapter" folder. Run:
    go build main.go
  1. navigate to GOPATH/src recognize relative path to package main, here "myproject/adapter". Run:
    go build myproject/adapter

exe file will be created at the directory you are currently at.

How to implement HorizontalScrollView like Gallery?

Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.

EDIT

In This example, all you need to do is add this line:

gallery.setSelection(1);

after setting the adapter to gallery object, that is this line:

gallery.setAdapter(new ImageAdapter(this));

UPDATE1

Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.

UPDATE2:

I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.

How do I set an absolute include path in PHP?

The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.

So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.

ini_set("include_path", "/your_include_path:".ini_get("include_path"));

This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You will have to use the fluent API to do this.

Try adding the following to your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
   g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:

CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

Jenkins pipeline if else not working

        if ( params.build_deploy == '1' ) {
            println "build_deploy ? ${params.build_deploy}"
              jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
                         string(name:'environment', value: "${params.environment}"),
                         string(name:'branch_name', value: "${params.branch_name}"),
                         string(name:'service_name', value: "${params.service_name}"),                      
                     ]
            println jobB.getResult()
        }

Convert hexadecimal string (hex) to a binary string

import java.util.*;
public class HexadeciamlToBinary
{
   public static void main()
   {
       Scanner sc=new Scanner(System.in);
       System.out.println("enter the hexadecimal number");
       String s=sc.nextLine();
       String p="";
       long n=0;
       int c=0;
       for(int i=s.length()-1;i>=0;i--)
       {
          if(s.charAt(i)=='A')
          {
             n=n+(long)(Math.pow(16,c)*10);
             c++;
          }
         else if(s.charAt(i)=='B')
         {
            n=n+(long)(Math.pow(16,c)*11);
            c++;
         }
        else if(s.charAt(i)=='C')
        {
            n=n+(long)(Math.pow(16,c)*12);
            c++;
        }
        else if(s.charAt(i)=='D')
        {
           n=n+(long)(Math.pow(16,c)*13);
           c++;
        }
        else if(s.charAt(i)=='E')
        {
            n=n+(long)(Math.pow(16,c)*14);
            c++;
        }
        else if(s.charAt(i)=='F')
        {
            n=n+(long)(Math.pow(16,c)*15);
            c++;
        }
        else
        {
            n=n+(long)Math.pow(16,c)*(long)s.charAt(i);
            c++;
        }
    }
    String s1="",k="";
    if(n>1)
    {
    while(n>0)
    {
        if(n%2==0)
        {
            k=k+"0";
            n=n/2;
        }
        else
        {
            k=k+"1";
            n=n/2;
        }
    }
    for(int i=0;i<k.length();i++)
    {
        s1=k.charAt(i)+s1;
    }
    System.out.println("The respective binary number is : "+s1);
    }
    else
    {
        System.out.println("The respective binary number is : "+n);
    }
  }
}

How to get URL of current page in PHP

if you want just the parts of url after http://domain.com, try this:

<?php echo $_SERVER['REQUEST_URI']; ?>

if the current url was http://domain.com/some-slug/some-id, echo will return only '/some-slug/some-id'.

if you want the full url, try this:

<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>

Accessing variables from other functions without using global variables

I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:

var MyApp = {}; // Globally scoped object

function foo(){
    MyApp.color = 'green';
}

function bar(){
    alert(MyApp.color); // Alerts 'green'
} 

No one should yell at you for doing something like the above.

How to test that no exception is thrown?

You can do it by using a @Rule and then call method reportMissingExceptionWithMessage as shown below: This is Scala code.

enter image description here

How to find the index of an element in an array in Java?

The problem with your code is that when you do

 list[] == "e"

you're asking if the array object (not the contents) is equal to the string "e", which is clearly not the case.

You'll want to iterate over the contents in order to do the check you want:

 for(String element : list) {
      if (element.equals("e")) {
           // do something here
      }
 }

Trim spaces from start and end of string

Here, this should do all that you need

function doSomething(input) {
    return input
              .replace(/^\s\s*/, '')     // Remove Preceding white space
              .replace(/\s\s*$/, '')     // Remove Trailing white space
              .replace(/([\s]+)/g, '-'); // Replace remaining white space with dashes
}

alert(doSomething("  something with  some       whitespace   "));

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

Issue: The Jet OLE DB provider reads a registry key to determine how many rows are to be read to guess the type of the source column. By default, the value for this key is 8. Hence, the provider scans the first 8 rows of the source data to determine the data types for the columns. If any field looks like text and the length of data is more than 255 characters, the column is typed as a memo field. So, if there is no data with a length greater than 255 characters in the first 8 rows of the source, Jet cannot accurately determine the nature of the data type. As the first 8 row length of data in the exported sheet is less than 255 its considering the source length as VARCHAR(255) and unable to read data from the column having more length.

Fix: The solution is just to sort the comment column in descending order. In 2012 onwards we can update the values in Advance tab in the Import wizard.

Fatal error: Call to undefined function mb_strlen()

The function mb_strlen() is not enabled by default in PHP. Please read the manual for installation details:

http://www.php.net/manual/en/mbstring.installation.php

Parsing query strings on Android

public static Map<String, List<String>> getUrlParameters(String url)
        throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    String[] urlParts = url.split("\\?");
    if (urlParts.length > 1) {
        String query = urlParts[1];
        for (String param : query.split("&")) {
            String pair[] = param.split("=", 2);
            String key = URLDecoder.decode(pair[0], "UTF-8");
            String value = "";
            if (pair.length > 1) {
                value = URLDecoder.decode(pair[1], "UTF-8");
            }
            List<String> values = params.get(key);
            if (values == null) {
                values = new ArrayList<String>();
                params.put(key, values);
            }
            values.add(value);
        }
    }
    return params;
}

SSL peer shut down incorrectly in Java

That is a problem of security protocol. I am using TLSv1 but the host accept only TLSv1.1 and TLSv1.2 then I changed the protocol in Java with the instruction below:

System.setProperty("https.protocols", "TLSv1.1");

Selecting non-blank cells in Excel with VBA

This might be completely off base, but can't you just copy the whole column into a new spreadsheet and then sort the column? I'm assuming that you don't need to maintain the order integrity.

How do I convert number to string and pass it as argument to Execute Process Task?

Cause of the issue:

Arguments property in Execute Process Task available on the Control Flow tab is expecting a value of data type DT_WSTR and not DT_STR.

SSIS 2008 R2 package illustrating the issue and fix:

Create an SSIS package in Business Intelligence Development Studio (BIDS) 2008 R2 and name it as SO_13177007.dtsx. Create a package variable with the following information.

Name   Scope        Data Type  Value
------ ------------ ---------- -----
IdVar  SO_13177007  Int32      123

Variables pane

Drag and drop an Execute Process Task onto the Control Flow tab and name it as Pass arguments

Control Flow tab

Double-click the Execute Process Task to open the Execute Process Task Editor. Click Expressions page and then click the Ellipsis button against the Expressions property to view the Property Expression Editor.

Execute Process Task Editor

On the Property Expression Editor, select the property Arguments and click the Ellipsis button against the property to open the Expression Builder.

Property Expression Editor

On the Expression Builder, enter the following expression and click Evaluate Expression. This expression tries to convert the integer value in the variable IdVar to string data type.

(DT_STR, 10, 1252) @[User::IdVar]

Expression Builder - DT_STR

Clicking Evaluate Expression will display the following error message because the Arguments property on Execute Process Task expects a value of data type DT_WSTR.

Integer to ANSI string conversion error

To fix the issue, update the expression as shown below to convert the integer value to data type DT_WSTR. Clicking Evaluate Expression will display the value in the Evaluated value text area.

(DT_WSTR, 10) @[User::IdVar]

Expression Builder - DT_WSTR

References:

To understand the differences between the data types DT_STR and DT_WSTR in SSIS, read the documentation Integration Services Data Types on MSDN. Here are the quotes from the documentation about these two string data types.

DT_STR

A null-terminated ANSI/MBCS character string with a maximum length of 8000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

DT_WSTR

A null-terminated Unicode character string with a maximum length of 4000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I added in android.support.design.widget.NawigationView this parameter:

android:layout_gravity="start"

And problem was solved.

Can I stretch text using CSS?

Always coming back to this page when a designer stretches a font on me. The accepted solution works great, but I frequently run into issues with margins.

Would recommend using the transform on the height instead of the width if you're running into issues, was a life safer for me in my current project.

.font-stretch {
    display: inline-block;
    -webkit-transform: scale(1,.9);
    -moz-transform: scale(1,.9);
    -ms-transform: scale(1,.9);
    -o-transform: scale(1,.9);
    transform: scale(1,.9);
}

How to run Spyder in virtual environment?

There is an option to create virtual environments in Anaconda with required Python version.

conda create -n myenv python=3.4

To activate it :

source activate myenv   # (in linux, you can use . as a shortcut for "source")
activate myenv          # (in windows - note that you should be in your c:\anaconda2 directory)

UPDATE. I have tested it with Ubuntu 18.04. Now you have to install spyder additionally for the new environment with this command (after the activation of the environment with the command above):

conda install spyder

(I have also tested the installation with pip, but for Python 3.4 or older versions, it breaks with the library dependencies error that requires manual installation.)

And now to run Spyder with Python 3.4 just type:

spyder

Spyder with Python 3.4

EDIT from a reader:

For a normal opening, use "Anaconda Prompt" > activate myenv > spyder (then the "Anaconda Prompt" must stay open, you cannot use it for other commands, and a force-close will shut down Spyder). This is of course faster than the long load of "Anaconda Navigator" > switch environment > launch Spyder (@adelriosantiago's answer).

Two inline-block, width 50% elements wrap to second line

You can remove the whitespaces via css using white-space so you can keep your pretty HTML layout. Don't forget to set the white-space back to normal again if you want your text to wrap inside the columns.

Tested in IE9, Chrome 18, FF 12

.container { white-space: nowrap; }
.column { display: inline-block; width: 50%; white-space: normal; }

<div class="container">
  <div class="column">text that can wrap</div>
  <div class="column">text that can wrap</div>
</div>