Programs & Examples On #Recess

Recess is an open source RESTful PHP framework designed to give you a fun & delightful development experience.

How to post JSON to PHP with curl

You need to set a few extra flags so that curl sends the data as JSON.

command

$ curl -H "Content-Type: application/json" \
       -X POST \
       -d '{"JSON": "HERE"}' \
       http://localhost:3000/api/url

flags

  • -H: custom header, next argument is expected to be header
  • -X: custom HTTP verb, next argument is expected to be verb
  • -d: sends the next argument as data in an HTTP POST request

resources

linq query to return distinct field values from a list of objects

Assuming you want the full object, but only want to deal with distinctness by typeID, there's nothing built into LINQ to make this easy. (If you just want the typeID values, it's easy - project to that with Select and then use the normal Distinct call.)

In MoreLINQ we have the DistinctBy operator which you could use:

var distinct = list.DistinctBy(x => x.typeID);

This only works for LINQ to Objects though.

You can use a grouping or a lookup, it's just somewhat annoying and inefficient:

var distinct = list.GroupBy(x => x.typeID, (key, group) => group.First());

simple vba code gives me run time error 91 object variable or with block not set

Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.

Override intranet compatibility mode IE8

I had struggled with this issue and wanted to help provide a unique solution and insight.

Certain AJAX based frameworks will inject javascripts and stylesheets at the beginning of the <head> and doing this seems to prevent the well-established meta tag solution from working properly. In this case I found that directly injecting into the HTTP response header, much like Andras Csehi's answer will solve the problem.

For those of us using Java Servlets however, a good way to solve this is to use a ServletFilter.

public class EmulateFilter implements Filter {

@Override
public void destroy() {
}

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
        FilterChain arg2) throws IOException, ServletException {
    HttpServletResponse response = ((HttpServletResponse)arg1);
    response.addHeader("X-UA-Compatible", "IE=8");
    arg2.doFilter(arg0, arg1);
}

@Override
public void init(FilterConfig arg0) throws ServletException {
}

}

Plot multiple columns on the same graph in R

The easiest is to convert your data to a "tall" format.

s <- 
"A       B        C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23
"
d <- read.delim(textConnection(s), sep="")

library(ggplot2)
library(reshape2)
d <- melt(d, id.vars="Xax")

# Everything on the same plot
ggplot(d, aes(Xax,value, col=variable)) + 
  geom_point() + 
  stat_smooth() 

# Separate plots
ggplot(d, aes(Xax,value)) + 
  geom_point() + 
  stat_smooth() +
  facet_wrap(~variable)

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

How do I create a random alpha-numeric string in C++?

Be ware when calling the function

string gen_random(const int len) {
static const char alphanum[] = "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

stringstream ss;

for (int i = 0; i < len; ++i) {
    ss << alphanum[rand() % (sizeof(alphanum) - 1)];
}
return ss.str();
}

(adapted of @Ates Goral) it will result in the same character sequence every time. Use

srand(time(NULL));

before calling the function, although the rand() function is always seeded with 1 @kjfletch.

For Example:

void SerialNumberGenerator() {

    srand(time(NULL));
    for (int i = 0; i < 5; i++) {
        cout << gen_random(10) << endl;
    }
}

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

When to use Hadoop, HBase, Hive and Pig?

I worked on Lambda architecture processing Real time and Batch loads. Real time processing is needed where fast decisions need to be taken in case of Fire alarm send by sensor or fraud detection in case of banking transactions. Batch processing is needed to summarize data which can be feed into BI systems.

we used Hadoop ecosystem technologies for above applications.

Real Time Processing

Apache Storm: Stream Data processing, Rule application

HBase: Datastore for serving Realtime dashboard

Batch Processing Hadoop: Crunching huge chunk of data. 360 degrees overview or adding context to events. Interfaces or frameworks like Pig, MR, Spark, Hive, Shark help in computing. This layer needs scheduler for which Oozie is good option.

Event Handling layer

Apache Kafka was first layer to consume high velocity events from sensor. Kafka serves both Real Time and Batch analytics data flow through Linkedin connectors.

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

Convert string to datetime in vb.net

Pass the decode pattern to ParseExact

Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)

ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string

How to convert date format to DD-MM-YYYY in C#

According to one of the first Google search hits: http://www.csharp-examples.net/string-format-datetime/

// Where 'dt' is the DateTime object...
String.Format("{0:dd-MM-yyyy}", dt);

What is the significance of 1/1/1753 in SQL Server?

This is whole story how date problem was and how Big DBMSs handled these problems.

During the period between 1 A.D. and today, the Western world has actually used two main calendars: the Julian calendar of Julius Caesar and the Gregorian calendar of Pope Gregory XIII. The two calendars differ with respect to only one rule: the rule for deciding what a leap year is. In the Julian calendar, all years divisible by four are leap years. In the Gregorian calendar, all years divisible by four are leap years, except that years divisible by 100 (but not divisible by 400) are not leap years. Thus, the years 1700, 1800, and 1900 are leap years in the Julian calendar but not in the Gregorian calendar, while the years 1600 and 2000 are leap years in both calendars.

When Pope Gregory XIII introduced his calendar in 1582, he also directed that the days between October 4, 1582, and October 15, 1582, should be skipped—that is, he said that the day after October 4 should be October 15. Many countries delayed changing over, though. England and her colonies didn't switch from Julian to Gregorian reckoning until 1752, so for them, the skipped dates were between September 4 and September 14, 1752. Other countries switched at other times, but 1582 and 1752 are the relevant dates for the DBMSs that we're discussing.

Thus, two problems arise with date arithmetic when one goes back many years. The first is, should leap years before the switch be calculated according to the Julian or the Gregorian rules? The second problem is, when and how should the skipped days be handled?

This is how the Big DBMSs handle these questions:

  • Pretend there was no switch. This is what the SQL Standard seems to require, although the standard document is unclear: It just says that dates are "constrained by the natural rules for dates using the Gregorian calendar"—whatever "natural rules" are. This is the option that DB2 chose. When there is a pretence that a single calendar's rules have always applied even to times when nobody heard of the calendar, the technical term is that a "proleptic" calendar is in force. So, for example, we could say that DB2 follows a proleptic Gregorian calendar.
  • Avoid the problem entirely. Microsoft and Sybase set their minimum date values at January 1, 1753, safely past the time that America switched calendars. This is defendable, but from time to time complaints surface that these two DBMSs lack a useful functionality that the other DBMSs have and that the SQL Standard requires.
  • Pick 1582. This is what Oracle did. An Oracle user would find that the date-arithmetic expression October 15 1582 minus October 4 1582 yields a value of 1 day (because October 5–14 don't exist) and that the date February 29 1300 is valid (because the Julian leap-year rule applies). Why did Oracle go to extra trouble when the SQL Standard doesn't seem to require it? The answer is that users might require it. Historians and astronomers use this hybrid system instead of a proleptic Gregorian calendar. (This is also the default option that Sun picked when implementing the GregorianCalendar class for Java—despite the name, GregorianCalendar is a hybrid calendar.)

Source 1 and 2

How to style a checkbox using CSS

Here is a simple CSS solution without any jQuery or JavaScript code.

I am using FontAwseome icons but you can use any image

input[type=checkbox] {
  display: inline-block;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  visibility: hidden;
  font-size: 14px;
}

input[type=checkbox]:before {
  content: @fa-var-square-o;
  visibility: visible;
  /*font-size: 12px;*/
}

input[type=checkbox]:checked:before {
  content: @fa-var-check-square-o;
}

PowerShell - Start-Process and Cmdline Switches

Using explicit parameters, it would be:

$msbuild = 'C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe'
start-Process -FilePath $msbuild -ArgumentList '/v:q','/nologo'

EDIT: quotes.

How to get page content using cURL?

Get content with Curl php

request server support Curl function, enable in httpd.conf in folder Apache


function UrlOpener($url)
     global $output;
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $url); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $output = curl_exec($ch); 
     curl_close($ch);    
     echo $output;

If get content by google cache use Curl you can use this url: http://webcache.googleusercontent.com/search?q=cache:Put your url Sample: http://urlopener.mixaz.net/

How to use Redirect in the new react-router-dom of Reactjs

Alternatively, you can use React conditional rendering.

import { Redirect } from "react-router";
import React, { Component } from 'react';

class UserSignup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirect: false
    }
  }
render() {
 <React.Fragment>
   { this.state.redirect && <Redirect to="/signin" /> }   // you will be redirected to signin route
}
</React.Fragment>
}

Reading an Excel file in python using pandas

This is much simple and easy way.

import pandas
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1')
# or using sheet index starting 0
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2)

check out documentation full details http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.read_excel.html

FutureWarning: The sheetname keyword is deprecated for newer Pandas versions, use sheet_name instead.

How to create Select List for Country and States/province in MVC

Designing You Model:

Public class ModelName
{
    ...// Properties
    public IEnumerable<SelectListItem> ListName { get; set; }
}

Prepare and bind List to Model in Controller :

    public ActionResult Index(ModelName model)
    {
        var items = // Your List of data
        model.ListName = items.Select(x=> new SelectListItem() {
                    Text = x.prop,
                    Value = x.prop2
               });
    }

In You View :

@Html.DropDownListFor(m => Model.prop2,Model.ListName)

How do I view the list of functions a Linux shared library is exporting?

What you need is nm and its -D option:

$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
         U atanf
         U calloc
.
.
.

Exported sumbols are indicated by a T. Required symbols that must be loaded from other shared objects have a U. Note that the symbol table does not include just functions, but exported variables as well.

See the nm manual page for more information.

MySQL Error: #1142 - SELECT command denied to user

You need to grant SELECT permissions to the MySQL user who is connecting to MySQL

same question as here Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

see answers of the link ;)

How do I create a MongoDB dump of my database?

Backup/Restore Mongodb with timing.

Backup:

sudo mongodump --db db_name --out /path_of_your_backup/`date +"%m-%d-%y"`

--db argument for databse name

--out argument for path of output

Restore:

sudo mongorestore --db db_name --drop /path_of_your_backup/01-01-19/db_name/

--drop argument for drop databse before restore

Timing:

You can use crontab for timing backup:

sudo crontab -e

It opens with editor(e.g. nano)

3 3 * * * mongodump --out /path_of_your_backup/`date +"%m-%d-%y"`

backup every day at 03:03 AM

Depending on your MongoDB database sizes you may soon run out of disk space with too many backups. That's why it's also recommended to clean the old backups regularly or to compress them. For example, to delete all the backups older than 7 days you can use the following bash command:

3 1 * * * find /path_of_your_backup/ -mtime +7 -exec rm -rf {} \;

delete all the backups older than 7 days

Good Luck.

ref: https://www.digitalocean.com/community/tutorials/how-to-back-up-restore-and-migrate-a-mongodb-database-on-ubuntu-14-04

How can I truncate a string to the first 20 words in PHP?

Change the number 3 to the number 20 below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the 3 to 20 to change the default value):

function first3words($s, $limit=3) {
    return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);   
}

var_dump(first3words("hello yes, world wah ha ha"));  # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha"));   # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha"));   # => "hello yes world"
var_dump(first3words("hello yes world"));  # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes"));  # => "hello yes"
var_dump(first3words("hello"));  # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words(""));  # => ""

Running a single test from unittest.TestCase via the command line

If you organize your test cases, that is, follow the same organization like the actual code and also use relative imports for modules in the same package, you can also use the following command format:

python -m unittest mypkg.tests.test_module.TestClass.test_method

# In your case, this would be:
python -m unittest testMyCase.MyCase.testItIsHot

Python 3 documentation for this: Command-Line Interface

Reset local repository branch to be just like remote repository HEAD

