Programs & Examples On #Incremental linking

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

jQuery If DIV Doesn't Have Class "x"

I think the author was looking for:

$(this).not('.selected')

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

_x000D_
_x000D_
button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_

Fiddle here.

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

Within the package there is a class called JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.SecurityTokenHandler. In WIF this is the core class for deserialising and serialising security tokens.

The class has a ReadToken(String) method that will take your base64 encoded JWT string and returns a SecurityToken which represents the JWT.

The SecurityTokenHandler also has a ValidateToken(SecurityToken) method which takes your SecurityToken and creates a ReadOnlyCollection<ClaimsIdentity>. Usually for JWT, this will contain a single ClaimsIdentity object that has a set of claims representing the properties of the original JWT.

JwtSecurityTokenHandler defines some additional overloads for ValidateToken, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters) overload. The TokenValidationParameters argument allows you to specify the token signing certificate (as a list of X509SecurityTokens). It also has an overload that takes the JWT as a string rather than a SecurityToken.

The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at

http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc

Alternatively, the JwtSecurityToken class has additional methods that are not on the base SecurityToken class, such as a Claims property that gets the contained claims without going via the ClaimsIdentity collection. It also has a Payload property that returns a JwtPayload object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.

The general (i.e. non JWT specific) documentation for the SecurityTokenHandler class is at

http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx

Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.

There are 3 samples of it in use in different types of application at

http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=aal&f%5B1%5D.Type=User&f%5B1%5D.Value=Azure%20AD%20Developer%20Experience%20Team&f%5B1%5D.Text=Azure%20AD%20Developer%20Experience%20Team

Probably, one will suite your needs or at least be adaptable to them.

std::string length() and size() member functions

Ruby's just the same, btw, offering both #length and #size as synonyms for the number of items in arrays and hashes (C++ only does it for strings).

Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

How do I check which version of NumPy I'm using?

From the command line, you can simply issue:

python -c "import numpy; print(numpy.version.version)"

Or:

python -c "import numpy; print(numpy.__version__)"

Angularjs - simple form submit

I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().

If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

How to use session in JSP pages to get information?

Use

<% String username = (String)request.getSession().getAttribute(...); %>

Note that your use of <%! ... %> is translated to class-level, but request is only available in the service() method of the translated servlet.

See how JSP code is translated to a servlet.

Maven: Non-resolvable parent POM

I had similar problem at my work.

Building the parent project without dependency created parent_project.pom file in the .m2 folder.

Then add the child module in the parent POM and run Maven build.

<modules>
    <module>module1</module>
    <module>module2</module>
    <module>module3</module>
    <module>module4</module>
</modules>

C# refresh DataGridView when updating or inserted on another form

for refresh data gridview in any where you just need this code:

datagridview1.DataSource = "your DataSource";
datagridview1.Refresh();

Running Google Maps v2 on the Android emulator

I have already replied to this question in an answer to Stack Overflow question Trouble using Google sign-in button in emulator. It only works for Android 4.2.2, but lets you use the "Intel Atom (x86)" in AVD.

I think that it is easy to make it work for other versions of Android. Just find the correct files.

How to center a checkbox in a table cell?

For dynamic writing td elements and not rely directly on the td Style

  <td>
     <div style="text-align: center;">
         <input  type="checkbox">
     </div>
  </td>

How to import multiple .csv files at once?

Here are some options to convert the .csv files into one data.frame using R base and some of the available packages for reading files in R.

This is slower than the options below.

# Get the files names
files = list.files(pattern="*.csv")
# First apply read.csv, then rbind
myfiles = do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))

Edit: - A few more extra choices using data.table and readr

A fread() version, which is a function of the data.table package. This is by far the fastest option in R.

library(data.table)
DT = do.call(rbind, lapply(files, fread))
# The same using `rbindlist`
DT = rbindlist(lapply(files, fread))

Using readr, which is another package for reading csv files. It's slower than fread, faster than base R but has different functionalities.

library(readr)
library(dplyr)
tbl = lapply(files, read_csv) %>% bind_rows()

What is more efficient? Using pow to square or just multiply it with itself?

I was also wondering about the performance issue, and was hoping this would be optimised out by the compiler, based on the answer from @EmileCormier. However, I was worried that the test code he showed would still allow the compiler to optimise away the std::pow() call, since the same values were used in the call every time, which would allow the compiler to store the results and re-use it in the loop - this would explain the almost identical run-times for all cases. So I had a look into it too.

Here's the code I used (test_pow.cpp):

#include <iostream>                                                                                                                                                                                                                       
#include <cmath>
#include <chrono>

class Timer {
  public:
    explicit Timer () : from (std::chrono::high_resolution_clock::now()) { }

    void start () {
      from = std::chrono::high_resolution_clock::now();
    }

    double elapsed() const {
      return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - from).count() * 1.0e-6;
    }

  private:
    std::chrono::high_resolution_clock::time_point from;
};

int main (int argc, char* argv[])
{
  double total;
  Timer timer;



  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,2);
  std::cout << "std::pow(i,2): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i;
  std::cout << "i*i: " << timer.elapsed() << "s (result = " << total << ")\n";

  std::cout << "\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,3);
  std::cout << "std::pow(i,3): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i*i;
  std::cout << "i*i*i: " << timer.elapsed() << "s (result = " << total << ")\n";


  return 0;
}

This was compiled using:

g++ -std=c++11 [-O2] test_pow.cpp -o test_pow

Basically, the difference is the argument to std::pow() is the loop counter. As I feared, the difference in performance is pronounced. Without the -O2 flag, the results on my system (Arch Linux 64-bit, g++ 4.9.1, Intel i7-4930) were:

std::pow(i,2): 0.001105s (result = 3.33333e+07)
i*i: 0.000352s (result = 3.33333e+07)

std::pow(i,3): 0.006034s (result = 2.5e+07)
i*i*i: 0.000328s (result = 2.5e+07)

With optimisation, the results were equally striking:

std::pow(i,2): 0.000155s (result = 3.33333e+07)
i*i: 0.000106s (result = 3.33333e+07)

std::pow(i,3): 0.006066s (result = 2.5e+07)
i*i*i: 9.7e-05s (result = 2.5e+07)

So it looks like the compiler does at least try to optimise the std::pow(x,2) case, but not the std::pow(x,3) case (it takes ~40 times longer than the std::pow(x,2) case). In all cases, manual expansion performed better - but particularly for the power 3 case (60 times quicker). This is definitely worth bearing in mind if running std::pow() with integer powers greater than 2 in a tight loop...

CentOS: Enabling GD Support in PHP Installation

The thing that did the trick for me eventually was:

yum install gd gd-devel php-gd

and then restart apache:

service httpd restart

dropzone.js - how to do something after ALL files are uploaded

The accepted answer is not necessarily correct. queuecomplete will be called even when the selected file is larger than the max file size.

The proper event to use is successmultiple or completemultiple.

Reference: http://www.dropzonejs.com/#event-successmultiple

How can I access Google Sheet spreadsheets only with Javascript?

'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:

http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs

http://code.google.com/apis/spreadsheets/gadgets/

http://code.google.com/apis/gdata/docs/js.html

http://www.mail-archive.com/[email protected]/msg01924.html

May be these would help you out..

C++11 reverse range-based for-loop

This should work in C++11 without boost:

namespace std {
template<class T>
T begin(std::pair<T, T> p)
{
    return p.first;
}
template<class T>
T end(std::pair<T, T> p)
{
    return p.second;
}
}

template<class Iterator>
std::reverse_iterator<Iterator> make_reverse_iterator(Iterator it)
{
    return std::reverse_iterator<Iterator>(it);
}

template<class Range>
std::pair<std::reverse_iterator<decltype(begin(std::declval<Range>()))>, std::reverse_iterator<decltype(begin(std::declval<Range>()))>> make_reverse_range(Range&& r)
{
    return std::make_pair(make_reverse_iterator(begin(r)), make_reverse_iterator(end(r)));
}

for(auto x: make_reverse_range(r))
{
    ...
}

open program minimized via command prompt

Local Windows 10 ActiveMQ server :

@echo off
start /min "" "C:\Install\apache-activemq\5.15.10\bin\win64\activemq.bat" start

mean() warning: argument is not numeric or logical: returning NA

If you just want to know the mean, you can use

summary(results)

It will give you more information than expected.

ex) Mininum value, 1st Qu., Median, Mean, 3rd Qu. Maxinum value, number of NAs.

Furthermore, If you want to get mean values of each column, you can simply use the method below.

mean(results$columnName, na.rm = TRUE)

That will return mean value. (you have to change 'columnName' to your variable name

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

public int GetResult(List<int> list){
int first = list.First();
return list.All(x => x == first) ? first : SOME_OTHER_VALUE;
}

How to clone a Date object?

_x000D_
_x000D_
var orig = new Date();
var copy = new Date(+orig);

console.log(orig, copy);
_x000D_
_x000D_
_x000D_

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

How Long Does it Take to Learn Java for a Complete Newbie?

You can definitely get a good understanding of Java in 10 weeks, but as mentioned before, practice makes perfect (or at least better...). A couple of starting places:

The Java API will be your friend: http://java.sun.com/j2se/1.5.0/docs/api/

Java has a lot of built-in functionality so try not to duplicate it (String functions and whatnot).

Also, an IDE might make some things a little more complicated, but it'll also help you find your way around the API. Eclipse is a good place to start (and it's free) http://www.eclipse.org/

Hope that helps a little..

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

How to update core-js to core-js@3 dependency?

For npm

 npm install --save core-js@^3

for yarn

yarn add core-js@^3

how to initialize a char array?

This method uses the 'C' memset function, and is very fast (avoids a char-by-char loop).

const uint size = 65546;
char* msg = new char[size];
memset(reinterpret_cast<void*>(msg), 0, size);

How to emit an event from parent to child?

As far as I know, there are 2 standard ways you can do that.

1. @Input

Whenever the data in the parent changes, the child gets notified about this in the ngOnChanges method. The child can act on it. This is the standard way of interacting with a child.

Parent-Component
public inputToChild: Object;

Parent-HTML
<child [data]="inputToChild"> </child>       

Child-Component: @Input() data;

ngOnChanges(changes: { [property: string]: SimpleChange }){
   // Extract changes to the input property by its name
   let change: SimpleChange = changes['data']; 
// Whenever the data in the parent changes, this method gets triggered. You 
// can act on the changes here. You will have both the previous value and the 
// current value here.
}
  1. Shared service concept

Creating a service and using an observable in the shared service. The child subscribes to it and whenever there is a change, the child will be notified. This is also a popular method. When you want to send something other than the data you pass as the input, this can be used.

SharedService
subject: Subject<Object>;

Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);

Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{

// Whenever the parent emits using the next method, you can receive the data 
in here and act on it.})

How to update fields in a model without creating a new record in django?

Django has some documentation about that on their website, see: Saving changes to objects. To summarize:

.. to save changes to an object that's already in the database, use save().

How can I change NULL to 0 when getting a single value from a SQL function?

The easiest way to do this is just to add zero to your result.

i.e.

$A=($row['SUM'Price']+0);
echo $A;

hope this helps!!

Django templates: If false?

This is far easier to check in Python (i.e. your view code) than in the template, because the Python code is simply:

myvar is False

Illustrating:

>>> False is False
True
>>> None is False
False
>>> [] is False
False

The problem at the template level is that the template if doesn't parse is (though it does parse in). Also, if you don't mind it, you could try to patch support for is into the template engine; base it on the code for ==.

Pass a simple string from controller to a view MVC3

If you are trying to simply return a string to a View, try this:

public string Test()
{
     return "test";
}

This will return a view with the word test in it. You can insert some html in the string.

You can also try this:

public ActionResult Index()
{
    return Content("<html><b>test</b></html>");
}

How do I encode and decode a base64 string?

    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        { 
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }

Usage

    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

How can I get the current screen orientation?

I just want to propose another alternative that will concern some of you :

android:configChanges="orientation|keyboardHidden" 

implies that we explicitly declare the layout to be injected.

In case we want to keep the automatic injection thanks to the layout-land and layout folders. All you have to do is add it to the onCreate:

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        getSupportActionBar().hide();

    } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        getSupportActionBar().show();
    }

Here, we display or not the actionbar depending on the orientation of the phone

How to change date format using jQuery?

You can use date.js to achieve this:

var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');

Alternatively, you can do it natively like this:

_x000D_
_x000D_
var dateAr = '2014-01-06'.split('-');_x000D_
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);_x000D_
_x000D_
console.log(newDate);
_x000D_
_x000D_
_x000D_

How to subtract one month using moment.js?

For substracting in moment.js:

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

Documentation:

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

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

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

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

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

Graph implementation C++

The most common representations are probably these two:

Of these two the adjacency matrix is the simplest, as long as you don't mind having a (possibly huge) n * n array, where n is the number of vertices. Depending on the base type of the array, you can even store edge weights for use in e.g. shortest path discovery algorithms.

Self Join to get employee manager name

Additionally you may want to get managers and their reports count with -

SELECT e2.ename ,count(e1.ename)  FROM employee_s e1 LEFT OUTER JOIN employee_s e2 
ON e1.manager_id = e2.eid
group by e2.ename;

100% width Twitter Bootstrap 3 template

You're right using div.container-fluid and you also need a div.row child. Then, the content must be placed inside without any grid columns. If you have a look at the docs you can find this text:

  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
  • Use rows to create horizontal groups of columns.

Not using grid columns it's ok as stated here:

  • Content should be placed within columns, and only columns may be immediate children of rows.

And looking at this example, you can read this text:

Full width, single column: No grid classes are necessary for full-width elements.

Here's a live example showing some elements using the correct layout. This way you don't need any custom CSS or hack.

MongoDB: update every document on one field

I have been using MongoDB .NET driver for a little over a month now. If I were to do it using .NET driver, I would use Update method on the collection object. First, I will construct a query that will get me all the documents I am interested in and do an Update on the fields I want to change. Update in Mongo only affects the first document and to update all documents resulting from the query one needs to use 'Multi' update flag. Sample code follows...

var collection = db.GetCollection("Foo");
var query = Query.GTE("No", 1); // need to construct in such a way that it will give all 20K //docs.
var update = Update.Set("timestamp", datetime.UtcNow);
collection.Update(query, update, UpdateFlags.Multi);

Protect .NET code from reverse engineering?

A secret that you share with lots of people is not a secret. If you have secret stuff in your code, obfuscating it is no protection; it only has to be deobfuscated once. If you have a secret that you don't want to share with your customers, then don't share it with your customers. Write your code as a web service and keep your super secret code on your own server, where only you can see it.

What's a good hex editor/viewer for the Mac?

I have recently started using 0xED, and like it a lot.

How do I find the last column with data?

Try using the code after you active the sheet:

Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

If you use Cells.SpecialCells(xlCellTypeLastCell).Row only, the problem will be that the xlCellTypeLastCell information will not be updated unless one do a "Save file" action. But use UsedRange will always update the information in realtime.

validation of input text field in html using javascript

<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
    First Name: <input type="text" id="name" /> <br />
    <span id="nameErrMsg" class="error"></span> <br />
    <!-- ... all your other stuff ... -->
</form>
  <p>
    1.word should be atleast 5 letter<br>
    2.No space should be encountered<br>
    3.No numbers and special characters allowed<br>
    4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
  </p>
  <button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>


validateForm = function () {
    return checkName();
}

function checkName() {
    var x = document.myForm;
    var input = x.name.value;
    var errMsgHolder = document.getElementById('nameErrMsg');
    if (input.length < 5) {
        errMsgHolder.innerHTML =
            'Please enter a name with at least 5 letters';
        return false;
    } else if (!(/^\S{3,}$/.test(input))) {
        errMsgHolder.innerHTML =
            'Name cannot contain whitespace';
        return false;
    }else if(!(/^[a-zA-Z]+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'Only alphabets allowed'
    }
    else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'per 3 alphabets allowed'
    }
    else {
        errMsgHolder.innerHTML = '';
        return undefined;
    }       

}

.error {
color: #E00000;
 }

Get the week start date and week end date from week number

I have a way other, It is select day Start and day End of Week Current:

DATEADD(d, -(DATEPART(dw, GETDATE()-2)), GETDATE()) is date time Start

and

DATEADD(day,7-(DATEPART(dw,GETDATE()-1)),GETDATE()) is date time End

What does -> mean in C++?

x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().

How do I run a simple bit of code in a new thread?

BackgroundWorker seems to be best choice for you.

Here is my minimal example. After you click on the button the background worker will begin working in background thread and also report its progress simultaneously. It will also report after the work completes.

using System.ComponentModel;
...
    private void button1_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();

        // this allows our worker to report progress during work
        bw.WorkerReportsProgress = true;

        // what to do in the background thread
        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            // do some simple processing for 10 seconds
            for (int i = 1; i <= 10; i++)
            {
                // report the progress in percent
                b.ReportProgress(i * 10);
                Thread.Sleep(1000);
            }

        });

        // what to do when progress changed (update the progress bar for example)
        bw.ProgressChanged += new ProgressChangedEventHandler(
        delegate(object o, ProgressChangedEventArgs args)
        {
            label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);
        });

        // what to do when worker completes its task (notify the user)
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        delegate(object o, RunWorkerCompletedEventArgs args)
        {
            label1.Text = "Finished!";
        });

        bw.RunWorkerAsync();
    }

Note:

  • I put everything in single method using C#'s anonymous method for simplicity but you can always pull them out to different methods.
  • It is safe to update GUI within ProgressChanged or RunWorkerCompleted handlers. However, updating GUI from DoWork will cause InvalidOperationException.

How can you test if an object has a specific property?

Just check against null.

($myObject.MyProperty -ne $null)

If you have not set PowerShell to StrictMode, this works even if the property does not exist:

$obj = New-Object PSObject;                                                   
Add-Member -InputObject $obj -MemberType NoteProperty -Name Foo -Value "Bar";
$obj.Foo; # Bar                                                                  
($obj.MyProperty -ne $null);  # False, no exception

How to uninstall jupyter

If you are using jupyter notebook, You can remove it like this:

pip uninstall notebook

You should use conda uninstall if you installed it with conda.

Apply pandas function to column to create multiple new columns?

Building off of user1827356 's answer, you can do the assignment in one pass using df.merge:

df.merge(df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1})), 
    left_index=True, right_index=True)

    textcol  feature1  feature2
0  0.772692  1.772692 -0.227308
1  0.857210  1.857210 -0.142790
2  0.065639  1.065639 -0.934361
3  0.819160  1.819160 -0.180840
4  0.088212  1.088212 -0.911788

EDIT: Please be aware of the huge memory consumption and low speed: https://ys-l.github.io/posts/2015/08/28/how-not-to-use-pandas-apply/ !

How to check if a character in a string is a digit or letter

You could use:

    if (Character.isLetter(character.charAt(0))){
    ....

File to byte[] in Java

//The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4"); 

FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);

//Now the bytes of the file are contain in the "byte[] data"

CSS vertical alignment text inside li

However many years late this response may be, anyone coming across this might just want to try

li {
    display: flex;
    flex-direction: row;
    align-items: center;
}

Browser support for flexbox is far better than it was when @scottjoudry posted his response above, but you may still want to consider prefixing or other options if you're trying to support much older browsers. caniuse: flex

Passing data to a jQuery UI Dialog

This work for me:

<a href="#" onclick="sposta(100)">SPOSTA</a>

function sposta(id) {
        $("#sposta").data("id",id).dialog({
            autoOpen: true,
            modal: true,
            buttons: { "Sposta": function () { alert($(this).data('id')); } }
        });
    }

When you click on "Sposta" in dialog alert display 100

Spring - download response as a file

You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data

Angular2 Routing with Hashtag to page anchor

A simple solution that works for pages without any query parameters, is browser back / forward, router and deep-linking compliant.

<a (click)="jumpToId('anchor1')">Go To Anchor 1</a>


ngOnInit() {

    // If your page is dynamic
    this.yourService.getWhatever()
        .then(
            data => {
            this.componentData = data;
            setTimeout(() => this.jumpToId( window.location.hash.substr(1) ), 100);
        }
    );

    // If your page is static
    // this.jumpToId( window.location.hash.substr(1) )
}

jumpToId( fragment ) {

    // Use the browser to navigate
    window.location.hash = fragment;

    // But also scroll when routing / deep-linking to dynamic page
    // or re-clicking same anchor
    if (fragment) {
        const element = document.querySelector('#' + fragment);
        if (element) element.scrollIntoView();
    }
}

The timeout is simply to allow the page to load any dynamic data "protected" by an *ngIf. This can also be used to scroll to the top of the page when changing route - just provide a default top anchor tag.

Can Android do peer-to-peer ad-hoc networking?

Your answer is Wi-Fi direct which is made available with ICS. Here is a link for explanation in Android doc

Required attribute on multiple checkboxes with the same name?

var verifyPaymentType = function () {
   //coloque os checkbox dentro de uma div com a class checkbox
  var inputs =  window.jQuery('.checkbox').find('input');
  var first = inputs.first()[0];

  inputs.on('change', function () {
    this.setCustomValidity('');
  });

  first.setCustomValidity( window.jQuery('.checkbox').find('input:checked').length === 0 ? 'Choose one' : '');
}

window.jQuery('#submit').click(verifyPaymentType);

}

What Scala web-frameworks are available?

It must be noted that there is also a considerable interest in Wicket and Scala. Wicket fits Scala suprisingly well. If you want to take advantage of the very mature Wicket project and its ecosystem (extensions) plus the concise syntax and productivity advantage of Scala, this one may be for you!

See also:

  1. Some prosa

  2. Presentation

  3. Some experience with Wicket and Scala

  4. Announcments with reference to the project for the glue code to bind Scala closures to models

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

error: ‘NULL’ was not declared in this scope

You can declare the macro NULL. Add that after your #includes:

#define NULL 0

or

#ifndef NULL
#define NULL 0
#endif

No ";" at the end of the instructions...

invalid_grant trying to get oAuth token from google

For future folks... I read many articles and blogs but had luck with solution below...