Previous answers assume that the branch to be reset is the current branch (checked out). In comments, OP hap497 clarified that the branch is indeed checked out, but this is not explicitly required by the original question. Since there is at least one "duplicate" question, Reset branch completely to repository state, which does not assume that the branch is checked out, here's an alternative:

If branch "mybranch" is not currently checked out, to reset it to remote branch "myremote/mybranch"'s head, you can use this low-level command:

git update-ref refs/heads/mybranch myremote/mybranch

This method leaves the checked out branch as it is, and the working tree untouched. It simply moves mybranch's head to another commit, whatever is given as the second argument. This is especially helpful if multiple branches need to be updated to new remote heads.

Use caution when doing this, though, and use gitk or a similar tool to double check source and destination. If you accidentally do this on the current branch (and git will not keep you from this), you may become confused, because the new branch content does not match the working tree, which did not change (to fix, update the branch again, to where it was before).

How to compare values which may both be null in T-SQL

NULLIF(TARGET.relation_id, SOURCE.app_relation_id) IS NULL Simple solution

How to check if a file exists from inside a batch file

C:\>help if

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

How can I select an element by name with jQuery?

You can get the element in JQuery by using its ID attribute like this:

$("#tcol1").hide();

What is the correct way to restore a deleted file from SVN?

With Tortoise SVN:

If you haven't committed your changes yet, you can do a revert on the parent folder where you deleted the file or directory.

If you have already committed the deleted file, then you can use the repository browser, change to the revision where the file still existed and then use the command Copy to... from the context menu. Enter the path to your working copy as the target and the deleted file will be copied from the repository to your working copy.

Generating HTML email body in C#

I use dotLiquid for exactly this task.

It takes a template, and fills special identifiers with the content of an anonymous object.

//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source

//Create DTO for the renderer
var bodyDto = new {
    Heading = "Heading Here",
    UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));

It also works with collections, see some online examples.

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

Did have identical problem with on XP machine when installing javacv and opencv in combination with Eclipse. It turned out that I was missing the following files:

  • msvcp100.dll
  • msvcr100.dll

Once these were installed, the project compiled and ran OK.

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

For Mac OS users:

Find the file named config.inc.php, usually located in /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php

(this is the filepath on my Mac)

Then click the right mouse click -> Click on Get Info, at the bottom of the box you will find permissions-> click on the Lock icon (bottom right corner) -> Put your System Admin Password -> -> where it says everyone, modify this permission to READ ONLY -> click back on the Lock icon and try to open http://localhost/phpMyadmin

Hope this helps! ;)

Oracle TNS names not showing when adding new connection to SQL Developer

Open SQL Developer. Go to Tools -> Preferences -> Databases -> Advanced Then explicitly set the Tnsnames Directory

My TNSNAMES was set up correctly and I could connect to Toad, SQL*Plus etc. but I needed to do this to get SQL Developer to work. Perhaps it was a Win 7 issue as it was a pain to install too.

Django ManyToMany filter()

Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct(). Otherwise you get one user multiple times:

users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Compute mean and standard deviation by group for multiple variables in a data.frame

I add the dplyr solution.

set.seed(1)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

library(dplyr)
df %>% group_by(ID) %>% summarise_each(funs(mean, sd))

#      ID Obs_1_mean Obs_2_mean Obs_3_mean  Obs_1_sd  Obs_2_sd  Obs_3_sd
#   (int)      (dbl)      (dbl)      (dbl)     (dbl)     (dbl)     (dbl)
# 1     1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
# 2     2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
# 3     3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

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

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

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

How to create batch file in Windows using "start" with a path and command with spaces

Interestingly, it seems that in Windows Embedded Compact 7, you cannot specify a title string. The first parameter has to be the command or program.

How to get browser width using JavaScript code?

var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;

Both return integers and don't require jQuery. Cross-browser compatible.

I often find jQuery returns invalid values for width() and height()

Getting a list of values from a list of dicts

For a very simple case like this, a comprehension, as in Ismail Badawi's answer is definitely the way to go.

But when things get more complicated, and you need to start writing multi-clause or nested comprehensions with complex expressions in them, it's worth looking into other alternatives. There are a few different (quasi-)standard ways to specify XPath-style searches on nested dict-and-list structures, such as JSONPath, DPath, and KVC. And there are nice libraries on PyPI for them.

Here's an example with the library named dpath, showing how it can simplify something just a bit more complicated:

>>> dd = {
...     'fruits': [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3}],
...     'vehicles': [{'value': 'cars', 'blah':4}]}

>>> {key: [{'value': d['value']} for d in value] for key, value in dd.items()}
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
 'vehicles': [{'value': 'cars'}]}

>>> dpath.util.search(dd, '*/*/value')
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
 'vehicles': [{'value': 'cars'}]}

Or, using jsonpath-ng:

>>> [d['value'] for key, value in dd.items() for d in value]
['apple', 'banana', 'cars']
>>> [m.value for m in jsonpath_ng.parse('*.[*].value').find(dd)]
['apple', 'banana', 'cars']

This one may not look quite as simple at first glance, because find returns match objects, which include all kinds of things besides just the matched value, such as a path directly to each item. But for more complex expressions, being able to specify a path like '*.[*].value' instead of a comprehension clause for each * can make a big difference. Plus, JSONPath is a language-agnostic specification, and there are even online testers that can be very handy for debugging.

How to count the number of letters in a string without the spaces?

Simply solution using the sum function:

sum(c != ' ' for c in word)

It's a memory efficient solution because it uses a generator rather than creating a temporary list and then calculating the sum of it.

It's worth to mention that c != ' ' returns True or False, which is a value of type bool, but bool is a subtype of int, so you can sum up bool values (True corresponds to 1 and False corresponds to 0)

You can check for an inheretance using the mro method:

>>> bool.mro() # Method Resolution Order
[<type 'bool'>, <type 'int'>, <type 'object'>]

Here you see that bool is a subtype of int which is a subtype of object.

Random number c++ in some range

float RandomFloat(float min, float max)
{
    float r = (float)rand() / (float)RAND_MAX;
    return min + r * (max - min);
}

Real world use of JMS/message queues?

I've used it to send intraday trades between different fund management systems. If you want to learn more about what a great technology messaging is, I can thoroughly recommend the book "Enterprise Integration Patterns". There are some JMS examples for things like request/reply and publish/subscribe.

Messaging is an excellent tool for integration.

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

CMake is not able to find BOOST libraries

I got the same error the first time I wanted to install LightGBM on python (GPU version).

You can simply fix it with this command line :

sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev

the boost libraries will be installed and you'll be fine to continue your installation process.

C# declare empty string array

If you must create an empty array you can do this:

string[] arr = new string[0];

If you don't know about the size then You may also use List<string> as well like

var valStrings = new List<string>();

// do stuff...

string[] arrStrings = valStrings.ToArray();

How to add and get Header values in WebApi

For .net Core in GET method, you can do like this:

 StringValues value1;
 string DeviceId = string.Empty;

  if (Request.Headers.TryGetValue("param1", out value1))
      {
                DeviceId = value1.FirstOrDefault();
      }

mysqldump data only

Would suggest using the following snippet. Works fine even with huge tables (otherwise you'd open dump in editor and strip unneeded stuff, right? ;)

mysqldump --no-create-info --skip-triggers --extended-insert --lock-tables --quick DB TABLE > dump.sql

At least mysql 5.x required, but who runs old stuff nowadays.. :)

How can I view a git log of just one user's commits?

Show n number of logs for x user in colour by adding this little snippet in your .bashrc file.