GoogleTokenResponse tokenResponse =
      new GoogleAuthorizationCodeTokenRequest(
          new NetHttpTransport(),
          JacksonFactory.getDefaultInstance(),
          "https://www.googleapis.com/oauth2/v4/token",
          clientId,
          clientSecret,
          authCode,
          "") //Redirect Url
     .setScopes(scopes)
     .setGrantType("authorization_code")
     .execute();

This blog depicts different cases in which "invalid_grant" error comes.

Enjoy!!!

How to set Apache Spark Executor memory

create a file called spark-env.sh in spark/conf directory and add this line

SPARK_EXECUTOR_MEMORY=2000m #memory size which you want to allocate for the executor

How do I access call log for android?

Before considering making Read Call Log or Read SMS permissions a part of your application I strongly advise you to have a look at this policy of Google Play Market: https://support.google.com/googleplay/android-developer/answer/9047303?hl=en

Those permissions are very sensitive and you will have to prove that your application needs them. But even if it really needs them Google Play Support team may easily reject your request without proper explanations.

This is what happened to me. After providing all the needed information along with the Demonstration video of my application it was rejected with the explanation that my "account is not authorized to provide a certain use case solution in my application" (the list of use cases they may consider as an exception is listed on that Policy page). No link to any policy statement was provided to explain what it all means. Basically they just judged my app as not to go without proper explanation.

I wish you good luck of cause with your applications guys but be careful.

Connect over ssh using a .pem file

You can connect to a AWS ec-2 instance using the following commands.

chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

ssh -i mykey.pem ubuntu@your-ip

Can I change the scroll speed using css or jQuery?

The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).

WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.

Toni Almeida of Portugal created a brilliant demo, reproduced below:

jsFiddle Demo

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:

How to change default scrollspeed,scrollamount,scrollinertia of a webpage

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Add swipe to delete UITableViewCell

Xcode asks for UIContextualAction, here what worked for me for the updated version:

For Trailing Swipe Actions:->

 func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let company = companies[indexPath.row]
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
           // Perform Delete Action
        }
        return action
    }
    
    func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
            // Perform Edit Action
        }
        return action
    }
    
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = self.delete(forRowAtIndexPath: indexPath)
        let edit = self.edit(forRowAtIndexPath: indexPath)
        let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
        return swipe
    }

For Leading Swipe Actions:->

 func delete(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let company = companies[indexPath.row]
        let action = UIContextualAction(style: .destructive, title: "Delete") { (action, view, _) in
           // Perform Delete Action
        }
        return action
    }
    
    func edit(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        let action  = UIContextualAction(style: .normal, title: "Edit") { (action, view, escaping) in
            // Perform Edit Action
        }
        return action
    }
    
    override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = self.delete(forRowAtIndexPath: indexPath)
        let edit = self.edit(forRowAtIndexPath: indexPath)
        let swipe = UISwipeActionsConfiguration(actions: [delete, edit])
        return swipe
    }

Return true for canEditRowAt for tableView Delegate:->

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

switch case statement error: case expressions must be constant expression

In a regular Android project, constants in the resource R class are declared like this:

public static final int main=0x7f030004;

However, as of ADT 14, in a library project, they will be declared like this:

public static int main=0x7f030004;

In other words, the constants are not final in a library project. Therefore your code would no longer compile.

The solution for this is simple: Convert the switch statement into an if-else statement.

public void onClick(View src)
{
    int id = src.getId();
    if (id == R.id.playbtn){
        checkwificonnection();
    } else if (id == R.id.stopbtn){
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
    } else if (id == R.id.btnmenu){
        openOptionsMenu();
    }
}

http://tools.android.com/tips/non-constant-fields

You can quickly convert a switch statement to an if-else statement using the following:

In Eclipse
Move your cursor to the switch keyword and press Ctrl + 1 then select

Convert 'switch' to 'if-else'.

In Android Studio
Move your cursor to the switch keyword and press Alt + Enter then select

Replace 'switch' with 'if'.

How to get the primary IP address of the local machine on Linux and OS X?

Another ifconfig variantion that works both on Linux and OSX:

ifconfig | grep "inet " | cut -f2 -d' '

How can I generate a 6 digit unique number?

Try this using uniqid and hexdec,

echo hexdec(uniqid());

How do you use subprocess.check_output() in Python?

Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():

>>> subprocess.run(['cat','/tmp/text.txt'], stdout=subprocess.PIPE).stdout
b'First line\nSecond line\n'

Since Python 3.7, instead of the above, you can use capture_output=true parameter to capture stdout and stderr:

>>> subprocess.run(['cat','/tmp/text.txt'], capture_output=True).stdout
b'First line\nSecond line\n'

Also, you may want to use universal_newlines=True or its equivalent since Python 3.7 text=True to work with text instead of binary:

>>> stdout = subprocess.run(['cat', '/tmp/text.txt'], capture_output=True, text=True).stdout
>>> print(stdout)
First line
Second line

See subprocess.run() documentation for more information.

How to move files from one git repo to another (not a clone), preserving history

Yep, hitting on the --subdirectory-filter of filter-branch was key. The fact that you used it essentially proves there's no easier way - you had no choice but to rewrite history, since you wanted to end up with only a (renamed) subset of the files, and this by definition changes the hashes. Since none of the standard commands (e.g. pull) rewrite history, there's no way you could use them to accomplish this.

You could refine the details, of course - some of your cloning and branching wasn't strictly necessary - but the overall approach is good! It's a shame it's complicated, but of course, the point of git isn't to make it easy to rewrite history.

How to set default values in Go structs

One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.

package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
    Name string
    Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
    return candidate{name, 0}  // enforce the default value here
}

Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.

Getting "project" nuget configuration is invalid error

NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.

Updating Visual Studio to 'Update 2' got it working again.

Tools -> Extensions and Updates ->Visual Studio Update 2

As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.

Adding integers to an int array

You cannot use the add method on an array in Java.

To add things to the array do it like this

public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
    int neki = Integer.parseInt(s);
    num[i] = neki;

}

If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.

ArrayList Example

public static void main(String[] args) {
    ArrayList<Integer> num = new ArrayList<Integer>();
    for (String s : args){
        Integer neki = new Integer(Integer.parseInt(s));
        num.add(s);
}

Repeat String - Javascript

Concatenating strings based on an number.

function concatStr(str, num) {
   var arr = [];

   //Construct an array
   for (var i = 0; i < num; i++)
      arr[i] = str;

   //Join all elements
   str = arr.join('');

   return str;
}

console.log(concatStr("abc", 3));

Hope that helps!

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

Remove all spaces from a string in SQL Server

Try to use like this, if normal spaces are not removed by LTRM or RTRM

LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column_data, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))

ERROR 1148: The used command is not allowed with this MySQL version

If you are using Java8 or + version, JDBC and MySql8 and facing this issue then try this:

Add parameter to connection string:

jdbc:mysql://localhost:3306/tempDB?allowLoadLocalInfile=true

Also, set

local_infile = 1

in my.cnf file.

The latest version of mysql-java-connector might be wont allow directly to connect to local file. So with this parameter, you can able to enable it. This works for me.

Send Email to multiple Recipients with MailMessage?

Easy!

Just split the incoming address list on the ";" character, and add them to the mail message:

foreach (var address in addresses.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    mailMessage.To.Add(address);    
}

In this example, addresses contains "[email protected];[email protected]".

mysql query: SELECT DISTINCT column1, GROUP BY column2

Replacing FROM tablename with FROM (SELECT DISTINCT * FROM tablename) should give you the result you want (ignoring duplicated rows) for example:

SELECT name, COUNT(*)
FROM (SELECT DISTINCT * FROM Table1) AS T1
GROUP BY name

Result for your test data:

dave 2
mark 2

How can I get the Google cache age of any URL or web page?

This one good also to view cachepage http://www.cachepage.net

  1. Cache page view via google: webcache.googleusercontent.com/search?q=cache: Your url

  2. Cache page view via archive.org: web.archive.org/web/*/Your url

How do I remove  from the beginning of a file?

For those with shell access here is a little command to find all files with the BOM set in the public_html directory - be sure to change it to what your correct path on your server is

Code:

grep -rl $'\xEF\xBB\xBF' /home/username/public_html

and if you are comfortable with the vi editor, open the file in vi:

vi /path-to-file-name/file.php

And enter the command to remove the BOM:

set nobomb

Save the file:

wq

fastest way to export blobs from table into individual files

I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:

declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1; 
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources

You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

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.

Cancel split window in Vim

Just like the others said before the way to do this is to press ctrl+w and then o. This will "maximize" the current window, while closing the others. If you'd like to be able to "unmaximize" it, there's a plugin called ZoomWin for that. Otherwise you'd have to recreate the window setup from scratch.

how to create insert new nodes in JsonNode?

These methods are in ObjectNode: the division is such that most read operations are included in JsonNode, but mutations in ObjectNode and ArrayNode.

Note that you can just change first line to be:

ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type

or

ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast

Python class returning value

I think you are very confused about what is occurring.

In Python, everything is an object:

  • [] (a list) is an object
  • 'abcde' (a string) is an object
  • 1 (an integer) is an object
  • MyClass() (an instance) is an object
  • MyClass (a class) is also an object
  • list (a type--much like a class) is also an object

They are all "values" in the sense that they are a thing and not a name which refers to a thing. (Variables are names which refer to values.) A value is not something different from an object in Python.

When you call a class object (like MyClass() or list()), it returns an instance of that class. (list is really a type and not a class, but I am simplifying a bit here.)

When you print an object (i.e. get a string representation of an object), that object's __str__ or __repr__ magic method is called and the returned value printed.

For example:

>>> class MyClass(object):
...     def __str__(self):
...             return "MyClass([])"
...     def __repr__(self):
...             return "I am an instance of MyClass at address "+hex(id(self))
... 
>>> m = MyClass()
>>> print m
MyClass([])
>>> m
I am an instance of MyClass at address 0x108ed5a10
>>> 

So what you are asking for, "I need that MyClass return a list, like list(), not the instance info," does not make any sense. list() returns a list instance. MyClass() returns a MyClass instance. If you want a list instance, just get a list instance. If the issue instead is what do these objects look like when you print them or look at them in the console, then create a __str__ and __repr__ method which represents them as you want them to be represented.

Update for new question about equality

Once again, __str__ and __repr__ are only for printing, and do not affect the object in any other way. Just because two objects have the same __repr__ value does not mean they are equal!

MyClass() != MyClass() because your class does not define how these would be equal, so it falls back to the default behavior (of the object type), which is that objects are only equal to themselves:

>>> m = MyClass()
>>> m1 = m
>>> m2 = m
>>> m1 == m2
True
>>> m3 = MyClass()
>>> m1 == m3
False

If you want to change this, use one of the comparison magic methods

For example, you can have an object that is equal to everything:

>>> class MyClass(object):
...     def __eq__(self, other):
...             return True
... 
>>> m1 = MyClass()
>>> m2 = MyClass()
>>> m1 == m2
True
>>> m1 == m1
True
>>> m1 == 1
True
>>> m1 == None
True
>>> m1 == []
True

I think you should do two things:

  1. Take a look at this guide to magic method use in Python.
  2. Justify why you are not subclassing list if what you want is very list-like. If subclassing is not appropriate, you can delegate to a wrapped list instance instead:

    class MyClass(object):
        def __init__(self):
            self._list = []
        def __getattr__(self, name):
            return getattr(self._list, name)
    
        # __repr__ and __str__ methods are automatically created
        # for every class, so if we want to delegate these we must
        # do so explicitly
        def __repr__(self):
            return "MyClass(%s)" % repr(self._list)
        def __str__(self):
            return "MyClass(%s)" % str(self._list)
    

    This will now act like a list without being a list (i.e., without subclassing list).

    >>> c = MyClass()
    >>> c.append(1)
    >>> c
    MyClass([1])
    

How to skip the first n rows in sql query

Use this:

SELECT *
FROM Sales.SalesOrderHeader 
ORDER BY OrderDate
OFFSET (@Skip) ROWS FETCH NEXT (@Take) ROWS ONLY

https://stackoverflow.com/a/19669165/1883345

Combine a list of data frames into one data frame by row

bind-plot

Code:

library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
plyr::rbind.fill(dflist),
dplyr::bind_rows(dflist),
data.table::rbindlist(dflist),
plyr::ldply(dflist,data.frame),
do.call("rbind",dflist),
times=1000)

ggplot2::autoplot(mb)

Session:

R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

> packageVersion("plyr")
[1] ‘1.8.4’
> packageVersion("dplyr")
[1] ‘0.5.0’
> packageVersion("data.table")
[1] ‘1.9.6’

UPDATE: Rerun 31-Jan-2018. Ran on the same computer. New versions of packages. Added seed for seed lovers.

enter image description here

set.seed(21)
library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
  plyr::rbind.fill(dflist),
  dplyr::bind_rows(dflist),
  data.table::rbindlist(dflist),
  plyr::ldply(dflist,data.frame),
  do.call("rbind",dflist),
  times=1000)

ggplot2::autoplot(mb)+theme_bw()


R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

> packageVersion("plyr")
[1] ‘1.8.4’
> packageVersion("dplyr")
[1] ‘0.7.2’
> packageVersion("data.table")
[1] ‘1.10.4’

UPDATE: Rerun 06-Aug-2019.

enter image description here

set.seed(21)
library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
  plyr::rbind.fill(dflist),
  dplyr::bind_rows(dflist),
  data.table::rbindlist(dflist),
  plyr::ldply(dflist,data.frame),
  do.call("rbind",dflist),
  purrr::map_df(dflist,dplyr::bind_rows),
  times=1000)

ggplot2::autoplot(mb)+theme_bw()

R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so

packageVersion("plyr")
packageVersion("dplyr")
packageVersion("data.table")
packageVersion("purrr")

>> packageVersion("plyr")
[1] ‘1.8.4’
>> packageVersion("dplyr")
[1] ‘0.8.3’
>> packageVersion("data.table")
[1] ‘1.12.2’
>> packageVersion("purrr")
[1] ‘0.3.2’

Reading json files in C++

storing peoples like this

{"Anna" : { 
  "age": 18,
  "profession": "student"},
"Ben" : {
  "age" : "nineteen",
  "profession": "mechanic"}
 }

will cause problems, particularly if differents peoples have same name..

rather use array storing objects like this

{
  "peoples":[
       { 
           "name":"Anna",  
           "age": 18,
           "profession": "student"
       },
       {
           "name":"Ben",
           "age" : "nineteen",
           "profession": "mechanic"
       } 
  ]
}

like this, you can enumerates objects, or acces objects by numerical index. remember that json is storage structure, not dynamically sorter or indexer. use data stored in json to build indexes as you need and acces data.

Get the current language in device

If you choose a language you can't type this Greek may be helpful.

getDisplayLanguage().toString() = English
getLanguage().toString() = en 
getISO3Language().toString() = eng
getDisplayLanguage()) = English
getLanguage() = en
getISO3Language() = eng

Now try it with Greek

getDisplayLanguage().toString() = ????????
getLanguage().toString() = el
getISO3Language().toString() = ell
getDisplayLanguage()) = ????????
getLanguage() = el
getISO3Language() = ell

How to trigger ngClick programmatically

angular.element(domElement).triggerHandler('click');

EDIT: It appears that you have to break out of the current $apply() cycle. One way to do this is using $timeout():

$timeout(function() {
    angular.element(domElement).triggerHandler('click');
}, 0);

See fiddle: http://jsfiddle.net/t34z7/

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

What i found...when i got 'EntityValidationErrors' error is that....i have a field in my database 'db1' in table 'tbladdress' as 'address1' which has size of 100 (i.e address varchar(100) null) and i was passing value more than 100 characters..and this leading to error while saving data to database....

So you must Check the data you are passing to the field.

How to develop Android app completely using python?

You could try BeeWare - as described on their website:

Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.

Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.

Here's the Tutorial for Android Apps.

Programmatically relaunch/recreate an activity?

I once made a test app that uploads, deletes, and then redownloads the database file using firebase cloud storage. To display the data in database, the following code was the only solution I found. Neither recreate() nor finish() worked in this case.

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
System.exit(0);

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
      android:icon="@drawable/menu_icon"
      android:orderInCategory="l01"
      android:title="Item One"
      my_menu_tutorial_app:showAsAction="always">
      <!--sub-menu-->
      <menu>
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />
      </menu>

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
    {
        case R.id.sub_one:
            isItemOneSelected = true;
            supportInvalidateOptionsMenu();
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            supportInvalidateOptionsMenu();
            return true;
        default:
            return false;
    }
}

This is the easiest way to display menus in action bar.

Does Python have “private” variables in classes?

The only time I ever use private variables is when I need to do other things when writing to or reading from the variable and as such I need to force the use of a setter and/or getter.

Again this goes to culture, as already stated. I've been working on projects where reading and writing other classes variables was free-for-all. When one implementation became deprecated it took a lot longer to identify all code paths that used that function. When use of setters and getters was forced, a debug statement could easily be written to identify that the deprecated method had been called and the code path that calls it.

When you are on a project where anyone can write an extension, notifying users about deprecated methods that are to disappear in a few releases hence is vital to keep module breakage at a minimum upon upgrades.

So my answer is; if you and your colleagues maintain a simple code set then protecting class variables is not always necessary. If you are writing an extensible system then it becomes imperative when changes to the core is made that needs to be caught by all extensions using the code.

Append to string variable

Ronal, to answer your question in the comment in my answer above:

function wasClicked(str)
{
  return str+' def';
}

How do you create a dictionary in Java?

You'll want a Map<String, String>. Classes that implement the Map interface include (but are not limited to):

Each is designed/optimized for certain situations (go to their respective docs for more info). HashMap is probably the most common; the go-to default.

For example (using a HashMap):

Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal

jQuery deferreds and promises - .then() vs .done()

The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.

Prior to jQuery 1.8, then() was just syntactic sugar:

promise.then( doneCallback, failCallback )
// was equivalent to
promise.done( doneCallback ).fail( failCallback )

As of 1.8, then() is an alias for pipe() and returns a new promise, see here for more information on pipe().

success() and error() are only available on the jqXHR object returned by a call to ajax(). They are simple aliases for done() and fail() respectively:

jqXHR.done === jqXHR.success
jqXHR.fail === jqXHR.error

Also, done() is not limited to a single callback and will filter out non-functions (though there is a bug with strings in version 1.8 that should be fixed in 1.8.1):

// this will add fn1 to 7 to the deferred's internal callback list
// (true, 56 and "omg" will be ignored)
promise.done( fn1, fn2, true, [ fn3, [ fn4, 56, fn5 ], "omg", fn6 ], fn7 );

Same goes for fail().

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

This application has no explicit mapping for /error

I too got the same error and was able to resolve the error by adding the below dependency to my pom.xml.

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

Reason is we are using JSP as the view. Default embedded servlet container for Spring Boot Starter Web is tomcat. To enable support for JSP’s, we would need to add a dependency on tomcat-embed-jasper.

In my case I was returning a JSP as view from controller. Hope this answer helps someone who are struggling with same issue.

Streaming via RTSP or RTP in HTML5

With VLC i'm able to transcode a live RTSP stream (mpeg4) to an HTTP stream in a OGG format (Vorbis/Theora). The quality is poor but the video work in Chrome 9. I have also tested with a trancoding in WEBM (VP8) but it's don't seem to work (VLC have the option but i don't know if it's really implemented for now..)

The first to have a doc on this should notify us ;)

How to use Switch in SQL Server

Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.

What's wrong with:

IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
    SET @SelectoneCount = @SelectoneCount + 1
END

(Although this does reek of being procedural code - not usually the best way to use SQL)

Bootstrap modal: close current, open new

This code, close modal opened, open the new modal but inmediatly, new modal is closed.

$(nameClose).modal('hide');
$(nameOpen).modal('show');

My solution for open new modal after close other is:

function swapModals(nameClose,nameOpen) {
    $(nameClose).modal('hide');
    $(nameClose).on('hidden.bs.modal', function () {
        console.log('Fired when hide event has finished!');
        $(nameOpen).modal('show');
    });
}

Difference between null and empty ("") Java String

"" and null both are different . the first one means as part of string variable declaration the string constant has been created in the string pool and some memory has been assigned for the same.

But when we are declaring it with null then it has just been instantiated jvm , but no memory has been allocated for it. therefore if you are trying to access this object by checking it with "" - blank variable , it can't prevent nullpointerexception . Please find below one use-case.

public class StringCheck {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String s1 = "siddhartha";
    String s2 = "";
    String s3 = null;

    System.out.println("length s1 ="+s1.length());
    System.out.println("length s2 ="+s2.length());

    //this piece of code will still throw nullpointerexception . 
    if(s3 != ""){
        System.out.println("length s3 ="+s3.length());
    }
}

}

jQuery remove options from select

For jquery < 1.8 you can use :

$('#selectedId option').slice(index1,index2).remove()

to remove a especific range of the select options.

Why is there no Constant feature in Java?

You can use static final to create something that works similar to Const, I have used this in the past.

protected static final int cOTHER = 0;
protected static final int cRPM = 1;
protected static final int cSPEED = 2;
protected static final int cTPS = 3;
protected int DataItemEnum = 0;

public static final int INVALID_PIN = -1;
public static final int LED_PIN = 0;

Java: How can I compile an entire directory structure of code ?

The already existing answers seem to only concern oneself with the *.java files themselves and not how to easily do it with library files that might be needed for the build.

A nice one-line situation which recursively gets all *.java files as well as includes *.jar files necessary for building is:

javac -cp ".:lib/*" -d bin $(find ./src/* | grep .java)

Here the bin file is the destination of class files, lib (and potentially the current working directory) contain the library files and all the java files in the src directory and beneath are compiled.

Check whether a path is valid

The closest I have come is by trying to create it, and seeing if it succeeds.

Printing variables in Python 3.4

one can print values using the format method in python. This small example will help take input of two numbers a and b. Print a+b in first line and a-b in second line

print('{:d}\n{:d}'.format(a+b,a-b))

Similarly in the answer we can do

print ("{0}. {1} appears {2} times.".format(22, 'c', 9999))

The python method format() for string is used to specify a string format. So {0},{1},{2} are like array indexes called as positional parameters. Therefore {0} is assigned first value written in format (a+b), {1} is assigned the second value (a-b) and so on. We can also use keyword instead of positional parameter like for example

print("Hi! my name is {name}".format(name="rashi"))

Therefore name here is the keyword and its value is Rashi Hope it helps :)

log4j:WARN No appenders could be found for logger (running jar file, not web app)

Solution

  1. Download log4j.jar file
  2. Add the log4j.jar file to build path
  3. Call logger by:

    private static org.apache.log4j.Logger log 
        = Logger.getLogger(<class-where-this-is-used>.class);
    
  4. if log4j properties does not exist, create new file log4j.properties file new file in bin directory:

    /workspace/projectdirectory/bin/
    

Sample log4j.properties file

log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%t %-5p %c{2} - %m%n 

How to Configure SSL for Amazon S3 bucket

I found you can do this easily via the Cloud Flare service.

Set up a bucket, enable webhosting on the bucket and point the desired CNAME to that endpoint via Cloudflare... and pay for the service of course... but $5-$20 VS $600 is much easier to stomach.

Full detail here: https://www.engaging.io/easy-way-to-configure-ssl-for-amazon-s3-bucket-via-cloudflare/

What is "runtime"?

Runtime describes software/instructions that are executed while your program is running, especially those instructions that you did not write explicitly, but are necessary for the proper execution of your code.

Low-level languages like C have very small (if any) runtime. More complex languages like Objective-C, which allows for dynamic message passing, have a much more extensive runtime.

You are correct that runtime code is library code, but library code is a more general term, describing the code produced by any library. Runtime code is specifically the code required to implement the features of the language itself.

Find maximum value of a column and return the corresponding row values using Pandas

df[df['Value']==df['Value'].max()]

This will return the entire row with max value

Laravel 4: Redirect to a given url

You can also use redirect() method like this:-

return redirect('https://stackoverflow.com/');

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

npm install --production --no-optional

It installs only deps from dependencies and will ignore optionalDependencies and devDependencies

Find character position and update file name

If you're working with actual files (as opposed to some sort of string data), how about the following?

$files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }

(or use _.+$ if you want to cut everything from the first underscore.)

how to access master page control from content page

In the MasterPage.cs file add the property of Label like this:

public string ErrorMessage
{
    get
    {
        return lblMessage.Text;
    }
    set
    {
        lblMessage.Text = value;
    }
}

On your aspx page, just below the Page Directive add this:

<%@ Page Title="" Language="C#" MasterPageFile="Master Path Name"..... %>
<%@ MasterType VirtualPath="Master Path Name" %>   // Add this

And in your codebehind(aspx.cs) page you can then easily access the Label Property and set its text as required. Like this:

this.Master.ErrorMessage = "Your Error Message here";

Why is the Java main method static?

The main method of the program has the reserved word static which means it is allowed to be used in the static context. A context relates to the use of computer memory during the running of the program. When the virtual machine loads a program, it creates the static context for it, allocating computer memory to store the program and its data, etc.. A dynamic context is certain kind of allocation of memory which is made later, during the running of the program. The program would not be able to start if the main method was not allowed to run in the static context.

Push origin master error on new repository

cd  app 

git init 

git status 

touch  test 

git add . 

git commit  -a  -m"message to log " 

git commit  -a  -m "message to log" 

git remote add origin 

 git remote add origin [email protected]:cherry 

git push origin master:refs/heads/master

git clone [email protected]:cherry test1

CSS border less than 1px

A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).

Here is a test to prove this point:

_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_

Output

enter image description here

Which gives the illusion that the last DIV has a smaller border width, because the blue border blends more with the white background.


Edit: Alternate solution

Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.

_x000D_
_x000D_
.container {
  border-style: solid;
  border-width: 1px;
  
  margin-bottom: 10px;
}

.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_

Python how to write to a binary file?

As of Python 3.2+, you can also accomplish this using the to_bytes native int method:

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

I.e., each single call to to_bytes in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte. You can also shorten the last two lines into a single one:

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

How can I declare a global variable in Angular 2 / Typescript?

A shared service is the best approach

export class SharedService {
  globalVar:string;
}

But you need to be very careful when registering it to be able to share a single instance for whole your application. You need to define it when registering your application:

bootstrap(AppComponent, [SharedService]);

But not to define it again within the providers attributes of your components:

@Component({
  (...)
  providers: [ SharedService ], // No
  (...)
})

Otherwise a new instance of your service will be created for the component and its sub-components.

You can have a look at this question regarding how dependency injection and hierarchical injectors work in Angular 2:

You should notice that you can also define Observable properties in the service to notify parts of your application when your global properties change:

export class SharedService {
  globalVar:string;
  globalVarUpdate:Observable<string>;
  globalVarObserver:Observer;

  constructor() {
    this.globalVarUpdate = Observable.create((observer:Observer) => {
      this.globalVarObserver = observer;
    });
  }

  updateGlobalVar(newValue:string) {
    this.globalVar = newValue;
    this.globalVarObserver.next(this.globalVar);
  }
}

See this question for more details:

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

Clear android application user data

This command worked for me:

adb shell pm clear packageName

How to convert C++ Code to C

http://llvm.org/docs/FAQ.html#translatecxx

It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.

Usage sytax from the command line is as follows for version 9.0.1:

clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
clang -march=c  CPPtoC.bc -o CPPtoC.c

For older versions (unsure of transition version), use the following syntax:

llvm-g++ -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
llc -march=c  CPPtoC.bc -o CPPtoC.c

Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.

Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.

EDIT : although official support of this functionality was removed, but users can still use this unofficial support from Julia language devs, to achieve mentioned above functionality.

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

How to set character limit on the_content() and the_excerpt() in wordpress

This also balances HTML tags so that they won't be left open and doesn't break words.

add_filter("the_content", "break_text");
function break_text($text){
    $length = 500;
    if(strlen($text)<$length+10) return $text;//don't cut if too short

    $break_pos = strpos($text, ' ', $length);//find next space after desired length
    $visible = substr($text, 0, $break_pos);
    return balanceTags($visible) . " […]";
} 

How to make a whole 'div' clickable in html and css without JavaScript?

we are using like this

     <label for="1">
<div class="options">
<input type="radio" name="mem" id="1" value="1" checked="checked"/>option one
    </div>
</label>
   <label for="2"> 
<div class="options">
 <input type="radio" name="mem" id="2" value="1" checked="checked"/>option two
</div></label>

using

  <label for="1">

tag and catching is with

id=1

hope this helps.

Setting session variable using javascript

You can use

sessionStorage.SessionName = "SessionData" ,

sessionStorage.getItem("SessionName") and

sessionStorage.setItem("SessionName","SessionData");

See the supported browsers on http://caniuse.com/namevalue-storage

Get filename in batch for loop

or Just %~F will give you the full path and full file name.

For example, if you want to register all *.ax files in the current directory....

FOR /R C:. %F in (*.ax) do regsvr32 "%~F"

This works quite nicely in Win7 (64bit) :-)

Deleting rows from parent and child tables

Two possible approaches.

  1. If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.

  2. Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?

      delete from child_table
          where parent_id in (
               select parent_id from parent_table
                    where updd_tms != (sysdate-30)
    

    -- now delete the parent table records

    delete from parent_table
    where updd_tms != (sysdate-30);
    

---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).

declare
    v_sqlcode number;
    PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
    for v_rec in (select parent_id, child id from child_table
                         where updd_tms != (sysdate-30) ) loop

    -- delete the children
    delete from child_table where child_id = v_rec.child_id;

    -- delete the parent. If we get foreign key violation, 
    -- stop this step and continue the loop
    begin
       delete from parent_table
          where parent_id = v_rec.parent_id;
    exception
       when foreign_key_violated
         then null;
    end;
 end loop;
end;
/

Keras, how do I predict after I trained a model?

model.predict() expects the first parameter to be a numpy array. You supply a list, which does not have the shape attribute a numpy array has.

Otherwise your code looks fine, except that you are doing nothing with the prediction. Make sure you store it in a variable, for example like this:

prediction = model.predict(np.array(tk.texts_to_sequences(text)))
print(prediction)

Removing an element from an Array (Java)

Swap the item to be removed with the last item, if resizing the array down is not an interest.

estimating of testing effort as a percentage of development time

Gartner in Oct 2006 states that testing typically consumes between 10% and 35% of work on a system integration project. I assume that it applies to the waterfall method. This is quite a wide range - but there are many dependencies on the amount of customisations to a standard product and the number of systems to be integrated.

Get only specific attributes with from Laravel Collection

$users = Users::get();

$subset = $users->map(function ($user) {
    return array_only(user, ['id', 'name', 'email']);
});

Show popup after page load

try something like this

<script type="text/javascript">
function PopUp(hideOrshow) {
    if (hideOrshow == 'hide') document.getElementById('ac-wrapper').style.display = "none";
    else document.getElementById('ac-wrapper').removeAttribute('style');
}
window.onload = function () {
    setTimeout(function () {
        PopUp('show');
    }, 5000);
}
</script>

and your html

<div id="ac-wrapper" style='display:none'>
    <div id="popup">
        <center>
             <h2>Popup Content Here</h2>    
            <input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
        </center>
    </div>
</div>

Demo JsFiddle

ReactJS - Add custom event listener to component

If you need to handle DOM events not already provided by React you have to add DOM listeners after the component is mounted:

Update: Between React 13, 14, and 15 changes were made to the API that affect my answer. Below is the latest way using React 15 and ES7. See answer history for older versions.

class MovieItem extends React.Component {

  componentDidMount() {
    // When the component is mounted, add your DOM listener to the "nv" elem.
    // (The "nv" elem is assigned in the render function.)
    this.nv.addEventListener("nv-enter", this.handleNvEnter);
  }

  componentWillUnmount() {
    // Make sure to remove the DOM listener when the component is unmounted.
    this.nv.removeEventListener("nv-enter", this.handleNvEnter);
  }

  // Use a class arrow function (ES7) for the handler. In ES6 you could bind()
  // a handler in the constructor.
  handleNvEnter = (event) => {
    console.log("Nv Enter:", event);
  }

  render() {
    // Here we render a single <div> and toggle the "aria-nv-el-current" attribute
    // using the attribute spread operator. This way only a single <div>
    // is ever mounted and we don't have to worry about adding/removing
    // a DOM listener every time the current index changes. The attrs 
    // are "spread" onto the <div> in the render function: {...attrs}
    const attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};

    // Finally, render the div using a "ref" callback which assigns the mounted 
    // elem to a class property "nv" used to add the DOM listener to.
    return (
      <div ref={elem => this.nv = elem} aria-nv-el {...attrs} className="menu_item nv-default">
        ...
      </div>
    );
  }

}

Example on Codepen.io

Advantage of switch over if-else statement

For the special case that you've provided in your example, the clearest code is probably:

if (RequiresSpecialEvent(numError))
    fire_special_event();

Obviously this just moves the problem to a different area of the code, but now you have the opportunity to reuse this test. You also have more options for how to solve it. You could use std::set, for example:

bool RequiresSpecialEvent(int numError)
{
    return specialSet.find(numError) != specialSet.end();
}

I'm not suggesting that this is the best implementation of RequiresSpecialEvent, just that it's an option. You can still use a switch or if-else chain, or a lookup table, or some bit-manipulation on the value, whatever. The more obscure your decision process becomes, the more value you'll derive from having it in an isolated function.

NoClassDefFoundError for code in an Java library on Android

In my case, I was trying to add a normal java class (from a normal java project) compiled with jre 1.7 to an android app project compiled with jre 1.7.

The solution was to recompile that normal java class with jre 1.6 and add references to the android app project (compiled with jre 1.6 also) as usual (in tab order and export be sure to check the class, project, etc).

The same process, when using an android library to reference external normal java classes.

Don't know what's wrong with jre 1.7, when compiling normal java classes from a normal java project and try to reference them in android app or android library projects.

If you don't use normal java classes (from a normal java project) you don't need to downgrade to jre 1.6.

How do I declare and initialize an array in Java?

If by "array" you meant using java.util.Arrays, you can do it like that :

List<String> number = Arrays.asList("1", "2", "3");

Out: ["1", "2", "3"]

This one is pretty simple and straightforward.

How to search a specific value in all tables (PostgreSQL)?

to search every column of every table for a particular value

This does not define how to match exactly.
Nor does it define what to return exactly.

Assuming:

  • Find any row with any column containing the given value in its text representation - as opposed to equaling the given value.
  • Return the table name (regclass) and the tuple ID (ctid), because that's simplest.

Here is a dead simple, fast and slightly dirty way:

CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
  RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
   FOR _tbl IN
      SELECT c.oid::regclass
      FROM   pg_class c
      JOIN   pg_namespace n ON n.oid = relnamespace
      WHERE  c.relkind = 'r'                           -- only tables
      AND    n.nspname !~ '^(pg_|information_schema)'  -- exclude system schemas
      ORDER BY n.nspname, c.relname
   LOOP
      RETURN QUERY EXECUTE format(
         'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
       , _tbl, '%' || _like_pattern || '%')
      USING _tbl;
   END LOOP;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM search_whole_db('mypattern');

Provide the search pattern without enclosing %.

Why slightly dirty?

If separators and decorators for the row in text representation can be part of the search pattern, there can be false positives:

  • column separator: , by default
  • whole row is enclosed in parentheses:()
  • some values are enclosed in double quotes "
  • \ may be added as escape char

And the text representation of some columns may depend on local settings - but that ambiguity is inherent to the question, not to my solution.

Each qualifying row is returned once only, even when it matches multiple times (as opposed to other answers here).

This searches the whole DB except for system catalogs. Will typically take a long time to finish. You might want to restrict to certain schemas / tables (or even columns) like demonstrated in other answers. Or add notices and a progress indicator, also demonstrated in another answer.

The regclass object identifier type is represented as table name, schema-qualified where necessary to disambiguate according to the current search_path:

What is the ctid?

You might want to escape characters with special meaning in the search pattern. See:

Ranges of floating point datatype in C?

These numbers come from the IEEE-754 standard, which defines the standard representation of floating point numbers. Wikipedia article at the link explains how to arrive at these ranges knowing the number of bits used for the signs, mantissa, and the exponent.

Running an Excel macro via Python?

A variation on SMNALLY's code that doesn't quit Excel if you already have it open:

import os, os.path
import win32com.client
    
if os.path.exists("excelsheet.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1) #create a workbook object
    xl.Application.Run("excelsheet.xlsm!modulename.macroname")
    wb.Close(False) #close the work sheet object rather than quitting excel
    del wb
    del xl

Open multiple Eclipse workspaces on the Mac

A more convenient way:

  1. Create an executable script as mentioned above:

    #!/bin/sh

    cd /Applications/Adobe\ Flash\ Builder\ 4.6

    open -n Adobe\ Flash\ Builder\ 4.6.app

  2. In you current instance of Flashbuilder or Eclipse, add a new external tool configuration. This is the button next to the debug/run/profile buttons on your toolbar. In that dialog, click on "Program" and add a new one. Give it the name you want and in the "Location" field, put the path to the script from step 1:

    /Users/username/bin/flashbuilder

  3. You can stop at step 2, but I prefer adding a custom icon to the toolbar. I use a the Quick Launch plugin to do that:

    http://sourceforge.net/projects/quicklaunch/files/

  4. After adding the plugin, go to "Run"->"Organize Quick Lauches" and add the external tool config from step 2. Then you can configure the icon for it.

  5. After you save that, you'll see the icon in your toolbar. Now you can just click it every time you want a new Flashbuilder/Eclipse instance.

How to check the Angular version?

  1. ng v
  2. ng --v

you shall see something like the following:

Angular CLI: 7.3.8
Node: 10.15.1
OS: win32 x64
Angular: 5.2.10
... animations, common, compiler, core, forms, http
... platform-browser, platform-browser-dynamic, router

Angular version is in line 4 above

Sql Server : How to use an aggregate function like MAX in a WHERE clause

The correct way to use max in the having clause is by performing a self join first:

select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
  on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)

The following is how you would join with a subquery:

select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
                 from table1 t1_max
                 where t1.id = t1_max.id)

Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
join #dataset d_max
  on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c

Sub query version:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
                from #dataset d_max
                where d.id = d_max.id)

Are HTTPS URLs encrypted?

A third-party that is monitoring traffic may also be able to determine the page visited by examining your traffic an comparing it with the traffic another user has when visiting the site. For example if there were 2 pages only on a site, one much larger than the other, then comparison of the size of the data transfer would tell which page you visited. There are ways this could be hidden from the third-party but they're not normal server or browser behaviour. See for example this paper from SciRate, https://scirate.com/arxiv/1403.0297.

In general other answers are correct, practically though this paper shows that pages visited (ie URL) can be determined quite effectively.

ActionController::InvalidAuthenticityToken

I had this issue with javascript calls. I fixed that with just requiring jquery_ujs into application.js file.

iOS application: how to clear notifications?

It might also make sense to add a call to clearNotifications in applicationDidBecomeActive so that in case the application is in the background and comes back it will also clear the notifications.

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [self clearNotifications];
}

Meaning of Choreographer messages in Logcat

I'm late to the party, but hopefully this is a useful addition to the other answers here...

Answering the Question / tl:dr;

I need to know how I can determine what "too much work" my application may be doing as all my processing is done in AsyncTasks.

The following are all candidates:

  • IO or expensive processing on the main thread (loading drawables, inflating layouts, and setting Uri's on ImageView's all constitute IO on the main thread)
  • Rendering large/complex/deep View hierarchies
  • Invalidating large portions of a View hierarchy
  • Expensive onDraw methods in custom View's
  • Expensive calculations in animations
  • Running "worker" threads at too high a priority to be considered "background" (AsyncTask's are "background" by default, java.lang.Thread is not)
  • Generating lots of garbage, causing the garbage collector to "stop the world" - including the main thread - while it cleans up

To actually determine the specific cause you'll need to profile your app.

More Detail

I've been trying to understand Choreographer by experimenting and looking at the code.

The documentation of Choreographer opens with "Coordinates the timing of animations, input and drawing." which is actually a good description, but the rest goes on to over-emphasize animations.

The Choreographer is actually responsible for executing 3 types of callbacks, which run in this order:

  1. input-handling callbacks (handling user-input such as touch events)
  2. animation callbacks for tweening between frames, supplying a stable frame-start-time to any/all animations that are running. Running these callbacks 2nd means any animation-related calculations (e.g. changing positions of View's) have already been made by the time the third type of callback is invoked...
  3. view traversal callbacks for drawing the view hierarchy.

The aim is to match the rate at which invalidated views are re-drawn (and animations tweened) with the screen vsync - typically 60fps.

The warning about skipped frames looks like an afterthought: The message is logged if a single pass through the 3 steps takes more than 30x the expected frame duration, so the smallest number you can expect to see in the log messages is "skipped 30 frames"; If each pass takes 50% longer than it should you will still skip 30 frames (naughty!) but you won't be warned about it.

From the 3 steps involved its clear that it isn't only animations that can trigger the warning: Invalidating a significant portion of a large View hierarchy or a View with a complicated onDraw method might be enough.

For example this will trigger the warning repeatedly:

public class AnnoyTheChoreographerActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.simple_linear_layout);

        ViewGroup root = (ViewGroup) findViewById(R.id.root);

        root.addView(new TextView(this){
            @Override
            protected void onDraw(Canvas canvas) {
                super.onDraw(canvas);
                long sleep = (long)(Math.random() * 1000L);
                setText("" + sleep);
                try {
                    Thread.sleep(sleep);
                } catch (Exception exc) {}
            }
        });
    }
}

... which produces logging like this:

11-06 09:35:15.865  13721-13721/example I/Choreographer? Skipped 42 frames!  The application may be doing too much work on its main thread.
11-06 09:35:17.395  13721-13721/example I/Choreographer? Skipped 59 frames!  The application may be doing too much work on its main thread.
11-06 09:35:18.030  13721-13721/example I/Choreographer? Skipped 37 frames!  The application may be doing too much work on its main thread.

You can see from the stack during onDraw that the choreographer is involved regardless of whether you are animating:

at example.AnnoyTheChoreographerActivity$1.onDraw(AnnoyTheChoreographerActivity.java:25) at android.view.View.draw(View.java:13759)

... quite a bit of repetition ...

at android.view.ViewGroup.drawChild(ViewGroup.java:3169) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3039) at android.view.View.draw(View.java:13762) at android.widget.FrameLayout.draw(FrameLayout.java:467) at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2396) at android.view.View.getDisplayList(View.java:12710) at android.view.View.getDisplayList(View.java:12754) at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1144) at android.view.ViewRootImpl.draw(ViewRootImpl.java:2273) at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2145) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1956) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1112) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4472) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) at android.view.Choreographer.doCallbacks(Choreographer.java:555) at android.view.Choreographer.doFrame(Choreographer.java:525) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898)

Finally, if there is contention from other threads that reduce the amount of work the main thread can get done, the chance of skipping frames increases dramatically even though you aren't actually doing the work on the main thread.

In this situation it might be considered misleading to suggest that the app is doing too much on the main thread, but Android really wants worker threads to run at low priority so that they are prevented from starving the main thread. If your worker threads are low priority the only way to trigger the Choreographer warning really is to do too much on the main thread.

How to check edittext's text is email address or not?

   I Hope this code is beneficial for you

    public class Register extends Activity 
      {
       EditText FirstName, PhoneNo, EmailId,weight;
       Button Register;
       private static final Pattern EMAIL_PATTERN = Pattern
        .compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");


   private static final Pattern USERFIRSTNAME_PATTERN = Pattern
        .compile("[a-zA-Z0-9]{1,250}");
   private static final Pattern PHONE_PATTERN = Pattern
        .compile("[a-zA-Z0-9]{1,250}");
       @Override
   public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);


        Register=(Button) findViewById(R.id.register);

        FirstName=(EditText)findViewById(R.id.person_firstname);

            PhoneNo =(EditText)findViewById(R.id.phone_no);
            EmailId=(EditText)findViewById(R.id.email_id);
            weight=(EditText) findViewById(R.id.weight);

         Register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                sFirstName= FirstName.getText().toString();
                 sPhoneNo= PhoneNo.getText().toString();
                sEmailId= EmailId.getText().toString();
                sweight= weight.getText().toString(); 

                if(sFirstName.equals("")||sPhoneNo.equals("")||sEmailId.equals("")||sweight.equals(""))
                {
                    if ((!CheckUsername(sFirstName))) 
                     {
                     Toast.makeText(Register.this, "FirstName can not be null",Toast.LENGTH_LONG).show();
                     }
                   else if ((!Checkphoneno(sPhoneNo)))
                       {
                    Toast.makeText(Register.this, "ENTER VALID mobile no ",Toast.LENGTH_LONG).show();
                       }
                    else if ((!CheckEmail(sEmailId)))
                       {
                      Toast.makeText(Register.this, "ENTER VALID EMAIL ID",Toast.LENGTH_LONG).show();
                       }
                    else if ((!Checkweight(sweight)))
                      {
                    Toast.makeText(Register.this, "ENTER Weight in kg",Toast.LENGTH_LONG).show();
                      }
               }

            }
                private boolean CheckEmail(String sEmailId) {

                    return EMAIL_PATTERN.matcher(sEmailId).matches();
                }



                private boolean CheckUsername(String sFirstName) {

                    return USERFIRSTNAME_PATTERN.matcher(sFirstName).matches();
                }
                private boolean Checkphoneno(String sPhoneNo) {

                    return PHONE_PATTERN.matcher(sPhoneNo).matches();
                }
                private boolean Checkweight(String sweight) {

                    return Weight_PATTERN.matcher(sweight).matches();
                }


        });

500.21 Bad module "ManagedPipelineHandler" in its module list

For me, I was getting this error message when using PUT or DELETE to WebAPI. I also tried re-registering .NET Framework as suggested but to no avail.

I was able to fix this by disabling WebDAV for my individual application pool, this stopped the 'bad module' error when using PUT or DELETE.

Disable WebDAV for Individual App Pool:

  1. Click the affected application pool
  2. Find WebDAV Authoring Tools in the list
  3. Click to open it
  4. Click Disable WebDAV in the top right.

This link is where I found the instructions but it's not very clear.

How to force Laravel Project to use HTTPS for all routes?

Here are several ways. Choose most convenient.

  1. Configure your web server to redirect all non-secure requests to https. Example of a nginx config:

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name example.com www.example.com;
        return 301 https://example.com$request_uri;
    }
    
  2. Set your environment variable APP_URL using https:

    APP_URL=https://example.com
    
  3. Use helper secure_url() (Laravel5.6)

  4. Add following string to AppServiceProvider::boot() method (for version 5.4+):

    \Illuminate\Support\Facades\URL::forceScheme('https');
    

Update:

  1. Implicitly setting scheme for route group (Laravel5.6):

    Route::group(['scheme' => 'https'], function () {
        // Route::get(...)->name(...);
    });
    

Excel: last character/string match in a string

I'm a little late to the party, but maybe this could help. The link in the question had a similar formula, but mine uses the IF() statement to get rid of errors.

If you're not afraid of Ctrl+Shift+Enter, you can do pretty well with an array formula.

String (in cell A1): "one.two.three.four"

Formula:

{=MAX(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)))}  use Ctrl+Shift+Enter

Result: 14

First,

ROW($1:$99)

returns an array of integers from 1 to 99: {1,2,3,4,...,98,99}.

Next,

MID(A1,ROW($1:$99),1)

returns an array of 1-length strings found in the target string, then returns blank strings after the length of the target string is reached: {"o","n","e",".",..."u","r","","",""...}

Next,

IF(MID(I16,ROW($1:$99),1)=".",ROW($1:$99))

compares each item in the array to the string "." and returns either the index of the character in the string or FALSE: {FALSE,FALSE,FALSE,4,FALSE,FALSE,FALSE,8,FALSE,FALSE,FALSE,FALSE,FALSE,14,FALSE,FALSE.....}

Last,

=MAX(IF(MID(I16,ROW($1:$99),1)=".",ROW($1:$99)))

returns the maximum value of the array: 14

Advantages of this formula is that it is short, relatively easy to understand, and doesn't require any unique characters.

Disadvantages are the required use of Ctrl+Shift+Enter and the limitation on string length. This can be worked around with a variation shown below, but that variation uses the OFFSET() function which is a volatile (read: slow) function.

Not sure what the speed of this formula is vs. others.

Variations:

=MAX((MID(A1,ROW(OFFSET($A$1,,,LEN(A1))),1)=".")*ROW(OFFSET($A$1,,,LEN(A1)))) works the same way, but you don't have to worry about the length of the string

=SMALL(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)),2) determines the 2nd occurrence of the match

=LARGE(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)),2) determines the 2nd-to-last occurrence of the match

=MAX(IF(MID(I16,ROW($1:$99),2)=".t",ROW($1:$99))) matches a 2-character string **Make sure you change the last argument of the MID() function to the number of characters in the string you wish to match!

How to increase the execution timeout in php?

optional : if you set config about php.ini but still can't upload

-this is php function to check error code

$error_type = [];
$error_type[0] = "There is no error";
$error_type[1] = "The uploaded file exceeds the upload_max_filesize directive in php.ini.";
$error_type[2] = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
$error_type[3] = "The uploaded file was only partially uploaded.";
$error_type[4] = "No file was uploaded.";
//$error_type["5"] = "";
$error_type[6] = "Missing a temporary folder. Introduced in PHP 5.0.3.";
$error_type[7] = "Failed to write file to disk. Introduced in PHP 5.1.0.";
$error_type[8] = "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.";
//------------------------------
//--> show msg error.
$status_code = $_FILES["uploadfile"]["error"];
if($status_code != 0){
    echo $error_type[$status_code];
    exit;
}

How to start a Process as administrator mode in C#

You probably need to set your application as an x64 app.

The IIS Snap In only works in 64 bit and doesn't work in 32 bit, and a process spawned from a 32 bit app seems to work to be a 32 bit process and the same goes for 64 bit apps.

Look at: Start process as 64 bit

Take nth column in a text file

iirc :

cat filename.txt | awk '{ print $2 $4 }'

or, as mentioned in the comments :

awk '{ print $2 $4 }' filename.txt

How to do HTTP authentication in android?

For me, it worked,

final String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);

Apache HttpCLient:

request.setHeader("Authorization", basicAuth);

HttpUrlConnection:

connection.setRequestProperty ("Authorization", basicAuth);

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

How to ignore whitespace in a regular expression subject string?

You could put \s* inbetween every character in your search string so if you were looking for cat you would use c\s*a\s*t\s*s\s*s

It's long but you could build the string dynamically of course.

You can see it working here: http://www.rubular.com/r/zzWwvppSpE

Escape single quote character for use in an SQLite query

Just in case if you have a loop or a json string that need to insert in the database. Try to replace the string with a single quote . here is my solution. example if you have a string that contain's a single quote.

String mystring = "Sample's";
String myfinalstring = mystring.replace("'","''");

 String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";

this works for me in c# and java

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

Adding subscribers to a list using Mailchimp's API v3

I got it working. I was adding the authentication to the header incorrectly:

$apikey = '<api_key>';
            $auth = base64_encode( 'user:'.$apikey );

            $data = array(
                'apikey'        => $apikey,
                'email_address' => $email,
                'status'        => 'subscribed',
                'merge_fields'  => array(
                    'FNAME' => $name
                )
            );
            $json_data = json_encode($data);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                                                        'Authorization: Basic '.$auth));
            curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);                                                                                                                  

            $result = curl_exec($ch);

            var_dump($result);
            die('Mailchimp executed');

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

Limit on the WHERE col IN (...) condition

For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.

select * from user where userId in (1,2,3,etc)

Should I use 'has_key()' or 'in' on Python dicts?

If you have something like this:

t.has_key(ew)

change it to below for running on Python 3.X and above:

key = ew
if key not in t

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

Here is some weak adobe documentation on different flash 9 wmode settings.

A note of caution on wmode transparent is here in the adobe bug trac.

And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.

JavaScript: replace last occurrence of text in a string

Not as elegant as the regex answers above, but easier to follow for the not-as-savvy among us:

function removeLastInstance(badtext, str) {
    var charpos = str.lastIndexOf(badtext);
    if (charpos<0) return str;
    ptone = str.substring(0,charpos);
    pttwo = str.substring(charpos+(badtext.length));
    return (ptone+pttwo);
}

I realize this is likely slower and more wasteful than the regex examples, but I think it might be helpful as an illustration of how string manipulations can be done. (It can also be condensed a bit, but again, I wanted each step to be clear.)

Drop shadow for PNG image in CSS

A trick I often use when I just need "a little" shadow (read: contour must not be super-precise) is placing a DIV with a radial fill 100%-black-to-100%-transparent under the image. The CSS for the DIV looks something like:

.shadow320x320{    
        background: -moz-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%, rgba(0,0,0,0.58) 1%, rgba(0,0,0,0) 43%, rgba(0,0,0,0) 100%); /* FF3.6+ */
        background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,rgba(0,0,0,0.58)), color-stop(1%,rgba(0,0,0,0.58)), color-stop(43%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0))); /* Chrome,Safari4+ */
        background: -webkit-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* Chrome10+,Safari5.1+ */
        background: -o-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* Opera 12+ */
        background: -ms-radial-gradient(center, ellipse cover, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* IE10+ */
        background: radial-gradient(ellipse at center, rgba(0,0,0,0.58) 0%,rgba(0,0,0,0.58) 1%,rgba(0,0,0,0) 43%,rgba(0,0,0,0) 100%); /* W3C */
        filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#94000000', endColorstr='#00000000',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
  }