gitlog() {
    if [ "$1" ] && [ "$2" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1" --author="$2"
    elif [ "$1" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1"
    else
        git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order
    fi
}

alias l=gitlog

To show the last 10 commits by Frank:

l 10 frank

To show the last 20 commits by anyone:

l 20

Build .NET Core console application to output an EXE

If a .bat file is acceptable, you can create a bat file with the same name as the DLL file (and place it in the same folder), then paste in the following content:

dotnet %~n0.dll %*

Obviously, this assumes that the machine has .NET Core installed and globally available.

c:\> "path\to\batch\file" -args blah

(This answer is derived from Chet's comment.)

Reset Entity-Framework Migrations

You need to :

  1. Delete the state: Delete the migrations folder in your project; And
  2. Delete the __MigrationHistory table in your database (may be under system tables); Then
  3. Run the following command in the Package Manager Console:

    Enable-Migrations -EnableAutomaticMigrations -Force
    

    Use with or without -EnableAutomaticMigrations

  4. And finally, you can run:

    Add-Migration Initial
    

IntelliJ IDEA "The selected directory is not a valid home for JDK"

I had \bin as part of the path. Up one level of the selected directory worked for me.

Reading string from input with space character?

NOTE: When using fgets(), the last character in the array will be '\n' at times when you use fgets() for small inputs in CLI (command line interpreter) , as you end the string with 'Enter'. So when you print the string the compiler will always go to the next line when printing the string. If you want the input string to have null terminated string like behavior, use this simple hack.

#include<stdio.h>
int main()
{
 int i,size;
 char a[100];
 fgets(a,100,stdin);;
 size = strlen(a);
 a[size-1]='\0';

return 0;
}

Update: Updated with help from other users.

Can't connect to docker from docker-compose

Apart from adding users to docker group, to avoid typing sudo repetitively, you can also create an alias for docker commands like so:

alias docker-compose="sudo docker-compose"
alias docker="sudo docker"

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

This is what worked for me in every datePicker version, firstly converting date into internal datePicker date format, and then converting it back to desired one

var date = "2017-11-07";   
date = $.datepicker.formatDate("dd.mm.yy", $.datepicker.parseDate('yy-mm-dd', date));
// 07.11.2017

How do I find numeric columns in Pandas?

You can use the undocumented function _get_numeric_data() to filter only numeric columns:

df._get_numeric_data()

Example:

In [32]: data
Out[32]:
   A  B
0  1  s
1  2  s
2  3  s
3  4  s

In [33]: data._get_numeric_data()
Out[33]:
   A
0  1
1  2
2  3
3  4

Note that this is a "private method" (i.e., an implementation detail) and is subject to change or total removal in the future. Use with caution.

Find intersection of two nested lists?

I was also looking for a way to do it, and eventually it ended up like this:

def compareLists(a,b):
    removed = [x for x in a if x not in b]
    added = [x for x in b if x not in a]
    overlap = [x for x in a if x in b]
    return [removed,added,overlap]

mysql update column with value from another table

    UPDATE    cities c,
          city_langs cl
    SET       c.fakename = cl.name
   WHERE     c.id = cl.city_id

SQL "select where not in subquery" returns no results

SELECT T.common_id
  FROM Common T
       LEFT JOIN Table1 T1 ON T.common_id = T1.common_id
       LEFT JOIN Table2 T2 ON T.common_id = T2.common_id
 WHERE T1.common_id IS NULL
   AND T2.common_id IS NULL

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Check the 'minSdkVersion' in your build.gradle

The default project creates it with the latest API, so if you're phone is not yet up-dated (e.g. minSdkVersion 21), which is probably your case.

Make sure the minSdkVersion value matches with the device API version or if the device has a higher one.

Example:

defaultConfig {
    applicationId 'xxxxxx'
    minSdkVersion 16
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}

ReactJS - Does render get called any time "setState" is called?

It seems that the accepted answers are no longer the case when using React hooks. You can see in this code sandbox that the class component is rerendered when the state is set to the same value, while in the function component, setting the state to the same value doesn't cause a rerender.

https://codesandbox.io/s/still-wave-wouk2?file=/src/App.js

internal/modules/cjs/loader.js:582 throw err

I was facing same problem.. I downgraded webpack-dev-server to 2.5.1 version. Now everything is working fine .

Combining node.js and Python

I'd consider also Apache Thrift http://thrift.apache.org/

It can bridge between several programming languages, is highly efficient and has support for async or sync calls. See full features here http://thrift.apache.org/docs/features/

The multi language can be useful for future plans, for example if you later want to do part of the computational task in C++ it's very easy to do add it to the mix using Thrift.

How to check if an object is a list or tuple (but not string)?

Python with PHP flavor:

def is_array(var):
    return isinstance(var, (list, tuple))

Is there a method for String conversion to Title Case?

This is the simplest solution

    static void title(String a,String b){
    String ra = Character.toString(Character.toUpperCase(a.charAt(0)));
    String rb = Character.toString(Character.toUpperCase(b.charAt(0)));
    for(int i=1;i<a.length();i++){
        ra+=a.charAt(i);
    }
    for(int i=1;i<b.length();i++){
        rb+=b.charAt(i);
    }
    System.out.println(ra+" "+rb);

Android: disabling highlight on listView click

After a few 'google'ing and testing on virtual and real devices, I notice my below code works:

ArrayAdapter<String> myList = new ArrayAdapter<String>(this, R.layout.list_item, strText) {
    public boolean isEnabled(int position) 
    { 
            return false; 
    } 
};

notice that I've omitted the areAllItemsEnabled() portion.

Remove or adapt border of frame of legend using matplotlib

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()
legend.get_frame().set_facecolor('none')

Warning, you want 'none' (the string). None means the default color instead.

Nodejs cannot find installed module on Windows

I had the same issue, trying to install bower with npm install -g bower

I think this was because node was installed by another user, not me.

I uninstalled node, and then I reinstalled it. During installation, I saw this text for the option Add to PATH > npm modules:

Message in node installation

enter image description here

After node installation, I executed npm install -g bower again. And now bower works.

Sure is not necessary reinstall node with own user, like me. Solution must be via NODE_PATH or PATH variables, as other users have explained.

This is only to remark that this problem occurs only if node has been installed by another user (or if during installation the option Add to PATH > npm modules has not been marked).

Sending JWT token in the headers with Postman

For the request Header name just use Authorization. Place Bearer before the Token. I just tried it out and it works for me.

Authorization: Bearer TOKEN_STRING

Each part of the JWT is a base64url encoded value.

How to Install pip for python 3.7 on Ubuntu 18?

This works for me.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Then this command with sudo:

python3.7 get-pip.py

Based on this instruction.

How to get the number of threads in a Java process

I have written a program to iterate all Threads created and printing getState() of each Thread

import java.util.Set;

public class ThreadStatus {
    public static void main(String args[]) throws Exception{
        for ( int i=0; i< 5; i++){
            Thread t = new Thread(new MyThread());
            t.setName("MyThread:"+i);
            t.start();
        }
        int threadCount = 0;
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        for ( Thread t : threadSet){
            if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){
                System.out.println("Thread :"+t+":"+"state:"+t.getState());
                ++threadCount;
            }
        }
        System.out.println("Thread count started by Main thread:"+threadCount);
    }
}

class MyThread implements Runnable{
    public void run(){
        try{
            Thread.sleep(2000);
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

Output:

java ThreadStatus

Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[main,5,main]:state:RUNNABLE
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:4,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:3,5,main]:state:TIMED_WAITING
Thread count started by Main thread:6

If you remove below condition

if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())

You will get below threads in output too, which have been started by system.

Reference Handler, Signal Dispatcher,Attach Listener and Finalizer.

Navigation Controller Push View Controller

Create the navigation controller first and provide it as rootViewController of your window object.

How do I check if the Java JDK is installed on Mac?

If you are on Mac OS Big Sur, then you probably have a messed up java installation. I found info on how to fix the issue with this article: https://knasmueller.net/how-to-install-java-openjdk-15-on-macos-big-sur

  1. Download the .tar.gz file of the JDK on https://jdk.java.net/15/
  2. Navigate to the download folder, and run these commands (move the .tar.gz file, extract it and remove it after extraction):
sudo mv openjdk-15.0.2_osx-x64_bin.tar.gz /Library/Java/JavaVirtualMachines/
cd /Library/Java/JavaVirtualMachines/
sudo tar -xzf openjdk-15.0.2_osx-x64_bin.tar.gz
sudo rm openjdk-15.0.2_osx-x64_bin.tar.gz

Note: it might be 15.0.3 or higher, depending on the date of your download.

  1. run /usr/libexec/java_home -v15 and copy the output
  2. add this line to your .bash_profile or .zshrc file, depending on which shell you are using. You will probably have only one of these files existing in your home directory (~/.bash_profile or ~/.zshrc).
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home
  1. save the changes and make them effective right away by running: source ~/.bash_profile or source ~/.zshrc
  2. check that java is working - run java -v

About catching ANY exception

I've just found out this little trick for testing if exception names in Python 2.7 . Sometimes i have handled specific exceptions in the code, so i needed a test to see if that name is within a list of handled exceptions.

try:
    raise IndexError #as test error
except Exception as e:
    excepName = type(e).__name__ # returns the name of the exception

How to remove class from all elements jquery

This just removes the highlight class from everything that has the edgetoedge class:

$(".edgetoedge").removeClass("highlight");

I think you want this:

$(".edgetoedge .highlight").removeClass("highlight");

The .edgetoedge .highlight selector will choose everything that is a child of something with the edgetoedge class and has the highlight class.

How do I make a Git commit in the past?

This is an old question but I recently stumbled upon it.

git commit --date='2021-01-01 12:12:00' -m "message" worked properly and verified it on GitHub.

Docker is in volume in use, but there aren't any Docker containers

You should type this command with flag -f (force):

sudo docker volume rm -f <VOLUME NAME>

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

How to produce an csv output file from stored procedure in SQL Server

This script exports rows from specified tables to the CSV format in the output window for any tables structure. Hope, the script will be helpful for you -

DECLARE 
      @TableName SYSNAME
    , @ObjectID INT

DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR 
    SELECT 
          '[' + s.name + '].[' + t.name + ']'
        , t.[object_id]
    FROM (
        SELECT DISTINCT
              t.[schema_id]
            , t.[object_id]
            , t.name
        FROM sys.objects t WITH (NOWAIT)
        JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
        WHERE p.[rows] > 0
            AND t.[type] = 'U'
    ) t
    JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
    WHERE t.name IN ('<your table name>')

OPEN [tables]

FETCH NEXT FROM [tables] INTO 
      @TableName
    , @ObjectID

DECLARE 
      @SQLInsert NVARCHAR(MAX)
    , @SQLColumns NVARCHAR(MAX)
    , @SQLTinyColumns NVARCHAR(MAX)

WHILE @@FETCH_STATUS = 0 BEGIN

    SELECT 
          @SQLInsert = ''
        , @SQLColumns = ''
        , @SQLTinyColumns = ''

    ;WITH cols AS 
    (
        SELECT 
              c.name
            , datetype = t.name
            , c.column_id
        FROM sys.columns c WITH (NOWAIT)
        JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
        WHERE c.[object_id] = @ObjectID
            AND c.is_computed = 0
            AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
    )
    SELECT 
          @SQLTinyColumns = STUFF((
            SELECT ', [' + c.name + ']'
            FROM cols c
            ORDER BY c.column_id
            FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
        , @SQLColumns = STUFF((SELECT CHAR(13) +
            CASE 
                WHEN c.datetype = 'uniqueidentifier' 
                    THEN ' + '';'' + ISNULL('''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''', ''NULL'')' 
                WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary') 
                    THEN ' + '';'' + ISNULL('''' + CAST(REPLACE([' + c.name + '], '''', '''''''') AS NVARCHAR(MAX)) + '''', ''NULL'')' 
                WHEN c.datetype = 'datetime'
                    THEN ' + '';'' + ISNULL('''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''', ''NULL'')' 
                ELSE 
                ' + '';'' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
            END
            FROM cols c
            ORDER BY c.column_id
            FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '''' +')

    DECLARE @SQL NVARCHAR(MAX) = '    
    SET NOCOUNT ON;
    DECLARE 
          @SQL NVARCHAR(MAX) = ''''
        , @x INT = 1
        , @count INT = (SELECT COUNT(1) FROM ' + @TableName + ')

    IF EXISTS(
        SELECT 1
        FROM tempdb.dbo.sysobjects
        WHERE ID = OBJECT_ID(''tempdb..#import'')
    )
        DROP TABLE #import;

    SELECT ' + @SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + @SQLTinyColumns + ')
    INTO #import
    FROM ' + @TableName + ' 

    WHILE @x < @count BEGIN

        SELECT @SQL = STUFF((
        SELECT ' + @SQLColumns + ' + ''''' + '
        FROM #import 
        WHERE RowNumber BETWEEN @x AND @x + 9
        FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''')

        PRINT(@SQL)

        SELECT @x = @x + 10

    END'

    EXEC sys.sp_executesql @SQL

    FETCH NEXT FROM [tables] INTO 
          @TableName
        , @ObjectID

END

CLOSE [tables]
DEALLOCATE [tables]

In the output window you'll get something like this (AdventureWorks.Person.Person):

1;EM;0;NULL;Ken;J;Sánchez;NULL;0;92C4279F-1207-48A3-8448-4636514EB7E2;2003-02-08 00:00:00
2;EM;0;NULL;Terri;Lee;Duffy;NULL;1;D8763459-8AA8-47CC-AFF7-C9079AF79033;2002-02-24 00:00:00
3;EM;0;NULL;Roberto;NULL;Tamburello;NULL;0;E1A2555E-0828-434B-A33B-6F38136A37DE;2001-12-05 00:00:00
4;EM;0;NULL;Rob;NULL;Walters;NULL;0;F2D7CE06-38B3-4357-805B-F4B6B71C01FF;2001-12-29 00:00:00
5;EM;0;Ms.;Gail;A;Erickson;NULL;0;F3A3F6B4-AE3B-430C-A754-9F2231BA6FEF;2002-01-30 00:00:00
6;EM;0;Mr.;Jossef;H;Goldberg;NULL;0;0DEA28FD-EFFE-482A-AFD3-B7E8F199D56F;2002-02-17 00:00:00

Remove file extension from a file name string

There's a method in the framework for this purpose, which will keep the full path except for the extension.

System.IO.Path.ChangeExtension(path, null);

If only file name is needed, use

System.IO.Path.GetFileNameWithoutExtension(path);

Highlight text similar to grep, but don't filter out text

You can make sure that all lines match but there is nothing to highlight on irrelevant matches

egrep --color 'apple|' test.txt 

Notes:

  • egrep may be spelled also grep -E
  • --color is usually default in most distributions
  • some variants of grep will "optimize" the empty match, so you might want to use "apple|$" instead (see: https://stackoverflow.com/a/13979036/939457)

How to post JSON to a server using C#?

I find this to be the friendliest and most concise way to post an read JSON data:

var url = @"http://www.myapi.com/";
var request = new Request { Greeting = "Hello world!" };
var json = JsonSerializer.Serialize<Request>(request);
using (WebClient client = new WebClient())
{
    var jsonResponse = client.UploadString(url, json);
    var response = JsonSerializer.Deserialize<Response>(jsonResponse);
}

I'm using Microsoft's System.Text.Json for serializing and deserializing JSON. See NuGet.

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

How to "properly" create a custom object in JavaScript?

You can also do it this way, using structures :

function createCounter () {
    var count = 0;

    return {
        increaseBy: function(nb) {
            count += nb;
        },
        reset: function {
            count = 0;
        }
    }
}

Then :

var counter1 = createCounter();
counter1.increaseBy(4);

I want to delete all bin and obj folders to force all projects to rebuild everything

To delete bin and obj before build add to project file:

<Target Name="BeforeBuild">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

Here is article: How to remove bin and/or obj folder before the build or deploy

Rounding Bigdecimal values with 2 Decimal Places

I think that the RoundingMode you are looking for is ROUND_HALF_EVEN. From the javadoc:

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.

Here is a quick test case:

BigDecimal a = new BigDecimal("10.12345");
BigDecimal b = new BigDecimal("10.12556");

a = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
b = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);

System.out.println(a);
System.out.println(b);

Correctly prints:

10.12
10.13

UPDATE:

setScale(int, int) has not been recommended since Java 1.5, when enums were first introduced, and was finally deprecated in Java 9. You should now use setScale(int, RoundingMode) e.g:

setScale(2, RoundingMode.HALF_EVEN)

Replace "\\" with "\" in a string in C#

You can simply do a replace in your string like

Str.Replace(@"\\",@"\");

SQL grammar for SELECT MIN(DATE)

To get the titles for dates greater than a week ago today, use this:

SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7

How do I write a backslash (\) in a string?

Just escape the "\" by using + "\\Tasks" or use a verbatim string like @"\Tasks"

Is nested function a good approach when required by only one function?

You can use it to avoid defining global variables. This gives you an alternative for other designs. 3 designs presenting a solution to a problem.

A) Using functions without globals

def calculate_salary(employee, list_with_all_employees):
    x = _calculate_tax(list_with_all_employees)

    # some other calculations done to x
    pass

    y = # something 

    return y

def _calculate_tax(list_with_all_employees):
    return 1.23456 # return something

B) Using functions with globals

_list_with_all_employees = None

def calculate_salary(employee, list_with_all_employees):

    global _list_with_all_employees
    _list_with_all_employees = list_with_all_employees

    x = _calculate_tax()

    # some other calculations done to x
    pass

    y = # something

    return y

def _calculate_tax():
    return 1.23456 # return something based on the _list_with_all_employees var

C) Using functions inside another function

def calculate_salary(employee, list_with_all_employees):

    def _calculate_tax():
        return 1.23456 # return something based on the list_with_a--Lemployees var

    x = _calculate_tax()

    # some other calculations done to x
    pass
    y = # something 

    return y

Solution C) allows to use variables in the scope of the outer function without having the need to declare them in the inner function. Might be useful in some situations.

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

Mutex example / tutorial?

While a mutex may be used to solve other problems, the primary reason they exist is to provide mutual exclusion and thereby solve what is known as a race condition. When two (or more) threads or processes are attempting to access the same variable concurrently, we have potential for a race condition. Consider the following code

//somewhere long ago, we have i declared as int
void my_concurrently_called_function()
{
  i++;
}

The internals of this function look so simple. It's only one statement. However, a typical pseudo-assembly language equivalent might be:

load i from memory into a register
add 1 to i
store i back into memory

Because the equivalent assembly-language instructions are all required to perform the increment operation on i, we say that incrementing i is a non-atmoic operation. An atomic operation is one that can be completed on the hardware with a gurantee of not being interrupted once the instruction execution has begun. Incrementing i consists of a chain of 3 atomic instructions. In a concurrent system where several threads are calling the function, problems arise when a thread reads or writes at the wrong time. Imagine we have two threads running simultaneoulsy and one calls the function immediately after the other. Let's also say that we have i initialized to 0. Also assume that we have plenty of registers and that the two threads are using completely different registers, so there will be no collisions. The actual timing of these events may be:

thread 1 load 0 into register from memory corresponding to i //register is currently 0
thread 1 add 1 to a register //register is now 1, but not memory is 0
thread 2 load 0 into register from memory corresponding to i
thread 2 add 1 to a register //register is now 1, but not memory is 0
thread 1 write register to memory //memory is now 1
thread 2 write register to memory //memory is now 1

What's happened is that we have two threads incrementing i concurrently, our function gets called twice, but the outcome is inconsistent with that fact. It looks like the function was only called once. This is because the atomicity is "broken" at the machine level, meaning threads can interrupt each other or work together at the wrong times.

We need a mechanism to solve this. We need to impose some ordering to the instructions above. One common mechanism is to block all threads except one. Pthread mutex uses this mechanism.

Any thread which has to execute some lines of code which may unsafely modify shared values by other threads at the same time (using the phone to talk to his wife), should first be made acquire a lock on a mutex. In this way, any thread that requires access to the shared data must pass through the mutex lock. Only then will a thread be able to execute the code. This section of code is called a critical section.

Once the thread has executed the critical section, it should release the lock on the mutex so that another thread can acquire a lock on the mutex.

The concept of having a mutex seems a bit odd when considering humans seeking exclusive access to real, physical objects but when programming, we must be intentional. Concurrent threads and processes don't have the social and cultural upbringing that we do, so we must force them to share data nicely.

So technically speaking, how does a mutex work? Doesn't it suffer from the same race conditions that we mentioned earlier? Isn't pthread_mutex_lock() a bit more complex that a simple increment of a variable?

Technically speaking, we need some hardware support to help us out. The hardware designers give us machine instructions that do more than one thing but are guranteed to be atomic. A classic example of such an instruction is the test-and-set (TAS). When trying to acquire a lock on a resource, we might use the TAS might check to see if a value in memory is 0. If it is, that would be our signal that the resource is in use and we do nothing (or more accurately, we wait by some mechanism. A pthreads mutex will put us into a special queue in the operating system and will notify us when the resource becomes available. Dumber systems may require us to do a tight spin loop, testing the condition over and over). If the value in memory is not 0, the TAS sets the location to something other than 0 without using any other instructions. It's like combining two assembly instructions into 1 to give us atomicity. Thus, testing and changing the value (if changing is appropriate) cannot be interrupted once it has begun. We can build mutexes on top of such an instruction.

Note: some sections may appear similar to an earlier answer. I accepted his invite to edit, he preferred the original way it was, so I'm keeping what I had which is infused with a little bit of his verbiage.

ImportError: No Module named simplejson

On Ubuntu/Debian, you can install it with apt-get install python-simplejson

PHP Session timeout

Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.

<?php 
   if(!isset($_SESSION["timeout"])){
     $_SESSION['timeout'] = time();
   };
   $st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>

<?php 
  if(time() < $st){
    echo 'Session will last 1 minute';
  }
?>

Unix tail equivalent command in Windows Powershell

Just some additions to previous answers. There are aliases defined for Get-Content, for example if you are used to UNIX you might like cat, and there are also type and gc. So instead of

Get-Content -Path <Path> -Wait -Tail 10

you can write

# Print whole file and wait for appended lines and print them
cat <Path> -Wait
# Print last 10 lines and wait for appended lines and print them
cat <Path> -Tail 10 -Wait

How to retrieve an element from a set without removing it?

tl;dr

for first_item in muh_set: break remains the optimal approach in Python 3.x. Curse you, Guido.

y u do this

Welcome to yet another set of Python 3.x timings, extrapolated from wr.'s excellent Python 2.x-specific response. Unlike AChampion's equally helpful Python 3.x-specific response, the timings below also time outlier solutions suggested above – including:

Code Snippets for Great Joy

Turn on, tune in, time it:

from timeit import Timer

stats = [
    "for i in range(1000): \n\tfor x in s: \n\t\tbreak",
    "for i in range(1000): next(iter(s))",
    "for i in range(1000): s.add(s.pop())",
    "for i in range(1000): list(s)[0]",
    "for i in range(1000): random.sample(s, 1)",
]

for stat in stats:
    t = Timer(stat, setup="import random\ns=set(range(100))")
    try:
        print("Time for %s:\t %f"%(stat, t.timeit(number=1000)))
    except:
        t.print_exc()

Quickly Obsoleted Timeless Timings

Behold! Ordered by fastest to slowest snippets:

$ ./test_get.py
Time for for i in range(1000): 
    for x in s: 
        break:   0.249871
Time for for i in range(1000): next(iter(s)):    0.526266
Time for for i in range(1000): s.add(s.pop()):   0.658832
Time for for i in range(1000): list(s)[0]:   4.117106
Time for for i in range(1000): random.sample(s, 1):  21.851104

Faceplants for the Whole Family

Unsurprisingly, manual iteration remains at least twice as fast as the next fastest solution. Although the gap has decreased from the Bad Old Python 2.x days (in which manual iteration was at least four times as fast), it disappoints the PEP 20 zealot in me that the most verbose solution is the best. At least converting a set into a list just to extract the first element of the set is as horrible as expected. Thank Guido, may his light continue to guide us.

Surprisingly, the RNG-based solution is absolutely horrible. List conversion is bad, but random really takes the awful-sauce cake. So much for the Random Number God.

I just wish the amorphous They would PEP up a set.get_first() method for us already. If you're reading this, They: "Please. Do something."

Add comma to numbers every three digits

Very Easy way is to use toLocaleString() function

tot = Rs.1402598 //Result : Rs.1402598

tot.toLocaleString() //Result : Rs.1,402,598

Updated : 23/01/2021

The Variable Should be in number format. Example :

Number(tot).toLocaleString() //Result : Rs.1,402,598

How do I address unchecked cast warnings?

Unfortunately, there are no great options here. Remember, the goal of all of this is to preserve type safety. "Java Generics" offers a solution for dealing with non-genericized legacy libraries, and there is one in particular called the "empty loop technique" in section 8.2. Basically, make the unsafe cast, and suppress the warning. Then loop through the map like this:

@SuppressWarnings("unchecked")
Map<String, Number> map = getMap();
for (String s : map.keySet());
for (Number n : map.values());

If an unexpected type is encountered, you will get a runtime ClassCastException, but at least it will happen close to the source of the problem.

Parameter in like clause JPQL

Just leave out the ''

LIKE %:code%

Extracting Nupkg files using command line

Rename it to .zip, then extract it.

Check if null Boolean is true results in exception

Use the Apache BooleanUtils.

(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)

Don't reinvent the wheel. Leverage what's already been built and use isTrue():

BooleanUtils.isTrue( bool );

Checks if a Boolean value is true, handling null by returning false.

If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

How to add a scrollbar to an HTML5 table?

HTML :

    <h1>&darr; SCROLL &darr;</h1>
<table class="blue">
  <thead>
    <tr>
      <th>Colonne 1</th>
      <th>Colonne 2</th>
      <th>Colonne 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
       <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
  </tbody>
</table>

<h1 class="scrollMore">&darr; SCROLL MORE &darr;</h1>
<table class="purple">
  <thead>
    <tr>
      <th>Colonne 1</th>
      <th>Colonne 2</th>
      <th>Colonne 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
       <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
    <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
       <tr>
      <td>Non</td>
      <td>Mais</td>
      <td>Allo !</td>
    </tr>
  </tbody>
</table>
<h1 class="up scrollMore">&uarr; UP &uarr;</h1>

CSS:

body{
  font:1.2em normal Arial,sans-serif;
  color:#34495E;
}

h1{
  text-align:center;
  text-transform:uppercase;
  letter-spacing:-2px;
  font-size:2.5em;
  margin:20px 0;
}

.container{
  width:90%;
  margin:auto;
}

table{
  border-collapse:collapse;
  width:100%;
}

.blue{
  border:2px solid #1ABC9C;
}

.blue thead{
  background:#1ABC9C;
}

.purple{
  border:2px solid #9B59B6;
}

.purple thead{
  background:#9B59B6;
}

thead{
  color:white;
}

th,td{
  text-align:center;
  padding:5px 0;
}

tbody tr:nth-child(even){
  background:#ECF0F1;
}

tbody tr:hover{
background:#BDC3C7;
  color:#FFFFFF;
}

.fixed{
  top:0;
  position:fixed;
  width:auto;
  display:none;
  border:none;
}

.scrollMore{
  margin-top:600px;
}

.up{
  cursor:pointer;
}

JS (jQuery):

;(function($) {
   $.fn.fixMe = function() {
      return this.each(function() {
         var $this = $(this),
            $t_fixed;
         function init() {
            $this.wrap('<div class="container" />');
            $t_fixed = $this.clone();
            $t_fixed.find("tbody").remove().end().addClass("fixed").insertBefore($this);
            resizeFixed();
         }
         function resizeFixed() {
            $t_fixed.find("th").each(function(index) {
               $(this).css("width",$this.find("th").eq(index).outerWidth()+"px");
            });
         }
         function scrollFixed() {
            var offset = $(this).scrollTop(),
            tableOffsetTop = $this.offset().top,
            tableOffsetBottom = tableOffsetTop + $this.height() - $this.find("thead").height();
            if(offset < tableOffsetTop || offset > tableOffsetBottom)
               $t_fixed.hide();
            else if(offset >= tableOffsetTop && offset <= tableOffsetBottom && $t_fixed.is(":hidden"))
               $t_fixed.show();
         }
         $(window).resize(resizeFixed);
         $(window).scroll(scrollFixed);
         init();
      });
   };
})(jQuery);

$(document).ready(function(){
   $("table").fixMe();
   $(".up").click(function() {
      $('html, body').animate({
      scrollTop: 0
   }, 2000);
 });
});

For beginner programmer: If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head> 

Adding jQuery to Your Web Pages click here.

Reference: HERE

How to obtain values of request variables using Python and Flask

If you want to retrieve POST data:

first_name = request.form.get("firstname")

If you want to retrieve GET (query string) data:

first_name = request.args.get("firstname")

Or if you don't care/know whether the value is in the query string or in the post data:

first_name = request.values.get("firstname") 

request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.

Better way to find last used row

This gives you last used row in a specified column.

Optionally you can specify worksheet, else it will takes active sheet.

Function shtRowCount(colm As Integer, Optional ws As Worksheet) As Long

    If ws Is Nothing Then Set ws = ActiveSheet

    If ws.Cells(Rows.Count, colm) <> "" Then
        shtRowCount = ws.Cells(Rows.Count, colm).Row
        Exit Function
    End If

    shtRowCount = ws.Cells(Rows.Count, colm).Row

    If shtRowCount = 1 Then
        If ws.Cells(1, colm) = "" Then
            shtRowCount = 0
        Else
            shtRowCount = 1
        End If
    End If

End Function

Sub test()

    Dim lgLastRow As Long
    lgLastRow = shtRowCount(2) 'Column B

End Sub

Assign command output to variable in batch file

This post has a method to achieve this

from (zvrba) You can do it by redirecting the output to a file first. For example:

echo zz > bla.txt
set /p VV=<bla.txt
echo %VV%

How to HTML encode/escape a string? Is there a built-in?

Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.

CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo &quot;bar&quot; &lt;baz&gt;"

How to get time difference in minutes in PHP

A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:

function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
    $nInterval = strtotime($sDate2) - strtotime($sDate1);
    if ($sUnit=='D') { // days
        $nInterval = $nInterval/60/60/24;
    } else if ($sUnit=='H') { // hours
        $nInterval = $nInterval/60/60;
    } else if ($sUnit=='M') { // minutes
        $nInterval = $nInterval/60;
    } else if ($sUnit=='S') { // seconds
    }
    return $nInterval;
} //DateDiffInterval

How to expand/collapse a diff sections in Vimdiff?

set vimdiff to ignore case

Having started vim diff with

 gvim -d main.sql backup.sql &

I find that annoyingly one file has MySQL keywords in lowercase the other uppercase showing differences on practically every other line

:set diffopt+=icase

this updates the screen dynamically & you can just as easily switch it off again

Can I animate absolute positioned element with CSS transition?

try this:

.test {
    position:absolute;
    background:blue;
    width:200px;
    height:200px;
    top:40px;
    transition:left 1s linear;
    left: 0;
}

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

ImportError: No module named dateutil.parser

If you're using a virtualenv, make sure that you are running pip from within the virtualenv.

$ which pip
/Library/Frameworks/Python.framework/Versions/Current/bin/pip
$ find . -name pip -print
./flask/bin/pip
./flask/lib/python2.7/site-packages/pip
$ ./flask/bin/pip install python-dateutil

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

What does if __name__ == "__main__": do?

The reason for

if __name__ == "__main__":
    main()

is primarily to avoid the import lock problems that would arise from having code directly imported. You want main() to run if your file was directly invoked (that's the __name__ == "__main__" case), but if your code was imported then the importer has to enter your code from the true main module to avoid import lock problems.

A side-effect is that you automatically sign on to a methodology that supports multiple entry points. You can run your program using main() as the entry point, but you don't have to. While setup.py expects main(), other tools use alternate entry points. For example, to run your file as a gunicorn process, you define an app() function instead of a main(). Just as with setup.py, gunicorn imports your code so you don't want it do do anything while it's being imported (because of the import lock issue).

Inserting values into tables Oracle SQL

You can expend the following function in order to pull out more parameters from the DB before the insert:

--
-- insert_employee  (Function) 
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2) 
RETURN VARCHAR2 AS

   p_state_id varchar2(30) := '';
 BEGIN    
      select state_id 
      into   p_state_id
      from states where lower(emp_state) = state_name;

      INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES 
                (p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);

    return 'SUCCESS';

 EXCEPTION 
   WHEN others THEN
    RETURN 'FAIL';
 END;
/

Labels for radio buttons in rails form

Using true/false as the value will have the field pre-filled if the model passed to the form has this attribute already filled:

= f.radio_button(:public?, true)
= f.label(:public?, "yes", value: true)
= f.radio_button(:public?, false)
= f.label(:public?, "no", value: false)

Is there a simple way to increment a datetime object one month in Python?

Question: Is there a simple way to do this in the current release of Python?

Answer: There is no simple (direct) way to do this in the current release of Python.

Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.

Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.

How do you round a float to 2 decimal places in JRuby?

Float#round can take a parameter in Ruby 1.9, not in Ruby 1.8. JRuby defaults to 1.8, but it is capable of running in 1.9 mode.

How to loop through a collection that supports IEnumerable?

foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
{

}

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.

You can use JavaScript/Canvas to do the job but it is still experimental.

Android BroadcastReceiver within Activity

What do I do wrong?

The source code of ToastDisplay is OK (mine is similar and works), but it will only receive something, if it is currently in foreground (you register receiver in onResume). But it can not receive anything if a different activity (in this case SendBroadcast activity) is shown.

Instead you probably want to startActivity ToastDisplay from the first activity?

BroadcastReceiver and Activity make sense in a different use case. In my application I need to receive notifications from a background GPS tracking service and show them in the activity (if the activity is in the foreground).

There is no need to register the receiver in the manifest. It would be even harmful in my use case - my receiver manipulates the UI of the activity and the UI would not be available during onReceive if the activity is not currently shown. Instead I register and unregister the receiver for activity in onResume and onPause as described in BroadcastReceiver documentation:

You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.

How to convert Django Model object to dict with its fields and values?

Update

The newer aggregated answer posted by @zags is more complete and elegant than my own. Please refer to that answer instead.

Original

If you are willing to define your own to_dict method like @karthiker suggested, then that just boils this problem down to a sets problem.

>>># Returns a set of all keys excluding editable = False keys
>>>dict = model_to_dict(instance)
>>>dict

{u'id': 1L, 'reference1': 1L, 'reference2': [1L], 'value': 1}


>>># Returns a set of editable = False keys, misnamed foreign keys, and normal keys
>>>otherDict = SomeModel.objects.filter(id=instance.id).values()[0]
>>>otherDict

{'created': datetime.datetime(2014, 2, 21, 4, 38, 51, tzinfo=<UTC>),
 u'id': 1L,
 'reference1_id': 1L,
 'value': 1L,
 'value2': 2L}

We need to remove the mislabeled foreign keys from otherDict.

To do this, we can use a loop that makes a new dictionary that has every item except those with underscores in them. Or, to save time, we can just add those to the original dict since dictionaries are just sets under the hood.

>>>for item in otherDict.items():
...    if "_" not in item[0]:
...            dict.update({item[0]:item[1]})
...
>>>

Thus we are left with the following dict:

>>>dict
{'created': datetime.datetime(2014, 2, 21, 4, 38, 51, tzinfo=<UTC>),
 u'id': 1L,
 'reference1': 1L,
 'reference2': [1L],
 'value': 1,
 'value2': 2L}

And you just return that.

On the downside, you can't use underscores in your editable=false field names. On the upside, this will work for any set of fields where the user-made fields do not contain underscores.

This is not the best way of doing this, but it could work as a temporary solution until a more direct method is found.

For the example below, dict would be formed based on model_to_dict and otherDict would be formed by filter's values method. I would have done this with the models themselves, but I can't get my machine to accept otherModel.

>>> import datetime
>>> dict = {u'id': 1, 'reference1': 1, 'reference2': [1], 'value': 1}
>>> otherDict = {'created': datetime.datetime(2014, 2, 21, 4, 38, 51), u'id': 1, 'reference1_id': 1, 'value': 1, 'value2': 2}
>>> for item in otherDict.items():
...     if "_" not in item[0]:
...             dict.update({item[0]:item[1]})
...
>>> dict
{'reference1': 1, 'created': datetime.datetime(2014, 2, 21, 4, 38, 51), 'value2': 2, 'value': 1, 'id': 1, 'reference2': [1]}
>>>

That should put you in a rough ballpark of the answer to your question, I hope.

sudo: docker-compose: command not found

If docker-compose is installed for your user but not installed for root user and if you need to run it only once and forget about it afterwords perform the next actions:

  • Find out path to docker-compose:

      which docker-compose
    
  • Run the command specifying full path to docker-compose from the previous command, eg:

      sudo /home/your-user/your-path-to-compose/docker-compose up
    

Adding a simple UIAlertView

Simple alert with array data:

NSString *name = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"Name"];

NSString *msg = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"message"];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:name
                                                message:msg
                                               delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
[alert show];

How to select min and max values of a column in a datatable?

int minAccountLevel = int.MaxValue;
int maxAccountLevel = int.MinValue;
foreach (DataRow dr in table.Rows)
{
    int accountLevel = dr.Field<int>("AccountLevel");
    minAccountLevel = Math.Min(minAccountLevel, accountLevel);
    maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);
}

Yes, this really is the fastest way. Using the Linq Min and Max extensions will always be slower because you have to iterate twice. You could potentially use Linq Aggregate, but the syntax isn't going to be much prettier than this already is.

How can I get Docker Linux container information from within the container itself?

You can communicate with docker from inside of a container using unix socket via Docker Remote API:

https://docs.docker.com/engine/reference/api/docker_remote_api/

In a container, you can find out a shortedned docker id by examining $HOSTNAME env var. According to doc, there is a small chance of collision, I think that for small number of container, you do not have to worry about it. I don't know how to get full id directly.

You can inspect container similar way as outlined in banyan answer:

GET /containers/4abbef615af7/json HTTP/1.1

Response:

HTTP/1.1 200 OK
Content-Type: application/json

{
         "Id": "4abbef615af7......  ",
         "Created": "2013.....",
         ...
}

Alternatively, you can transfer docker id to the container in a file. The file is located on "mounted volume" so it is transfered to container:

docker run -t -i -cidfile /mydir/host1.txt -v /mydir:/mydir ubuntu /bin/bash

The docker id (shortened) will be in file /mydir/host1.txt in the container.

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

What is the difference between Serializable and Externalizable in Java?

There are so many difference exist between Serializable and Externalizable but when we compare difference between custom Serializable(overrided writeObject() & readObject()) and Externalizable then we find that custom implementation is tightly bind with ObjectOutputStream class where as in Externalizable case , we ourself provide an implementation of ObjectOutput which may be ObjectOutputStream class or it could be some other like org.apache.mina.filter.codec.serialization.ObjectSerializationOutputStream

In case of Externalizable interface

@Override
public void writeExternal(ObjectOutput out) throws IOException {
    out.writeUTF(key);
    out.writeUTF(value);
    out.writeObject(emp);
}

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    this.key = in.readUTF();
    this.value = in.readUTF();
    this.emp = (Employee) in.readObject();
}





**In case of Serializable interface**


        /* 
             We can comment below two method and use default serialization process as well
             Sequence of class attributes in read and write methods MUST BE same.
        // below will not work it will not work . 
        // Exception = java.io.StreamCorruptedException: invalid type code: 00\
              private void writeObject(java.io.ObjectOutput stream) 
              */
            private void writeObject(java.io.ObjectOutputStream Outstream)
                    throws IOException {

                System.out.println("from writeObject()");
                /*     We can define custom validation or business rules inside read/write methods.
 This way our validation methods will be automatically 
    called by JVM, immediately after default serialization 
    and deserialization process 
    happens.
                 checkTestInfo();
                */

                stream.writeUTF(name);
                stream.writeInt(age);
                stream.writeObject(salary);
                stream.writeObject(address);
            }

            private void readObject(java.io.ObjectInputStream Instream)
                    throws IOException, ClassNotFoundException {
                System.out.println("from readObject()");
                name = (String) stream.readUTF();
                age = stream.readInt();
                salary = (BigDecimal) stream.readObject();
                address = (Address) stream.readObject();
                // validateTestInfo();
            }

I have added sample code to explain better. please check in/out object case of Externalizable. These are not bound to any implementation directly.
Where as Outstream/Instream are tightly bind to classes. We can extends ObjectOutputStream/ObjectInputStream but it will a bit difficult to use.

SQL Error: ORA-00933: SQL command not properly ended

its very true on oracle as well as sql is "users" is a reserved words just change it , it will serve u the best if u like change it to this

UPDATE system_info set field_value = 'NewValue' 

FROM system_users users JOIN system_info info ON users.role_type = info.field_desc where users.user_name = 'uname'

How can I combine multiple rows into a comma-delimited list in Oracle?

I have always had to write some PL/SQL for this or I just concatenate a ',' to the field and copy into an editor and remove the CR from the list giving me the single line.

That is,

select country_name||', ' country from countries

A little bit long winded both ways.

If you look at Ask Tom you will see loads of possible solutions but they all revert to type declarations and/or PL/SQL

Ask Tom

windows batch file rename

as Itsproinc said, the REN command works!

but if your file path/name has spaces, use quotes " "

example:

ren C:\Users\&username%\Desktop\my file.txt not my file.txt

add " "

ren "C:\Users\&username%\Desktop\my file.txt" "not my file.txt"

hope it helps

Git SSH error: "Connect to host: Bad file number"

Double check that you have published your public keys through your GitHub Administration interface.

Then make sure port 22 isn't somehow blocked (as illustrated in this question)

Apache: client denied by server configuration

Can you try changing "Allow from 127.0.0 192.168.1 ::1 localhost" to "Allow from all". If that fixes your problem, you need to be less restrict about where content can be requested from

Codeigniter LIKE with wildcard(%)

Searching multiple fields at once can be done like so...

function search($search)
{
    $sql = "SELECT * FROM some_table
    WHERE UPPER(a_name) LIKE ?
    OR
    UPPER(a_full_name) LIKE ?
    OR
    UPPER(a_city) LIKE ?
    OR
    UPPER(a_code) LIKE ?
    ";
    $arr = array_map(array($this,"wrapLIKE"),array($search, $search, $search, $search));
    $r = $this->db->query($sql, $arr);
    return $r;
}

function wrapLIKE($string)
{
    return strtoupper("%$string%");
}

Making the main scrollbar always visible

I do this:

html {
    margin-left: calc(100vw - 100%);
    margin-right: 0;
}

Then I don't have to look at the ugly greyed out scrollbar when it's not needed.

How to pass objects to functions in C++?

There are three methods of passing an object to a function as a parameter:

  1. Pass by reference
  2. pass by value
  3. adding constant in parameter

Go through the following example:

class Sample
{
public:
    int *ptr;
    int mVar;

    Sample(int i)
    {
        mVar = 4;
        ptr = new int(i);
    }

    ~Sample()
    {
        delete ptr;
    }

    void PrintVal()
    {
        cout << "The value of the pointer is " << *ptr << endl
             << "The value of the variable is " << mVar;
   }
};

void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}


int main()
{

  Sample s1= 10;
  SomeFunc(s1);
  s1.PrintVal();
  char ch;
  cin >> ch;
}

Output:

Say i am in someFunc
The value of the pointer is -17891602
The value of the variable is 4

How do I disable a href link in JavaScript?

Use all three of the following: Event.preventDefault();, Event.stopPropagation();, and return false;. Each explained...

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. (Source: MDN Webdocs.)

  • Event.stopPropagation(); : To stop the event from clicking a link within the containing parent's DOM (i.e., if two links overlapped visually in the UI).

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. (Source: MDN Webdocs.)

  • return false; : To indicate to the onevent handler that we are cancelling the link-clicking behavior.

The return value from the handler determines if the event is canceled. (Source: MDN Webdocs.)

Full Working JSBin Demo.

StackOverflow Demo...

_x000D_
_x000D_
document.getElementById('my-link').addEventListener('click', function(e) {
  console.log('Click happened for: ' + e.target.id);
  e.preventDefault();
  e.stopPropagation();
  return false;
});
_x000D_
<a href="https://www.wikipedia.com/" id="my-link" target="_blank">Link</a>
_x000D_
_x000D_
_x000D_

How to add header to a dataset in R?

in case you are interested in reading some data from a .txt file and only extract few columns of that file into a new .txt file with a customized header, the following code might be useful:

# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")

# assign the name for the output file:
seqName <- "seq1_data.txt"

#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx        <- civit_cam$q.x.rad.
qy        <- civit_cam$q.y.rad.
qz        <- civit_cam$q.z.rad.
qw        <- civit_cam$q.w

# From GPS:
gpsT      <- civit_gps$X.gpsTime.sec.
latitude  <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude  <- civit_gps$H.Ell.m.
heading   <- civit_gps$Heading.deg.
pitch     <- civit_gps$pitch.deg.
roll      <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]

#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
                     c(frame_idx),
                     c(qx),
                     c(qy),
                     c(qz),
                     c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")

Of course, you should modify this sample script based on your own application.

Group by month and year in MySQL

Use

GROUP BY year, month DESC";

Instead of

GROUP BY MONTH(t.summaryDateTime) DESC";

what do these symbolic strings mean: %02d %01d?

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

the same rules should apply to Java.

in your case it means output of integer values in 2 or more digits, the first being zero if number less than or equal to 9

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

html script src="" triggering redirection with button

your folder name is scripts..

and you are Referencing it like ../script/login.js

Also make sure that script folder is in your project directory

Thanks

Set maxlength in Html Textarea

try this

$(function(){
  $("textarea[maxlength]")
    .keydown(function(event){
       return !$(this).attr("maxlength") || this.value.length < $(this).attr("maxlength") || event.keyCode == 8 || event.keyCode == 46;
    })
    .keyup(function(event){
      var limit = $(this).attr("maxlength");

      if (!limit) return;

      if (this.value.length <= limit) return true;
      else {
        this.value = this.value.substr(0,limit);
        return false;
      }    
    });
});

For me works really perfect without jumping/showing additional characters; works exactly like maxlength on input

Error 1046 No database Selected, how to resolve?

If you're trying to do this via the command line...

If you're trying to run the CREATE TABLE statement from the command line interface, you need to specify the database you're working in before executing the query:

USE your_database;

Here's the documentation.

If you're trying to do this via MySQL Workbench...

...you need to select the appropriate database/catalog in the drop down menu found above the :Object Browser: tab. You can specify the default schema/database/catalog for the connection - click the "Manage Connections" options under the SQL Development heading of the Workbench splash screen.

Addendum

This all assumes there's a database you want to create the table inside of - if not, you need to create the database before anything else:

CREATE DATABASE your_database;

Regular expression to get a string between two strings in Javascript

You can use destructuring to only focus on the part of your interest.

So you can do:

_x000D_
_x000D_
let str = "My cow always gives milk";

let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];

console.log(result);
_x000D_
_x000D_
_x000D_

In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || [] may be interesting if you are not sure there will be a match at all. In that case match would return null which cannot be destructured, and so we return [] instead in that case, and then result will be null.

The additional \b ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+ is needed to avoid that the match includes some outer spacing.

Cannot use a leading ../ to exit above the top directory

I moved my project from "standard" hosting to Azure and get the same error when I try to open page with url-rewrite. I.e. rule is :

<add key="/iPod-eBook-Creator.html" value="/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR" />

try to open my_site/iPod-eBook-Creator.html and get this error (page my_site/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR can be opened without any problem).

I checked the fully site - never used .. to "level up"

How to refresh the data in a jqGrid?

var newdata= //You call Ajax peticion//

$("#idGrid").clearGridData();

$("#idGrid").jqGrid('setGridParam', {data:newdata)});
$("#idGrid").trigger("reloadGrid");

in event update data table

How to use underscore.js as a template engine?

The documentation for templating is partial, I watched the source.

The _.template function has 3 arguments:

  1. String text : the template string
  2. Object data : the evaluation data
  3. Object settings : local settings, the _.templateSettings is the global settings object

If no data (or null) given, than a render function will be returned. It has 1 argument:

  1. Object data : same as the data above

There are 3 regex patterns and 1 static parameter in the settings:

  1. RegExp evaluate : "<%code%>" in template string
  2. RegExp interpolate : "<%=code%>" in template string
  3. RegExp escape : "<%-code%>"
  4. String variable : optional, the name of the data parameter in the template string

The code in an evaluate section will be simply evaluated. You can add string from this section with the __p+="mystring" command to the evaluated template, but this is not recommended (not part of the templating interface), use the interpolate section instead of that. This type of section is for adding blocks like if or for to the template.

The result of the code in the interpolate section will added to the evaluated template. If null given back, then empty string will added.

The escape section escapes html with _.escape on the return value of the given code. So its similar than an _.escape(code) in an interpolate section, but it escapes with \ the whitespace characters like \n before it passes the code to the _.escape. I don't know why is that important, it's in the code, but it works well with the interpolate and _.escape - which doesn't escape the white-space characters - too.

By default the data parameter is passed by a with(data){...} statement, but this kind of evaluating is much slower than the evaluating with named variable. So naming the data with the variable parameter is something good...

For example:

var html = _.template(
    "<pre>The \"<% __p+=_.escape(o.text) %>\" is the same<br />" +
        "as the  \"<%= _.escape(o.text) %>\" and the same<br />" +
        "as the \"<%- o.text %>\"</pre>",
    {
        text: "<b>some text</b> and \n it's a line break"
    },
    {
        variable: "o"
    }
);

$("body").html(html);

results

The "<b>some text</b> and 
 it's a line break" is the same
as the "<b>some text</b> and 
 it's a line break" and the same
as the "<b>some text</b> and 
 it's a line break"

You can find here more examples how to use the template and override the default settings: http://underscorejs.org/#template

By template loading you have many options, but at the end you always have to convert the template into string. You can give it as normal string like the example above, or you can load it from a script tag, and use the .html() function of jquery, or you can load it from a separate file with the tpl plugin of require.js.

Another option to build the dom tree with laconic instead of templating.

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

How to kill a nodejs process in Linux?

sudo netstat -lpn |grep :'3000'

3000 is port i was looking for, After first command you will have Process ID for that port

kill -9 1192

in my case 1192 was process Id of process running on 3000 PORT use -9 for Force kill the process

PHP function to make slug (URL string)

The most elegant way I think is using a Behat\Transliterator\Transliterator.

I need to extends this class by your class because it is an Abstract, some like this:

<?php
use Behat\Transliterator\Transliterator;

class Urlizer extends Transliterator
{
}

And then, just use it:

$text = "Master Ápiu";
$urlizer = new Urlizer();
$slug = $urlizer->transliterate($slug, "-");
echo $slug; // master-apiu

Of course you should put this things in your composer as well.

composer require behat/transliterator

More info here https://github.com/Behat/Transliterator

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

How to compile C programming in Windows 7?

MinGW uses a fairly old version of GCC (3.4.5, I believe), and hasn't been updated in a while. If you're already comfortable with the GCC toolset and just looking to get your feet wet in Windows programming, this may be a good option for you. There are lots of great IDEs available that use this compiler.

Edit: Apparently I was wrong; that's what I get for talking about something I know very little about. Tauran points out that there is a project that aims to provide the MinGW toolkit with the current version of GCC. You can download it from their website.


However, I'm not sure that I can recommend it for serious Windows development. If you're not a idealistic fanboy who can't stomach the notion of ever using Microsoft software, I highly recommend investigating Visual Studio, which comes bundled with Microsoft's C/C++ compiler. The Express version (which includes the same compiler as all the paid-for editions) is absolutely free for download. In addition to the compiler, Visual Studio also provides a world-class IDE that makes developing Windows-specific applications much easier. Yes, detractors will ramble on about the fact that it's not fully standards-compliant, but such is the world of writing Windows applications. They're never going to be truly portable once you include windows.h, so most of the idealistic dedication just ends up being a waste of time.

How to correctly use the extern keyword in C

It has already been stated that the extern keyword is redundant for functions.

As for variables shared across compilation units, you should declare them in a header file with the extern keyword, then define them in a single source file, without the extern keyword. The single source file should be the one sharing the header file's name, for best practice.

How to leave/exit/deactivate a Python virtualenv

I found that when within a Miniconda3 environment I had to run:

conda deactivate

Neither deactivate nor source deactivate worked for me.

Reading PDF content with itextsharp dll in VB.NET or C#

Public Sub PDFTxtToPdf(ByVal sTxtfile As String, ByVal sPDFSourcefile As String)
        Dim sr As StreamReader = New StreamReader(sTxtfile)
    Dim doc As New Document()
    PdfWriter.GetInstance(doc, New FileStream(sPDFSourcefile, FileMode.Create))
    doc.Open()
    doc.Add(New Paragraph(sr.ReadToEnd()))
    doc.Close()
End Sub

How to get a substring between two strings in PHP?

I have to add something to the post of Julius Tilvikas. I looked for a solution like this one he described in his post. But i think there is a mistake. I don't get realy the string between two string, i also get more with this solution, because i have to substract the lenght of the start-string. When do this, i realy get the String between two strings.

Here are my changes of his solution:

function get_string_between ($string, $start, $end, $inclusive = false){
    $string = " ".$string;

    if ($start == "") { $ini = 0; }
    else { $ini = strpos($string, $start); }

    if ($end == "") { $len = strlen($string); }
    else { $len = strpos($string, $end, $ini) - $ini - strlen($start);}

    if (!$inclusive) { $ini += strlen($start); }
    else { $len += strlen($end); }

    return substr($string, $ini, $len);
}

Greetz

V

How to use sessions in an ASP.NET MVC 4 application?

Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serialising them and storing them in a session.

A perfect use case of this could be if you need to access regular information across your application, to save additional database calls on each request, this data can be stored in an object and unserialised on each request, like so:

Our reusable, serializable object:

[Serializable]
public class UserProfileSessionData
{
    public int UserId { get; set; }

    public string EmailAddress { get; set; }

    public string FullName { get; set; }
}

Use case:

public class LoginController : Controller {

    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var profileData = new UserProfileSessionData {
                UserId = model.UserId,
                EmailAddress = model.EmailAddress,
                FullName = model.FullName
            }

            this.Session["UserProfile"] = profileData;
        }
    }

    public ActionResult LoggedInStatusMessage()
    {
        var profileData = this.Session["UserProfile"] as UserProfileSessionData;

        /* From here you could output profileData.FullName to a view and
        save yourself unnecessary database calls */
    }

}

Once this object has been serialised, we can use it across all controllers without needing to create it or query the database for the data contained within it again.

Inject your session object using Dependency Injection

In a ideal world you would 'program to an interface, not implementation' and inject your serializable session object into your controller using your Inversion of Control container of choice, like so (this example uses StructureMap as it's the one I'm most familiar with).

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.For<IUserProfileSessionData>().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());   
    }

    public static IUserProfileSessionData GetUserProfileFromSession()
    {
        var session = HttpContext.Current.Session;
        if (session["UserProfile"] != null)
        {
            return session["UserProfile"] as IUserProfileSessionData;
        }

        /* Create new empty session object */
        session["UserProfile"] = new UserProfileSessionData();

        return session["UserProfile"] as IUserProfileSessionData;
    }
}

You would then register this in your Global.asax.cs file.

For those that aren't familiar with injecting session objects, you can find a more in-depth blog post about the subject here.

A word of warning:

It's worth noting that sessions should be kept to a minimum, large sessions can start to cause performance issues.

It's also recommended to not store any sensitive data in them (passwords, etc).

How do I configure Notepad++ to use spaces instead of tabs?

Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.

Enter image description here

See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings

How can I extract substrings from a string in Perl?

You could use a regular expression such as the following:

/([-a-z0-9]+)\s*\((.*?)\)\s*(\*)?/

So for example:

$s = "abc-456-hu5t10 (High priority) *";
$s =~ /([-a-z0-9]+)\s*\((.*?)\)\s*(\*)?/;
print "$1\n$2\n$3\n";

prints

abc-456-hu5t10
High priority
*

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

How can we draw a vertical line in the webpage?

There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0; and bottom:0; style.

Try this:

CSS

.vr {
    width:10px;
    background-color:#000;
    position:absolute;
    top:0;
    bottom:0;
    left:150px;
}

HTML

<div class="vr">&nbsp;</div>

Demo

jQuery scroll to ID from different page

I made a reusable plugin that can do this... I left the binding to events outside the plugin itself because I feel it is too intrusive for such a little helper....

jQuery(function ($) {

    /**
     * This small plugin will scrollTo a target, smoothly
     *
     * First argument = time to scroll to the target
     * Second argument = set the hash in the current url yes or no
     */
    $.fn.smoothScroll = function(t, setHash) {
        // Set time to t variable to if undefined 500 for 500ms transition
        t = t || 500;
        setHash = (typeof setHash == 'undefined') ? true : setHash;

        // Return this as a proper jQuery plugin should
        return this.each(function() {
            $('html, body').animate({
                scrollTop: $(this).offset().top
            }, t);

            // Lets set the hash to the current ID since if an event was prevented this doesn't get done
            if (this.id && setHash) {
                window.location.hash = this.id;
            }
        });
    };

});

Now next, we can onload just do this, check for a hash and if its there try to use it directly as a selector for jQuery. Now I couldn't easily test this at the time but I made similar stuff for production sites not long ago, if this doesn't immediatly work let me know and I'll look into the solution I got there.

(script should be within an onload section)

if (window.location.hash) {
    window.scrollTo(0,0);
    $(window.location.hash).smoothScroll();
}

Next we bind the plugin to onclick of anchors which only contain a hash in their href attribute.

(script should be within an onload section)

$('a[href^="#"]').click(function(e) {
    e.preventDefault();

    $($(this).attr('href')).smoothScroll();
});

Since jQuery doesn't do anything if the match itself fails we have a nice fallback for when a target on a page can't be found yay \o/

Update

Alternative onclick handler to scroll to the top when theres only a hash:

$('a[href^="#"]').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');

    // In this case we have only a hash, so maybe we want to scroll to the top of the page?
    if(href.length === 1) { href = 'body' }

    $(href).smoothScroll();
});

Here is also a simple jsfiddle that demonstrates the scrolling within page, onload is a little hard to set up...

http://jsfiddle.net/sg3s/bZnWN/

Update 2

So you might get in trouble with the window already scrolling to the element onload. This fixes that: window.scrollTo(0,0); it just scrolls the page to the left top. Added it to the code snippet above.

Add a CSS class to <%= f.submit %>

both of them works <%= f.submit class: "btn btn-primary" %> and <%= f.submit "Name of Button", class: "btn btn-primary "%>

How to convert string to integer in C#

int i;
string whatever;

//Best since no exception raised
int.TryParse(whatever, out i);

//Better use try catch on this one
i = Convert.ToInt32(whatever);

Is there a way to make mv create the directory to be moved to if it doesn't exist?

I frequently stumble upon this issue while bulk moving files to new subdirectories. Ideally, I want to do this:

mv * newdir/  

Most of the answers in this thread propose to mkdir and then mv, but this results in:

mkdir newdir && mv * newdir 
mv: cannot move 'newdir/' to a subdirectory of itself

The problem I face is slightly different in that I want to blanket move everything, and, if I create the new directory before moving then it also tries to move the new directory to itself. So, I work around this by using the parent directory:

mkdir ../newdir && mv * ../newdir && mv ../newdir .

Caveats: Does not work in the root folder (/).

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

How to reset Django admin password?

Another thing that is worth noting is to set your user's status is_staff as active. At least, that's what makes it works for me. For more detail, I created another superuser as people explained above. Then I go to the database table auth_user and search for that username to make sure its is_staff flag is set to 1. That finally allowed me to log into admin site.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

For me the solution was besides using "Ntlm" as credential type, similar as Jeroen K's solution. If I had the permission level I would plus on his post, but let me post my whole code here, which will support both Windows and other credential types like basic auth:

    XxxSoapClient xxxClient = new XxxSoapClient();
    ApplyCredentials(userName, password, xxxClient.ClientCredentials);

    private static void ApplyCredentials(string userName, string password, ClientCredentials clientCredentials)
    {
        clientCredentials.UserName.UserName = userName;
        clientCredentials.UserName.Password = password;
        clientCredentials.Windows.ClientCredential.UserName = userName;
        clientCredentials.Windows.ClientCredential.Password = password;
        clientCredentials.Windows.AllowNtlm = true;
        clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    }  

What's the best visual merge tool for Git?

You can change the tool used by git mergetool by passing git mergetool -t=<tool> or --tool=<tool>. To change the default (from vimdiff) use git config merge.tool <tool>.

Subtracting time.Duration from time in Go

There's time.ParseDuration which will happily accept negative durations, as per manual. Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.

E.g. when you need to substract an hour and a half, you can do that like so:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    duration, _ := time.ParseDuration("-1.5h")

    then := now.Add(duration)

    fmt.Println("then:", then)
}

https://play.golang.org/p/63p-T9uFcZo

Target WSGI script cannot be loaded as Python module

If you install your project’s Python dependencies inside a virtualenv, you’ll need to add the path to this virtualenv’s directory to your Python path as well. To do this, add an additional path to your WSGIPythonPath directive, with multiple paths separated by a colon (:) if using a UNIX-like system, or a semicolon (;) if using Windows

List Directories and get the name of the Directory

This will print all the subdirectories of the current directory:

print [name for name in os.listdir(".") if os.path.isdir(name)]

I'm not sure what you're doing with split("-"), but perhaps this code will help you find a solution?

If you want the full pathnames of the directories, use abspath:

print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]

Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk as others have suggested.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

I successfully put a portable version of libreoffice on my host's webserver, which I call with PHP to do a commandline conversion from .docx, etc. to pdf. on the fly. I do not have admin rights on my host's webserver. Here is my blog post of what I did:

http://geekswithblogs.net/robertphyatt/archive/2011/11/19/converting-.docx-to-pdf-or-.doc-to-pdf-or-.doc.aspx

Yay! Convert directly from .docx or .odt to .pdf using PHP with LibreOffice (OpenOffice's successor)!

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

It's looking for the file in the current directory.

First, go to that directory

cd /users/gcameron/Desktop/map

And then try to run it

python colorize_svg.py

Django: TemplateSyntaxError: Could not parse the remainder

This error usually means you've forgotten a closing quote somewhere in the template you're trying to render. For example: {% url 'my_view %} (wrong) instead of {% url 'my_view' %} (correct). In this case it's the colon that's causing the problem. Normally you'd edit the template to use the correct {% url %} syntax.

But there's no reason why the django admin site would throw this, since it would know it's own syntax. My best guess is therefore that grapelli is causing your problem since it changes the admin templates. Does removing grappelli from installed apps help?

How to Deep clone in javascript

We can utilize recursion for making deepCopy. It can create copy of array, object, array of object, object with function. if you want, you can add function for other type of data structure like map etc.

function deepClone(obj) {
         var retObj;
        _assignProps = function(obj, keyIndex, retObj) {
               var subType = Object.prototype.toString.call(obj[keyIndex]);
               if(subType === "[object Object]" || subType === "[object Array]") {
                    retObj[keyIndex] = deepClone(obj[keyIndex]);
               }
               else {
                     retObj[keyIndex] = obj[keyIndex];
               }
        };

        if(Object.prototype.toString.call(obj) === "[object Object]") {
           retObj = {};
           for(key in obj) {
               this._assignProps(obj, key, retObj);
           }
        }
        else if(Object.prototype.toString.call(obj) == "[object Array]") {
           retObj = [];
           for(var i = 0; i< obj.length; i++) {
              this._assignProps(obj, i, retObj);
            }
        };

        return retObj;
    };

numbers not allowed (0-9) - Regex Expression in javascript

\D is a non-digit, and so then \D* is any number of non-digits in a row. So your whole string should match ^\D*$.

Check on http://rubular.com/r/AoWBmrbUkN it works perfectly.

You can also try on http://regexpal.com/ OR http://www.regextester.com/

How to disable all div content

Or just use css and a "disabled" class.
Note: don't use the disabled attribute.
No need to mess with jQuery on/off.
This is much easier and works cross browser:

.disabled{
    position: relative;
}
.disabled:after{
    content: "";
    position: absolute;
    width: 100%;
    height: inherit;
    background-color: rgba(0,0,0,0.1);
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

Then you can shut it on and off when initializing your page, or toggling a button

if(myDiv !== "can be edited"){
    $('div').removeClass('disabled');
} else{
    $('div').addClass('disabled');
}

How can I change the image of an ImageView?

Have a look at the ImageView API. There are several setImage* methods. Which one to use depends on the image you provide. If you have the image as resource (e.g. file res/drawable/my_image.png)

ImageView img = new ImageView(this);  // or (ImageView) findViewById(R.id.myImageView);
img.setImageResource(R.drawable.my_image);

In bash, how to store a return value in a variable?

It is easy you need to echo the value you need to return and then capture it like below

demofunc(){
    local variable="hellow"
    echo $variable    
}

val=$(demofunc)
echo $val

How to check if anonymous object has a method?

You want hasOwnProperty():

_x000D_
_x000D_
var myObj1 = { _x000D_
 prop1: 'no',_x000D_
 prop2: function () { return false; }_x000D_
}_x000D_
var myObj2 = { _x000D_
 prop1: 'no'_x000D_
}_x000D_
_x000D_
console.log(myObj1.hasOwnProperty('prop2')); // returns true_x000D_
console.log(myObj2.hasOwnProperty('prop2')); // returns false_x000D_
 
_x000D_
_x000D_
_x000D_

References: Mozilla, Microsoft, phrogz.net.

Decimal or numeric values in regular expression validation

I've tested all given regexes but unfortunately none of them pass those tests:

    String []goodNums={"3","-3","0","0.0","1.0","0.1"};
    String []badNums={"001","-00.2",".3","3.","a",""," ","-"," -1","--1","-.1","-0", "2..3", "2-", "2...3", "2.4.3", "5-6-7"};

Here is the best I wrote that pass all those tests:

"^(-?0[.]\\d+)$|^(-?[1-9]+\\d*([.]\\d+)?)$|^0$"

enter image description here

Skip over a value in the range function in python

for i in range(100):
    if i == 50:
        continue
    dosomething

How to return multiple objects from a Java method?

You may use any of following ways:

private static final int RETURN_COUNT = 2;
private static final int VALUE_A = 0;
private static final int VALUE_B = 1;
private static final String A = "a";
private static final String B = "b";

1) Using Array

private static String[] methodWithArrayResult() {
    //...
    return new String[]{"valueA", "valueB"};
}

private static void usingArrayResultTest() {
    String[] result = methodWithArrayResult();
    System.out.println();
    System.out.println("A = " + result[VALUE_A]);
    System.out.println("B = " + result[VALUE_B]);
}

2) Using ArrayList

private static List<String> methodWithListResult() {
    //...
    return Arrays.asList("valueA", "valueB");
}

private static void usingListResultTest() {
    List<String> result = methodWithListResult();
    System.out.println();
    System.out.println("A = " + result.get(VALUE_A));
    System.out.println("B = " + result.get(VALUE_B));
}

3) Using HashMap

private static Map<String, String> methodWithMapResult() {
    Map<String, String> result = new HashMap<>(RETURN_COUNT);
    result.put(A, "valueA");
    result.put(B, "valueB");
    //...
    return result;
}

private static void usingMapResultTest() {
    Map<String, String> result = methodWithMapResult();
    System.out.println();
    System.out.println("A = " + result.get(A));
    System.out.println("B = " + result.get(B));
}

4) Using your custom container class

private static class MyContainer<M,N> {
    private final M first;
    private final N second;

    public MyContainer(M first, N second) {
        this.first = first;
        this.second = second;
    }

    public M getFirst() {
        return first;
    }

    public N getSecond() {
        return second;
    }

    // + hashcode, equals, toString if need
}

private static MyContainer<String, String> methodWithContainerResult() {
    //...
    return new MyContainer("valueA", "valueB");
}

private static void usingContainerResultTest() {
    MyContainer<String, String> result = methodWithContainerResult();
    System.out.println();
    System.out.println("A = " + result.getFirst());
    System.out.println("B = " + result.getSecond());
}

5) Using AbstractMap.simpleEntry

private static AbstractMap.SimpleEntry<String, String> methodWithAbstractMapSimpleEntryResult() {
    //...
    return new AbstractMap.SimpleEntry<>("valueA", "valueB");
}

private static void usingAbstractMapSimpleResultTest() {
    AbstractMap.SimpleEntry<String, String> result = methodWithAbstractMapSimpleEntryResult();
    System.out.println();
    System.out.println("A = " + result.getKey());
    System.out.println("B = " + result.getValue());
}

6) Using Pair of Apache Commons

private static Pair<String, String> methodWithPairResult() {
    //...
    return new ImmutablePair<>("valueA", "valueB");
}

private static void usingPairResultTest() {
    Pair<String, String> result = methodWithPairResult();
    System.out.println();
    System.out.println("A = " + result.getKey());
    System.out.println("B = " + result.getValue());
}

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

The service cannot accept control messages at this time

I forgot I had mine attached to Visual Studio debugger. Be sure to disconnect from there, and then wait a moment. Otherwise killing the process viewing the PID from the Worker Processes functionality of IIS manager will work too.

How to get $(this) selected option in jQuery?

var cur_value = $(this).find('option:selected').text();

Since option is likely to be immediate child of select you can also use:

var cur_value = $(this).children('option:selected').text();

http://api.jquery.com/find/

how can I login anonymously with ftp (/usr/bin/ftp)?

As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:

If the server uses Pure-FTP as the FTP server:

421 Can't change directory to /var/ftp/ error message.

If the server uses ProFTP as the FTP server:

530 Login Authentication Failed error message.

When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where example.com is the domain used in your e-mail address:

User name: [email protected]

In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.

For reference, this answer is based on content found on a documentation.cpanel.net Anonymous FTP page. At the time of this writing, it stated:

When users log in to FTP anonymously, they must format usernames as [email protected], where example.com represents the user's domain name. This requirement directs your server to the correct public_ftp directory.

How do I select an entire row which has the largest ID in the table?

One can always go for analytical functions as well which will give you more control

select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1

If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.

How to include jQuery in ASP.Net project?

There are actually a few ways this can be done:

1: Download

You can download the latest version of jQuery and then include it in your page with a standard HTML script tag. This can be done within the master or an individual page.

HTML5

<script src="/scripts/jquery-2.1.0.min.js"></script>

HTML4

<script src="/scripts/jquery-2.1.0.min.js" type="text/javascript"></script>

2: Content Delivery Network

You can include jQuery to your site using a CDN (Content Delivery Network) such as Google's. This should help reduce page load times if the user has already visited a site using the same version from the same CDN.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

3: NuGet Package Manager

Lastly, (my preferred) use NuGet which is shipped with Visual Studio and Visual Studio Express. This is accessed from right-clicking on your project and clicking Manage NuGet Packages.

NuGet is an open source Library Package Manager that comes as a Visual Studio extension and that makes it very easy to add, remove, and update external libraries in your Visual Studio projects and websites. Beginning ASP.NET 4.5 in C# and VB.NET, WROX, 2013

enter image description here

Once installed, a new Folder group will appear in your Solution Explorer called Scripts. Simply drag and drop the file you wish to include onto your page of choice.

This method is ideal for larger projects because if you choose to remove the files, or change versions later (though the package manager) if will automatically remove/update any reference to that file within your project.

The only downside to this approach is it does not use a CDN to host the file so page load time may be slightly slower the first time the user visits your site.

Python 3: ImportError "No Module named Setuptools"

Windows 7:

I have given a complete solution here for python selenium webdriver

1. Setup easy install (windows - simplified)
    a. download ez.setup.py (https://bootstrap.pypa.io/ez_setup.py) from 'https://pypi.python.org/pypi/setuptools'
    b. move ez.setup.py to C:\Python27\
    c. open cmd prompt
    d. cd C:\Python27\
    e. C:\Python27\python.exe ez.setup.py install

Rails: update_attribute vs update_attributes

update_attribute

This method update single attribute of object without invoking model based validation.

obj = Model.find_by_id(params[:id])
obj.update_attribute :language, “java”

update_attributes

This method update multiple attribute of single object and also pass model based validation.

attributes = {:name => “BalaChandar”, :age => 23}
obj = Model.find_by_id(params[:id])
obj.update_attributes(attributes)

Hope this answer will clear out when to use what method of active record.

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Try this:

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

This work for me on Centos 6

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

mongodb 2.6.8 on windows7 32bits you only need create a folder c:/data/db execute mongod, and execute mongo

Mocking methods of local scope objects with Mockito

If you really want to avoid touching this code, you can use Powermockito (PowerMock for Mockito).

With this, amongst many other things, you can mock the construction of new objects in a very easy way.

How to convert an NSTimeInterval (seconds) into minutes

    NSDate *timeLater = [NSDate dateWithTimeIntervalSinceNow:60*90];

    NSTimeInterval duration = [timeLater  timeIntervalSinceNow];

    NSInteger hours = floor(duration/(60*60));
    NSInteger minutes = floor((duration/60) - hours * 60);
    NSInteger seconds = floor(duration - (minutes * 60) - (hours * 60 * 60));

    NSLog(@"timeLater: %@", [dateFormatter stringFromDate:timeLater]);

    NSLog(@"time left: %d hours %d minutes  %d seconds", hours,minutes,seconds);

Outputs:

timeLater: 22:27
timeLeft: 1 hours 29 minutes  59 seconds

How to add Python to Windows registry

When installing Python 3.4 the "Add python.exe to Path" came up unselected. Re-installed with this selected and problem resolved.