This will create a circular black faded-out 'dot' on a 320x320 DIV. If you scale the height or width of the DIV you get a corresponding oval. Very nice to create eg shadows under bottles or other cylinder-like shapes.

There is an absolute incredible, super-excellent tool to create CSS gradients here:

http://www.colorzilla.com/gradient-editor/

ps: Do a courtesy ad-click when you use it. (And, no,I'm not affiliated with it. But courtesy clicking should become a bit of a habit, especially for tool you use often... just sayin... since we're all working on the net...)

How to increase scrollback buffer size in tmux?

This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.

tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000

This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.

I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:

#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is available only on IE browser. So every other useragent will throw an error

On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

You may also get this error if you have a name clash of a view and a module. I've got the error when i distribute my view files under views folder, /views/view1.py, /views/view2.py and imported some model named table.py in view2.py which happened to be a name of a view in view1.py. So naming the view functions as v_table(request,id) helped.

Convert multidimensional array into single array

You can do it just using a loop.

    $singleArray = array();

    foreach ($multiDimensionalArray as $key => $value){
        $singleArray[$key] = $value['plan'];
    }

QLabel: set color of text and background

The ONLY thing that worked for me was html.

And I found it to be the far easier to do than any of the programmatic approaches.

The following code changes the text color based on a parameter passed by a caller.

enum {msg_info, msg_notify, msg_alert};
:
:
void bits::sendMessage(QString& line, int level)
{
    QTextCursor cursor = ui->messages->textCursor();
    QString alertHtml  = "<font color=\"DeepPink\">";
    QString notifyHtml = "<font color=\"Lime\">";
    QString infoHtml   = "<font color=\"Aqua\">";
    QString endHtml    = "</font><br>";

    switch(level)
    {
        case msg_alert:  line = alertHtml % line; break;
        case msg_notify: line = notifyHtml % line; break;
        case msg_info:   line = infoHtml % line; break;
        default:         line = infoHtml % line; break;
    }

    line = line % endHtml;
    ui->messages->insertHtml(line);
    cursor.movePosition(QTextCursor::End);
    ui->messages->setTextCursor(cursor);
}

Passing variable number of arguments around

Though you can solve passing the formatter by storing it in local buffer first, but that needs stack and can sometime be issue to deal with. I tried following and it seems to work fine.

#include <stdarg.h>
#include <stdio.h>

void print(char const* fmt, ...)
{
    va_list arg;
    va_start(arg, fmt);
    vprintf(fmt, arg);
    va_end(arg);
}

void printFormatted(char const* fmt, va_list arg)
{
    vprintf(fmt, arg);
}

void showLog(int mdl, char const* type, ...)
{
    print("\nMDL: %d, TYPE: %s", mdl, type);

    va_list arg;
    va_start(arg, type);
    char const* fmt = va_arg(arg, char const*);
    printFormatted(fmt, arg);
    va_end(arg);
}

int main() 
{
    int x = 3, y = 6;
    showLog(1, "INF, ", "Value = %d, %d Looks Good! %s", x, y, "Infact Awesome!!");
    showLog(1, "ERR");
}

Hope this helps.

CSS display:table-row does not expand when width is set to 100%

If you're using display:table-row etc., then you need proper markup, which includes a containing table. Without it your original question basically provides the equivalent bad markup of:

<tr style="width:100%">
    <td>Type</td>
    <td style="float:right">Name</td>
</tr>

Where's the table in the above? You can't just have a row out of nowhere (tr must be contained in either table, thead, tbody, etc.)

Instead, add an outer element with display:table, put the 100% width on the containing element. The two inside cells will automatically go 50/50 and align the text right on the second cell. Forget floats with table elements. It'll cause so many headaches.

markup:

<div class="view-table">
    <div class="view-row">
        <div class="view-type">Type</div>
        <div class="view-name">Name</div>                
    </div>
</div>

CSS:

.view-table
{
    display:table;
    width:100%;
}
.view-row,
{
    display:table-row;
}
.view-row > div
{
    display: table-cell;
}
.view-name 
{
    text-align:right;
}

Set cURL to use local virtual hosts

Either use a real fully qualified domain name (like dev.yourdomain.com) that pointing to 127.0.0.1 or try editing the proper hosts file (usually /etc/hosts in *nix environments).

Compare DATETIME and DATE ignoring time portion

A small drawback in Marc's answer is that both datefields have been typecast, meaning you'll be unable to leverage any indexes.

So, if there is a need to write a query that can benefit from an index on a date field, then the following (rather convoluted) approach is necessary.

  • The indexed datefield (call it DF1) must be untouched by any kind of function.
  • So you have to compare DF1 to the full range of datetime values for the day of DF2.
  • That is from the date-part of DF2, to the date-part of the day after DF2.
  • I.e. (DF1 >= CAST(DF2 AS DATE)) AND (DF1 < DATEADD(dd, 1, CAST(DF2 AS DATE)))
  • NOTE: It is very important that the comparison is >= (equality allowed) to the date of DF2, and (strictly) < the day after DF2. Also the BETWEEN operator doesn't work because it permits equality on both sides.

PS: Another means of extracting the date only (in older versions of SQL Server) is to use a trick of how the date is represented internally.

  • Cast the date as a float.
  • Truncate the fractional part
  • Cast the value back to a datetime
  • I.e. CAST(FLOOR(CAST(DF2 AS FLOAT)) AS DATETIME)

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

Calling another different view from the controller using ASP.NET MVC 4

You can directly return a different view like:

return View("NameOfView", Model);

Or you can make a partial view and can return like:

return PartialView("PartialViewName", Model);

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

Stop UIWebView from "bouncing" vertically?

I was annoyed to find out that UIWebView is not a scroll view, so I made a custom subclass to get at the web view's scroll view. This suclass contains a scroll view so you can customize the behavior of your web view. The punchlines of this class are:

@class CustomWebView : UIWebview
...

- (id) initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
// WebViews are subclass of NSObject and not UIScrollView and therefore don't allow customization.
// However, a UIWebView is a UIScrollViewDelegate, so it must CONTAIN a ScrollView somewhere.
// To use a web view like a scroll view, let's traverse the view hierarchy to find the scroll view inside the web view.
for (UIView* v in self.subviews){
    if ([v isKindOfClass:[UIScrollView class]]){
        _scrollView = (UIScrollView*)v; 
        break;
    }
}
return self;

}

Then, when you create a custom web view, you can disable bouncing with:

customWebView.scrollView.bounces = NO; //(or customWebView.scrollView.alwaysBounceVertically = NO)

This is a great general purpose way to make a web view with customizable scrolling behavior. There are just a few things to watch out for:

  • as with any view, you'll also need to override -(id)initWithCoder: if you use it in Interface Builder
  • when you initially create a web view, its content size is always the same as the size of the view's frame. After you scroll the web, the content size represents the size of the actual web contents inside the view. To get around this, I did something hacky - calling -setContentOffset:CGPointMake(0,1)animated:YES to force an unnoticeable change that will set the proper content size of the web view.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

On Linux Machine, save the bash script and execute it. If you want to free port 8080, Input 8080 when prompted

echo "Enter port number to be closed :: "
read port
sudo kill $(sudo lsof -t -i:$port)

Postgresql 9.2 pg_dump version mismatch

For me the issue was updating psql apt-get wasn't resolving newer versions, even after update. The following worked.

Ubuntu

Start with the import of the GPG key for PostgreSQL packages.

sudo apt-get install wget ca-certificates
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

Now add the repository to your system.

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" >> /etc/apt/sources.list.d/pgdg.list'

Install PostgreSQL on Ubuntu

sudo apt-get update
sudo apt-get install postgresql postgresql-contrib

https://www.postgresql.org/download/linux/ubuntu/

Combining (concatenating) date and time into a datetime

drop table test

create table test(
    CollectionDate date NULL,
    CollectionTime  [time](0) NULL,
    CollectionDateTime as (isnull(convert(datetime,CollectionDate)+convert(datetime,CollectionTime),CollectionDate))
-- if CollectionDate is datetime no need to convert it above
)

insert test (CollectionDate, CollectionTime)
values ('2013-12-10', '22:51:19.227'),
       ('2013-12-10', null),
       (null, '22:51:19.227')

select * from test

CollectionDate  CollectionTime  CollectionDateTime
2013-12-10      22:51:19        2013-12-10 22:51:19.000
2013-12-10      NULL            2013-12-10 00:00:00.000
NULL            22:51:19        NULL

JavaScript string with new line - but not using \n

you can use the following function:

  function nl2br (str, is_xhtml) {
     var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
     return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
  } 

like so:

var mystr="line\nanother line\nanother line";
mystr=nl2br(mystr);
alert(mystr);

this should alert line<br>another line<br>another line

the source of the function is from here: http://phpjs.org/functions/nl2br:480

this imitates the nl2br function in php...

Simple two column html layout without using tables

a few small changes to make it responsive

<style type="text/css">
#wrap {
    width: 100%;
    margin: 0 auto;
    display: table;
}
#left_col {
   float:left;
   width:50%;
}
#right_col {
   float:right;
   width:50%;
}
@media only screen and (max-width: 480px){
    #left_col {
       width:100%;
    }
    #right_col {
       width:100%;
    }
}
</style>

<div id="wrap">
    <div id="left_col">
        ...
    </div>
    <div id="right_col">
        ...
    </div>
</div>

How to open every file in a folder

import pyautogui
import keyboard
import time
import os
import pyperclip

os.chdir("target directory")

# get the current directory
cwd=os.getcwd()

files=[]

for i in os.walk(cwd):
    for j in i[2]:
        files.append(os.path.abspath(j))

os.startfile("C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe")
time.sleep(1)


for i in files:
    print(i)
    pyperclip.copy(i)
    keyboard.press('ctrl')
    keyboard.press_and_release('o')
    keyboard.release('ctrl')
    time.sleep(1)

    keyboard.press('ctrl')
    keyboard.press_and_release('v')
    keyboard.release('ctrl')
    time.sleep(1)
    keyboard.press_and_release('enter')
    keyboard.press('ctrl')
    keyboard.press_and_release('p')
    keyboard.release('ctrl')
    keyboard.press_and_release('enter')
    time.sleep(3)
    keyboard.press('ctrl')
    keyboard.press_and_release('w')
    keyboard.release('ctrl')
    pyperclip.copy('')

loading json data from local file into React JS

If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.

Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: How to open a local disk file with Javascript?

I will include a slightly modified version for using it in React:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
    this.handleFileSelect = this.handleFileSelect.bind(this);
  }

  displayData(content) {
    this.setState({data: content});
  }

  handleFileSelect(evt) {
    let files = evt.target.files;
    if (!files.length) {
      alert('No file select');
      return;
    }
    let file = files[0];
    let that = this;
    let reader = new FileReader();
    reader.onload = function(e) {
      that.displayData(e.target.result);
    };
    reader.readAsText(file);
  }

  render() {
    const data = this.state.data;
    return (
      <div>
        <input type="file" onChange={this.handleFileSelect}/>
        { data && <p> {data} </p> }
      </div>
    );
  }
}

Has anyone gotten HTML emails working with Twitter Bootstrap?

Hi Brian Armstrong, visit this link.

This blog tells you how to integrate Rails with Bootstrap less (using premailer-rails).

If you're using bootstrap sass, you could do the same:

start by importing some Bootstrap sass files into email.css.scss

@import "bootstrap-sprockets";
@import "bootstrap/variables";
@import "bootstrap/mixins";
@import "bootstrap/scaffolding";
@import "bootstrap/type";
@import "bootstrap/buttons";
@import "bootstrap/alerts";
@import 'bootstrap/normalize';
@import 'bootstrap/tables';
@import 'bootstrap/progress-bars';

and then in your view <head> section add <%= stylesheet_link_tag "email" %>

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

This is Chrome's hint to tell you that if you type $0 on the console, it will be equivalent to that specific element.

Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.

Here are some of its applications:

  • Accessing DOM elements from console: $0
  • Accessing their properties from console: $0.parentElement
  • Updating their properties from console: $1.classList.add(...)
  • Updating CSS elements from console: $0.styles.backgroundColor="aqua"
  • Triggering CSS events from console: $0.click()
  • And doing a lot more complex stuffs, like: $0.appendChild(document.createElement("div"))

Watch all of this in action:

enter image description here

Backing statement:

Yes, I agree there are better ways to perform these actions, but this feature can come out handy in certain intricate scenarios, like when a DOM element needs to be clicked but it is not possible to do so from the UI because it is covered by other elements or, for some reason, is not visible on UI at that moment.

How to prevent form from submitting multiple times from client side?

The simpliest and elegant solution for me:

function checkForm(form) // Submit button clicked
{
    form.myButton.disabled = true;
    form.myButton.value = "Please wait...";
    return true;
}

<form method="POST" action="..." onsubmit="return checkForm(this);">
    ...
    <input type="submit" name="myButton" value="Submit">
</form>

Link for more...