Programs & Examples On #Ansi

ANSI stands for American National Standards Institute. Please do not use this tag, see the full tag wiki for alternatives.

What is ANSI format?

Once upon a time Microsoft, like everyone else, used 7-bit character sets, and they invented their own when it suited them, though they kept ASCII as a core subset. Then they realised the world had moved on to 8-bit encodings and that there were international standards around, such as the ISO-8859 family. In those days, if you wanted to get hold of an international standard and you lived in the US, you bought it from the American National Standards Institute, ANSI, who republished international standards with their own branding and numbers (that's because the US government wants conformance to American standards, not international standards). So Microsoft's copy of ISO-8859 said "ANSI" on the cover. And because Microsoft weren't very used to standards in those days, they didn't realise that ANSI published lots of other standards as well. So they referred to the standards in the ISO-8859 family (and the variants that they invented, because they didn't really understand standards in those days) by the name on the cover, "ANSI", and it found its way into Microsoft user documentation and hence into the user community. That was about 30 years ago, but you still sometimes hear the name today.

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

Rails 4 LIKE query - ActiveRecord adds quotes

Try

 def self.search(search, page = 1 )
    paginate :per_page => 5, :page => page,
      :conditions => ["name LIKE  ? OR postal_code like ?", "%#{search}%","%#{search}%"],   order => 'name'
  end

See the docs on AREL conditions for more info.

Finding Key associated with max Value in a Java Map

Java 8 way to get all keys with max value.

Integer max = PROVIDED_MAP.entrySet()
            .stream()
            .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1)
            .get()
            .getValue();

List listOfMax = PROVIDED_MAP.entrySet()
            .stream()
            .filter(entry -> entry.getValue() == max)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

System.out.println(listOfMax);

Also you can parallelize it by using parallelStream() instead of stream()

Laravel Eloquent Join vs Inner Join?

I'm sure there are other ways to accomplish this, but one solution would be to use join through the Query Builder.

If you have tables set up something like this:

users
    id
    ...

friends
    id
    user_id
    friend_id
    ...

votes, comments and status_updates (3 tables)
    id
    user_id
    ....

In your User model:

class User extends Eloquent {
    public function friends()
    {
        return $this->hasMany('Friend');
    }
}

In your Friend model:

class Friend extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:

$user = User::find(1);
$friends_votes = $user->friends()
    ->with('user') // bring along details of the friend
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id')
    ->get(['votes.*']); // exclude extra details from friends table

Run the same join for the comments and status_updates tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.


Edit

To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where instead:

$friends_votes = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id');

$friends_comments = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('comments', 'comments.user_id', '=', 'friends.friend_id');

$friends_status_updates = 
    DB::table('status_updates')->where('status_updates.user_id','1')
    ->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');

$friends_events = 
    $friends_votes
    ->union($friends_comments)
    ->union($friends_status_updates)
    ->get();

At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

How to remove border of drop down list : CSS

This solution seems not working for me.

select {
    border: 0px;
    outline: 0px;
}

But you may set select border to the background color of the container and it will work.

Difference between two DateTimes C#?

Are you perhaps looking for:

int Difference = (a-b).Hours;

Sending JWT token in the headers with Postman

For people who are using wordpress plugin Advanced Access Manager to open up the JWT Authentication.

The Header field should put Authentication instead of Authorization

enter image description here

AAM mentioned it inside their documentation,

Note! AAM does not use standard Authorization header as it is skipped by most Apache servers. ...


Hope it helps someone! Thanks for other answers helped me alot too!!

div inside table

It is allow as TD can contain inline- AND block-elements.

Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains

CSS :selected pseudo class similar to :checked, but for <select> elements

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

_x000D_
_x000D_
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
  background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Works on gecko/webkit.

Chrome extension id - how to find it

You get an extension ID when you upload your extension to Google Web Store. Ie. Adblock has URL https://chrome.google.com/webstore/detail/cfhdojbkjhnklbpkdaibdccddilifddb and the last part of this URL is its extension ID cfhdojbkjhnklbpkdaibdccddilifddb.


If you wish to read installed extension IDs from your extension, check out the managment module. chrome.management.getAll allows to fetch information about all installed extensions.

How to remove underline from a link in HTML?

This will remove all underlines from all links:

a {text-decoration: none; }

If you have specific links that you want to apply this to, give them a class name, like nounderline and do this:

a.nounderline {text-decoration: none; }

That will apply only to those links and leave all others unaffected.

This code belongs in the <head> of your document or in a stylesheet:

<head>
    <style type="text/css">
        a.nounderline {text-decoration: none; }
    </style>
</head>

And in the body:

<a href="#" class="nounderline">Link</a>

ggplot with 2 y axes on each side and different scales

Taking above answers and some fine-tuning (and for whatever it's worth), here is a way of achieving two scales via sec_axis:

Assume a simple (and purely fictional) data set dt: for five days, it tracks the number of interruptions VS productivity:

        when numinter prod
1 2018-03-20        1 0.95
2 2018-03-21        5 0.50
3 2018-03-23        4 0.70
4 2018-03-24        3 0.75
5 2018-03-25        4 0.60

(the ranges of both columns differ by about factor 5).

The following code will draw both series that they use up the whole y axis:

ggplot() + 
  geom_bar(mapping = aes(x = dt$when, y = dt$numinter), stat = "identity", fill = "grey") +
  geom_line(mapping = aes(x = dt$when, y = dt$prod*5), size = 2, color = "blue") + 
  scale_x_date(name = "Day", labels = NULL) +
  scale_y_continuous(name = "Interruptions/day", 
    sec.axis = sec_axis(~./5, name = "Productivity % of best", 
      labels = function(b) { paste0(round(b * 100, 0), "%")})) + 
  theme(
      axis.title.y = element_text(color = "grey"),
      axis.title.y.right = element_text(color = "blue"))

Here's the result (above code + some color tweaking):

two scales in one ggplot2

The point (aside from using sec_axis when specifying the y_scale is to multiply each value the 2nd data series with 5 when specifying the series. In order to get the labels right in the sec_axis definition, it then needs dividing by 5 (and formatting). So a crucial part in above code is really *5 in the geom_line and ~./5 in sec_axis (a formula dividing the current value . by 5).

In comparison (I don't want to judge the approaches here), this is how two charts on top of one another look like:

two charts above one another

You can judge for yourself which one better transports the message (“Don’t disrupt people at work!”). Guess that's a fair way to decide.

The full code for both images (it's not really more than what's above, just complete and ready to run) is here: https://gist.github.com/sebastianrothbucher/de847063f32fdff02c83b75f59c36a7d a more detailed explanation here: https://sebastianrothbucher.github.io/datascience/r/visualization/ggplot/2018/03/24/two-scales-ggplot-r.html

Print out the values of a (Mat) matrix in OpenCV C++

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) << src.at<double>(0,i) << endl;

    return 0;
}

LINQ Aggregate algorithm explained

It partly depends on which overload you're talking about, but the basic idea is:

  • Start with a seed as the "current value"
  • Iterate over the sequence. For each value in the sequence:
    • Apply a user-specified function to transform (currentValue, sequenceValue) into (nextValue)
    • Set currentValue = nextValue
  • Return the final currentValue

You may find the Aggregate post in my Edulinq series useful - it includes a more detailed description (including the various overloads) and implementations.

One simple example is using Aggregate as an alternative to Count:

// 0 is the seed, and for each item, we effectively increment the current value.
// In this case we can ignore "item" itself.
int count = sequence.Aggregate(0, (current, item) => current + 1);

Or perhaps summing all the lengths of strings in a sequence of strings:

int total = sequence.Aggregate(0, (current, item) => current + item.Length);

Personally I rarely find Aggregate useful - the "tailored" aggregation methods are usually good enough for me.

CSS Background Image Not Displaying

Make sure your body has a height, f.ex:

body { 
    background: url(/img/debut_dark.png) repeat;
    min-height: 100%;
}

How to include scripts located inside the node_modules folder?

As mentioned by jfriend00 you should not expose your server structure. You could copy your project dependency files to something like public/scripts. You can do this very easily with dep-linker like this:

var DepLinker = require('dep-linker');
DepLinker.copyDependenciesTo('./public/scripts')
// Done

How to change a package name in Eclipse?

  1. Change the Package Name in Manifest.
  2. A warning box will be said to change into workspace ,press "yes"
  3. then right click on src-> refactor -> rename paste your package name
  4. select package name and sub package name both

  5. press "save" a warning pop ups , press "continue"

name changed successfully

Pretty printing XML with javascript

here is another function to format xml

function formatXml(xml){
    var out = "";
    var tab = "    ";
    var indent = 0;
    var inClosingTag=false;
    var dent=function(no){
        out += "\n";
        for(var i=0; i < no; i++)
            out+=tab;
    }


    for (var i=0; i < xml.length; i++) {
        var c = xml.charAt(i);
        if(c=='<'){
            // handle </
            if(xml.charAt(i+1) == '/'){
                inClosingTag = true;
                dent(--indent);
            }
            out+=c;
        }else if(c=='>'){
            out+=c;
            // handle />
            if(xml.charAt(i-1) == '/'){
                out+="\n";
                //dent(--indent)
            }else{
              if(!inClosingTag)
                dent(++indent);
              else{
                out+="\n";
                inClosingTag=false;
              }
            }
        }else{
          out+=c;
        }
    }
    return out;
}

How to send a POST request with BODY in swift

Alamofire Fetch data with POST,Parameter and Headers

func feedbackApi(){
    DispatchQueue.main.async {
        let headers = [
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "------"
        ]
        let url = URL(string: "---------")
        var parameters = [String:AnyObject]()
        parameters =  [
            "device_id":"-----" as AnyObject,
            "user_id":"----" as AnyObject,
            "cinema_id":"-----" as AnyObject,
            "session_id":"-----" as AnyObject,
        ]
       Alamofire.request(url!, method: .post, parameters: parameters,headers:headers).responseJSON { response in
                switch response.result{
                case.success(let data):
                    self.myResponse = JSON(data)
                    print(self.myResponse as Any)
                    let slide = self.myResponse!["sliders"]
                    print(slide)
                    print(slide.count)
                    for i in 0..<slide.count{
                        let single = Sliders(sliderJson: slide[i])
                        self.slidersArray.append(single)
                    }
                    DispatchQueue.main.async {
                        self.getSliderCollection.reloadData()
                    }
                case .failure(let error):
                    print("dddd",error)
                }

        }
    }

}

How can I disable an <option> in a <select> based on its value in JavaScript?

You can also use this function,

function optionDisable(selectId, optionIndices)
{
    for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
    {
        document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
        document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
        document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
    }
}

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

Try this function : mltiple queries and multiple values insertion.

function employmentStatus($Status) {
$pdo = PDO2::getInstance();

$sql_parts = array(); 
for($i=0; $i<count($Status); $i++){
    $sql_parts[] = "(:userID, :val$i)";
}

$requete = $pdo->dbh->prepare("DELETE FROM employment_status WHERE userid = :userID; INSERT INTO employment_status (userid, status) VALUES ".implode(",", $sql_parts));
$requete->bindParam(":userID", $_SESSION['userID'],PDO::PARAM_INT);
for($i=0; $i<count($Status); $i++){
    $requete->bindParam(":val$i", $Status[$i],PDO::PARAM_STR);
}
if ($requete->execute()) {
    return true;
}
return $requete->errorInfo();
}

How do I split a string so I can access item x?

Almost all the other answers are replacing the string being split which wastes CPU cycles and performs unnecessary memory allocations.

I cover a much better way to do a string split here: http://www.digitalruby.com/split-string-sql-server/

Here is the code:

SET NOCOUNT ON

-- You will want to change nvarchar(MAX) to nvarchar(50), varchar(50) or whatever matches exactly with the string column you will be searching against
DECLARE @SplitStringTable TABLE (Value nvarchar(MAX) NOT NULL)
DECLARE @StringToSplit nvarchar(MAX) = 'your|string|to|split|here'
DECLARE @SplitEndPos int
DECLARE @SplitValue nvarchar(MAX)
DECLARE @SplitDelim nvarchar(1) = '|'
DECLARE @SplitStartPos int = 1

SET @SplitEndPos = CHARINDEX(@SplitDelim, @StringToSplit, @SplitStartPos)

WHILE @SplitEndPos > 0
BEGIN
    SET @SplitValue = SUBSTRING(@StringToSplit, @SplitStartPos, (@SplitEndPos - @SplitStartPos))
    INSERT @SplitStringTable (Value) VALUES (@SplitValue)
    SET @SplitStartPos = @SplitEndPos + 1
    SET @SplitEndPos = CHARINDEX(@SplitDelim, @StringToSplit, @SplitStartPos)
END

SET @SplitValue = SUBSTRING(@StringToSplit, @SplitStartPos, 2147483647)
INSERT @SplitStringTable (Value) VALUES(@SplitValue)

SET NOCOUNT OFF

-- You can select or join with the values in @SplitStringTable at this point.

Child inside parent with min-height: 100% not inheriting height

In addition to the existing answers, there is also viewport units vh to use. Simple snippet below. Of course it can be used together with calc() as well, e.g. min-height: calc(100vh - 200px); when page header and footer have 200px height together.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  min-height: 100vh;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Create GUI using Eclipse (Java)

Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here

REST API Login Pattern

TL;DR Login for each request is not a required component to implement API security, authentication is.

It is hard to answer your question about login without talking about security in general. With some authentication schemes, there's no traditional login.

REST does not dictate any security rules, but the most common implementation in practice is OAuth with 3-way authentication (as you've mentioned in your question). There is no log-in per se, at least not with each API request. With 3-way auth, you just use tokens.

  1. User approves API client and grants permission to make requests in the form of a long-lived token
  2. Api client obtains a short-lived token by using the long-lived one.
  3. Api client sends the short-lived token with each request.

This scheme gives the user the option to revoke access at any time. Practially all publicly available RESTful APIs I've seen use OAuth to implement this.

I just don't think you should frame your problem (and question) in terms of login, but rather think about securing the API in general.

For further info on authentication of REST APIs in general, you can look at the following resources:

Set start value for column with autoincrement

From Resetting SQL Server Identity Columns:

Retrieving the identity for the table Employees:

DBCC checkident ('Employees')

Repairing the identity seed (if for some reason the database is inserting duplicate identities):

DBCC checkident ('Employees', reseed)

Changing the identity seed for the table Employees to 1000:

DBCC checkident ('Employees', reseed, 1000)

The next row inserted will begin at 1001.

pandas: best way to select all columns whose names start with X

You can try the regex here to filter out the columns starting with "foo"

df.filter(regex='^foo*')

If you need to have the string foo in your column then

df.filter(regex='foo*')

would be appropriate.

For the next step, you can use

df[df.filter(regex='^foo*').values==1]

to filter out the rows where one of the values of 'foo*' column is 1.

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

This python script is awesome.

Here's my Ruby version of it (with minor improvement) and search capabilities. (for iOS 5)

# encoding: utf-8
require 'fileutils'
require 'digest/sha1'

class ManifestParser
  def initialize(mbdb_filename, verbose = false)
    @verbose = verbose
    process_mbdb_file(mbdb_filename)
  end

  # Returns the numbers of records in the Manifest files.
  def record_number
    @mbdb.size
  end

  # Returns a huge string containing the parsing of the Manifest files.
  def to_s
    s = ''
    @mbdb.each do |v|
      s += "#{fileinfo_str(v)}\n"
    end
    s
  end

  def to_file(filename)
    File.open(filename, 'w') do |f|
      @mbdb.each do |v|
        f.puts fileinfo_str(v)
      end
    end
  end

  # Copy the backup files to their real path/name.
  # * domain_match Can be a regexp to restrict the files to copy.
  # * filename_match Can be a regexp to restrict the files to copy.
  def rename_files(domain_match = nil, filename_match = nil)
    @mbdb.each do |v|
      if v[:type] == '-' # Only rename files.
        if (domain_match.nil? or v[:domain] =~ domain_match) and (filename_match.nil? or v[:filename] =~ filename_match)
          dst = "#{v[:domain]}/#{v[:filename]}"
          puts "Creating: #{dst}"
          FileUtils.mkdir_p(File.dirname(dst))
          FileUtils.cp(v[:fileID], dst)
        end
      end
    end
  end

  # Return the filename that math the given regexp.
  def search(regexp)
    result = Array.new
    @mbdb.each do |v|
      if "#{v[:domain]}::#{v[:filename]}" =~ regexp
        result << v
      end
    end
    result
  end

  private
  # Retrieve an integer (big-endian) and new offset from the current offset
  def getint(data, offset, intsize)
    value = 0
    while intsize > 0
      value = (value<<8) + data[offset].ord
      offset += 1
      intsize -= 1
    end
    return value, offset
  end

  # Retrieve a string and new offset from the current offset into the data
  def getstring(data, offset)
    return '', offset + 2 if data[offset] == 0xFF.chr and data[offset + 1] == 0xFF.chr # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset...(offset + length)]
    return value, (offset + length)
  end

  def process_mbdb_file(filename)
    @mbdb = Array.new
    data = File.open(filename, 'rb') { |f| f.read }
    puts "MBDB file read. Size: #{data.size}"
    raise 'This does not look like an MBDB file' if data[0...4] != 'mbdb'
    offset = 4
    offset += 2 # value x05 x00, not sure what this is
    while offset < data.size
      fileinfo = Hash.new
      fileinfo[:start_offset] = offset
      fileinfo[:domain], offset = getstring(data, offset)
      fileinfo[:filename], offset = getstring(data, offset)
      fileinfo[:linktarget], offset = getstring(data, offset)
      fileinfo[:datahash], offset = getstring(data, offset)
      fileinfo[:unknown1], offset = getstring(data, offset)
      fileinfo[:mode], offset = getint(data, offset, 2)
      if (fileinfo[:mode] & 0xE000) == 0xA000 # Symlink
        fileinfo[:type] = 'l'
      elsif (fileinfo[:mode] & 0xE000) == 0x8000 # File
        fileinfo[:type] = '-'
      elsif (fileinfo[:mode] & 0xE000) == 0x4000 # Dir
        fileinfo[:type] = 'd'
      else
        # $stderr.puts "Unknown file type %04x for #{fileinfo_str(f, false)}" % f['mode']
        fileinfo[:type] = '?'
      end
      fileinfo[:unknown2], offset = getint(data, offset, 4)
      fileinfo[:unknown3], offset = getint(data, offset, 4)
      fileinfo[:userid], offset = getint(data, offset, 4)
      fileinfo[:groupid], offset = getint(data, offset, 4)
      fileinfo[:mtime], offset = getint(data, offset, 4)
      fileinfo[:atime], offset = getint(data, offset, 4)
      fileinfo[:ctime], offset = getint(data, offset, 4)
      fileinfo[:filelen], offset = getint(data, offset, 8)
      fileinfo[:flag], offset = getint(data, offset, 1)
      fileinfo[:numprops], offset = getint(data, offset, 1)
      fileinfo[:properties] = Hash.new
      (0...(fileinfo[:numprops])).each do |ii|
        propname, offset = getstring(data, offset)
        propval, offset = getstring(data, offset)
        fileinfo[:properties][propname] = propval
      end
      # Compute the ID of the file.
      fullpath = fileinfo[:domain] + '-' + fileinfo[:filename]
      fileinfo[:fileID] = Digest::SHA1.hexdigest(fullpath)
      # We add the file to the list of files.
      @mbdb << fileinfo
    end
    @mbdb
  end

  def modestr(val)
    def mode(val)
      r = (val & 0x4) ? 'r' : '-'
      w = (val & 0x2) ? 'w' : '-'
      x = (val & 0x1) ? 'x' : '-'
      r + w + x
    end
    mode(val >> 6) + mode(val >> 3) + mode(val)
  end

  def fileinfo_str(f)
    return "(#{f[:fileID]})#{f[:domain]}::#{f[:filename]}" unless @verbose
    data = [f[:type], modestr(f[:mode]), f[:userid], f[:groupid], f[:filelen], f[:mtime], f[:atime], f[:ctime], f[:fileID], f[:domain], f[:filename]]
    info = "%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % data
    info += ' -> ' + f[:linktarget] if f[:type] == 'l' # Symlink destination
    f[:properties].each do |k, v|
      info += " #{k}=#{v.inspect}"
    end
    info
  end
end

if __FILE__ == $0
  mp = ManifestParser.new 'Manifest.mbdb', true
  mp.to_file 'filenames.txt'
end

Custom domain for GitHub project pages

If you are wondering how to get your domain to appear as www.mydomain.com instead of redirecting the www request to mydomain.com, try this:

CNAME file on gh-pages branch will have one line:

www.mydomain.com (instead of mydomain.com)

No matter your preference on redirection (in other words, no matter what is in your CNAME file on the gs-pages branch), with your DNS provider, you should set it up like this:

A      @    192.30.252.154
A      @    192.30.252.153
CNAME  www  username.github.io

List names of all tables in a SQL Server 2012 schema

SELECT t.name 
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = N'schema_name';

How to find the number of days between two dates

The DATEDIFF function is use to calculate the number of days between the required date

Example if you are diff current date from given date in string format

SELECT * , DATEDIFF(CURDATE(),STR_TO_DATE('01/11/2017', '%m/%d/%Y')) AS days FROM consignments WHERE code = '1610000154'

Here, STR_TO_DATE () : Take a string and returns a date specified by a format mask;

For your example :

SELECT dtCreated
    , bActive
    , dtLastPaymentAttempt
    , dtLastUpdated
    , dtLastVisit
    , DATEDIFF(dtLastUpdated, dtCreated) as Difference
FROM Customers
WHERE (bActive = 'true') 
    AND (dtLastUpdated > '2012-01-01 00:00:00')

Tested on mysql server 5.7.17

How do I sort strings alphabetically while accounting for value when a string is numeric?

public class NaturalSort: IComparer<string>
{
          [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
          public static extern int StrCmpLogicalW(string x, string y);

          public int Compare(string x, string y)
          {
                 return StrCmpLogicalW(x, y);
          }
}

arr = arr.OrderBy(x => x, new NaturalSort()).ToArray();

The reason I needed it was to get filed in a directory whose filenames started with a number:

public static FileInfo[] GetFiles(string path)
{
  return new DirectoryInfo(path).GetFiles()
                                .OrderBy(x => x.Name, new NaturalSort())
                                .ToArray();
}

How to append data to div using JavaScript?

Try this:

var div = document.getElementById('divID');

div.innerHTML += 'Extra stuff';

Python+OpenCV: cv2.imwrite

enter image description here enter image description here enter image description here

Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

1 Perform face detection(Input an image, output all boxes of detected faces):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

2 save all detected faces to separate files:

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3 or Draw rectangles of all detected faces:

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

How to round a numpy array?

It is worth noting that the accepted answer will round small floats down to zero.

>>> import numpy as np 
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03  4.82011728e-08  1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0.  ,  0.  ,  0.  ]) 

You can use set_printoptions and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:

>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]  

This way, you get the full versatility of format and maintain the full precision of numpy's datatypes.

Also note that this only affects printing, not the actual precision of the stored values used for computation.

How to add a line to a multiline TextBox?

@Casperah pointed out that i'm thinking about it wrong:

  • A TextBox doesn't have lines
  • it has text
  • that text can be split on the CRLF into lines, if requested
  • but there is no notion of lines

The question then is how to accomplish what i want, rather than what WinForms lets me.

There are subtle bugs in the other given variants:

  • textBox1.AppendText("Hello" + Environment.NewLine);
  • textBox1.AppendText("Hello" + "\r\n");
  • textBox1.Text += "Hello\r\n"
  • textbox1.Text += System.Environment.NewLine + "brown";

They either append or prepend a newline when one (might) not be required.

So, extension helper:

public static class WinFormsExtensions
{
   public static void AppendLine(this TextBox source, string value)
   {
      if (source.Text.Length==0)
         source.Text = value;
      else
         source.AppendText("\r\n"+value);
   }
}

So now:

textBox1.Clear();
textBox1.AppendLine("red");
textBox1.AppendLine("green");
textBox1.AppendLine("blue");

and

textBox1.AppendLine(String.Format("Processing file {0}", filename));

Note: Any code is released into the public domain. No attribution required.

Prevent any form of page refresh using jQuery/Javascript

#1 can be implemented via window.onbeforeunload.

For example:

<script type="text/javascript">
    window.onbeforeunload = function() {
        return "Dude, are you sure you want to leave? Think of the kittens!";
    }
</script>

The user will be prompted with the message, and given an option to stay on the page or continue on their way. This is becoming more common. Stack Overflow does this if you try to navigate away from a page while you are typing a post. You can't completely stop the user from reloading, but you can make it sound real scary if they do.

#2 is more or less impossible. Even if you tracked sessions and user logins, you still wouldn't be able to guarantee that you were detecting a second tab correctly. For example, maybe I have one window open, then close it. Now I open a new window. You would likely detect that as a second tab, even though I already closed the first one. Now your user can't access the first window because they closed it, and they can't access the second window because you're denying them.

In fact, my bank's online system tries real hard to do #2, and the situation described above happens all the time. I usually have to wait until the server-side session expires before I can use the banking system again.

qmake: could not find a Qt installation of ''

As Debian Qt's maintainer please allow me to suggest you to not use qtx-default. Please read qtchooser's man page, the solution is described there. If you are interested in packaging an app you can also take a look at this blog post I made explaining how to do it

# method 1
QT_SELECT=qt5 qmake

# method 2:
export QT_SELECT=qt5
qmake
... more qt commands here

# method 3:
make -qt5

To use Qt 4, just replace the qt5 with qt4

Update 20210202: starting from Debian 11 (bullseye) the packages qtx-default do not longer exist. Same goes for Ubuntu, but I don't know in which specific version. If you know of a package that still has the dependency (mostly non-Debian official packages) please file a bug. Same goes for Wiki pages, etc.

Byte[] to ASCII

Encoding.GetString Method (Byte[]) convert bytes to a string.

When overridden in a derived class, decodes all the bytes in the specified byte array into a string.

Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)

Syntax

public virtual string GetString(byte[] bytes)

Parameters

bytes
    Type: System.Byte[]
    The byte array containing the sequence of bytes to decode.

Return Value

Type: System.String
A String containing the results of decoding the specified sequence of bytes.

Exceptions

ArgumentException        - The byte array contains invalid Unicode code points.
ArgumentNullException    - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.

Remarks

If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.

See the Remarks under Encoding.GetChars for more discussion of decoding techniques and considerations.

Can someone explain the dollar sign in Javascript?

Here is a good short video explanation: https://www.youtube.com/watch?v=Acm-MD_6934

According to Ecma International Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on both normative and informative character categories specified by the Unicode Standard. The characters in the specified categories in version 3.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations.this standard specifies specific character additions:

The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

Further reading can be found on: http://www.ecma-international.org/ecma-262/5.1/#sec-7.6

Ecma International is an industry association founded in 1961 and dedicated to the standardization of Information and Communication Technology (ICT) and Consumer Electronics (CE).

Mysql database sync between two databases

Replication is not very hard to create.

Here's some good tutorials:

http://www.ghacks.net/2009/04/09/set-up-mysql-database-replication/

http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html

http://www.lassosoft.com/Beginners-Guide-to-MySQL-Replication

Here some simple rules you will have to keep in mind (there's more of course but that is the main concept):

  1. Setup 1 server (master) for writing data.
  2. Setup 1 or more servers (slaves) for reading data.

This way, you will avoid errors.

For example: If your script insert into the same tables on both master and slave, you will have duplicate primary key conflict.

You can view the "slave" as a "backup" server which hold the same information as the master but cannot add data directly, only follow what the master server instructions.

NOTE: Of course you can read from the master and you can write to the slave but make sure you don't write to the same tables (master to slave and slave to master).

I would recommend to monitor your servers to make sure everything is fine.

Let me know if you need additional help

How to move Docker containers between different hosts?

Use this script: https://github.com/ricardobranco777/docker-volumes.sh

This does preserve data in volumes.

Example usage:

# Stop the container   
docker stop $CONTAINER

# Create a new image   
docker commit $CONTAINER $CONTAINER

# Save image
docker save -o $CONTAINER.tar $CONTAINER

# Save the volumes (use ".tar.gz" if you want compression)
docker-volumes.sh $CONTAINER save $CONTAINER-volumes.tar

# Copy image and volumes to another host
scp $CONTAINER.tar $CONTAINER-volumes.tar $USER@$HOST:

# On the other host:
docker load -i $CONTAINER.tar
docker create --name $CONTAINER [<PREVIOUS CONTAINER OPTIONS>] $CONTAINER

# Load the volumes
docker-volumes.sh $CONTAINER load $CONTAINER-volumes.tar

# Start container
docker start $CONTAINER

Can we make unsigned byte in Java

I am trying to use this data as a parameter to a function of Java that accepts only a byte as parameter

This is not substantially different from a function accepting an integer to which you want to pass a value larger than 2^32-1.

That sounds like it depends on how the function is defined and documented; I can see three possibilities:

  1. It may explicitly document that the function treats the byte as an unsigned value, in which case the function probably should do what you expect but would seem to be implemented wrong. For the integer case, the function would probably declare the parameter as an unsigned integer, but that is not possible for the byte case.

  2. It may document that the value for this argument must be greater than (or perhaps equal to) zero, in which case you are misusing the function (passing an out-of-range parameter), expecting it to do more than it was designed to do. With some level of debugging support you might expect the function to throw an exception or fail an assertion.

  3. The documentation may say nothing, in which case a negative parameter is, well, a negative parameter and whether that has any meaning depends on what the function does. If this is meaningless then perhaps the function should really be defined/documented as (2). If this is meaningful in an nonobvious manner (e.g. non-negative values are used to index into an array, and negative values are used to index back from the end of the array so -1 means the last element) the documentation should say what it means and I would expect that it isn't what you want it to do anyway.

How to remove title bar from the android activity?

In your Android Manifest file make sure that the activity is using this (or a) theme (that is based on) @style/Theme.AppCompat.NoActionBar This removes the ActionBar completely, but won't make your activity fullscreen. If you want to make your activity fullscreen only use this theme

@android:style/Theme.NoTitleBar.Fullscreen

Or you could change

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

to

requestWindowFeature(Window.FEATURE_NO_TITLE);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

This is what I use to get fullscreen at runtime

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                mDecorView = getWindow().getDecorView();
                mDecorView.setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);
            }

To exit fullscreen I use this

mDecorView = getWindow().getDecorView();
mDecorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

Checking if a string array contains a value, and if so, getting its position

We can also use Exists:

string[] array = { "cat", "dog", "perl" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perl");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

How can I debug git/git-shell related problems?

Have you tried adding the verbose (-v) operator when you clone?

git clone -v git://git.kernel.org/pub/scm/.../linux-2.6 my2.6

MySQL: #126 - Incorrect key file for table

I got this error when I set ft_min_word_len = 2 in my.cnf, which lowers the minimum word length in a full text index to 2, from the default of 4.

Repairing the table fixed the problem.

How do I include a Perl module that's in a different directory?

Most likely the reason your push did not work is order of execution.

use is a compile time directive. You push is done at execution time:

push ( @INC,"directory_path/more_path");
use Foo.pm;  # In directory path/more_path

You can use a BEGIN block to get around this problem:

BEGIN {
    push ( @INC,"directory_path/more_path");
}
use Foo.pm;  # In directory path/more_path

IMO, it's clearest, and therefore best to use lib:

use lib "directory_path/more_path";
use Foo.pm;  # In directory path/more_path

See perlmod for information about BEGIN and other special blocks and when they execute.

Edit

For loading code relative to your script/library, I strongly endorse File::FindLib

You can say use File::FindLib 'my/test/libs'; to look for a library directory anywhere above your script in the path.

Say your work is structured like this:

   /home/me/projects/
    |- shared/
    |   |- bin/
    |   `- lib/
    `- ossum-thing/
       `- scripts 
           |- bin/
           `- lib/

Inside a script in ossum-thing/scripts/bin:

use File::FindLib 'lib/';
use File::FindLib 'shared/lib/';

Will find your library directories and add them to your @INC.

It's also useful to create a module that contains all the environment set-up needed to run your suite of tools and just load it in all the executables in your project.

use File::FindLib 'lib/MyEnvironment.pm'

Python - Passing a function into another function

Treat function as variable in your program so you can just pass them to other functions easily:

def test ():
   print "test was invoked"

def invoker(func):
   func()

invoker(test)  # prints test was invoked

What is the difference between .py and .pyc files?

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

jquery save json data object in cookie

You can serialize the data as JSON, like this:

$.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));

Then to get it from the cookie:

$("#ArticlesHolder").data(JSON.parse($.cookie("basket-data")));

This relies on JSON.stringify() and JSON.parse() to serialize/deserialize your data object, for older browsers (IE<8) include json2.js to get the JSON functionality. This example uses the jQuery cookie plugin

HTML form with multiple "actions"

this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!

_x000D_
_x000D_
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
_x000D_
_x000D_

shift a std_logic_vector of n bit to right or left

Personally, I think the concatenation is the better solution. The generic implementation would be

entity shifter is
    generic (
        REGSIZE  : integer := 8);
    port(
        clk      : in  str_logic;
        Data_in  : in  std_logic;
        Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;

architecture bhv of shifter is
    signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
    process (clk) begin
        if rising_edge(clk) then
            shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
        end if;
    end process;
end bhv;
Data_out <= shift_reg;

Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.

Setting user agent of a java URLConnection

its work for me set the User-Agent in the addRequestProperty.

URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");

Docker: How to use bash with an Alpine based docker image?

Alpine docker image doesn't have bash installed by default. You will need to add following commands to get bash:

RUN apk update && apk add bash

If youre using Alpine 3.3+ then you can just do

RUN apk add --no-cache bash

to keep docker image size small. (Thanks to comment from @sprkysnrky)

Service Temporarily Unavailable Magento?

In Magento 2 You have to remove file located in /var/.maintenance.flag - just realized that after some searching, so i shall share.

Best way to "negate" an instanceof

If you can use static imports, and your moral code allows them

public class ObjectUtils {
    private final Object obj;
    private ObjectUtils(Object obj) {
        this.obj = obj;
    }

    public static ObjectUtils thisObj(Object obj){
        return new ObjectUtils(obj);
    }

    public boolean isNotA(Class<?> clazz){
        return !clazz.isInstance(obj);
    }
}

And then...

import static notinstanceof.ObjectUtils.*;

public class Main {

    public static void main(String[] args) {
        String a = "";
        if (thisObj(a).isNotA(String.class)) {
            System.out.println("It is not a String");
        }
        if (thisObj(a).isNotA(Integer.class)) {
            System.out.println("It is not an Integer");
        }
    }    
}

This is just a fluent interface exercise, I'd never use that in real life code!
Go for your classic way, it won't confuse anyone else reading your code!

jQuery append and remove dynamic table row

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script>`enter code here`
        $(document).ready(function () {
var result=1;
$('input').keyup(function(){`enter code here`
     $('tr').each(function () {
         var sum = $(this).find('td.combat').text();
         var combat = $(this).find('input.combat').val();
         if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
                 result = parseFloat(sum)*parseFloat(combat);
             }

         $(this).find('.total-combat').html(result);
        });
    });
 $('.add').click(function(){
        var sno = $(this).parent().siblings('.sno').text();
        var cust = $(this).parent().siblings('.cust').text();
        var price = $(this).parent().siblings('td.combat').text();
        var rowValue = [];
        $(this).closest('tr').find("input").each(function() {
                  rowValue.push($(this).val());
                  return $(this).val(); 
                 });

         var rowValue1 = [];
        $(this).closest('tr').find("span").each(function() {
                  rowValue1.push($(this).text());
                  return $(this).val(); 
                 });

                    var markup = "<tr><td class='sno'>" + sno + "</td><td class='custname'>" + cust +"</td><td class='price'>" + price +"</td><td><input type='text' class='newtext' value="+ rowValue[0] +"></td><td class='total'>" + rowValue1[0] +"</td><td><input type='submit' class='update' value='upd'><input type='button' class='del' value='del'></td></tr>";



        var rightcol = $(this).closest('tr').find(".cust");
        var row_count =  $('.tbl1 tbody tr').length;
        alert(row_count);

        if (row_count == 0) {


                        $(".tbl1 tbody").append(markup);


        }
        else
        {
            var tes=0;
            $('.tbl1 tbody tr').each(function(){
                        var leftcol = $(this).find(".custname");

                            if(rightcol.html() == leftcol.html()) {
                                alert(leftcol.html()+"-----------------"+rightcol.html());
                                $(this).find('.sno').text(sno);
                                $(this).find('.custname').text(cust);
                                $(this).find('.price').text(price);
                                $(this).find('.newtext').val(rowValue[0]);
                                $(this).find('.total').text(rowValue1[0]);
                                tes++;
                     }
            });
                if(tes==0){
                    $(".tbl1 tbody").append(markup);
                }    


        }

});
            $(".tb").on("click", ".update", function(e) {
                var rowValues = [];
                                    $(this).closest('tr').find("input").each(function() {
                                  rowValues.push($(this).val());
                                  return $(this).val(); 

                                 });
                    var total=$(this).closest('tr').find('.total').text();
                    var right_cols = $(this).closest('tr').find(".custname");

                $('.tbl tbody tr').each(function(){
                        var row = $(this);
                        var left_cols = $(this).find(".cust");
                            if(left_cols.html() == right_cols.html()) {

                                $(this).find('.text').val(rowValues[0]);
                                $(this).find('.total-combat').text(total);
                             }
                         });



        });         
                $(".tb").on("keyup", "input", function() {
                 $('tr').each(function () {
                     var sum = $(this).find('td.price').text();
                     var combat = $(this).find('input.newtext').val();
                     if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
                            result = parseFloat(sum)*parseFloat(combat);
                         }

                        $(this).find('.total').html(result);
                    });
                });
         $(".tb").on("click", ".del", function() {
                  $(this).closest('tr').remove();
              });
});


    </script>
<style>

    .table_style {
    width: 500px;
    margin: 0px auto;
    }
    table{
    width: 100%;
    border-collapse: collapse;
    }
    table tr td{
    width: 50%;
    border: 5px solid #ff751a;
    padding: 5px;
    }
    table tr th{
    border: 5px solid #79ff4d;
    padding: 5px;
    }
    input{
        width:35px;
    }
    .tbl1{
        margin-top: 50px;
        border: 0px solid #cdcdcd;
    }
    .btn{
        float:left;
    }
    </style>
        <title>E-Commerce-Table</title>
</head>
<body>

<div class="table_style">
    <caption>Price-List</caption>
<table class="tbl">
    <tr>
        <th>S.No</th>
        <th>P.Name</th>
        <th>Price</th>
        <th>Qnty</th>
        <th>Rate</th>   
        <th>action</th>
    </tr>
    <tbody>
    <tr>
        <td class="sno">1</td>
        <td class="cust">A</td>
        <td class="combat">5</td>
        <td class="tester"><input type="number" id="qnty1" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">2</td>
        <td class="cust">B</td>
        <td class="combat">8</td>
        <td><input type="number" id="qnty2" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">3</td>
        <td class="cust">C</td>
        <td class="combat">7</td>
        <td><input type="number" id="qnty3" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">4</td>
        <td class="cust">D</td>
        <td class="combat">2</td>
        <td><input type="number" id="qnty4" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
</tbody>

</table>

     <table class="tbl1">
        <thead>
            <tr>
                <th>S.No</th>
                <th>P.Name</th>
                <th>Price</th>
                <th>Qnty</th>
                <th>Rate</th>
                <th>action</th>
            </tr>
        </thead>
        <tbody class="tb">

        </tbody>
    </table>
    <button type="submit" name="addtocart" id="btn">Add-to-cart</button>
</div>

</body>
</html>

What is the maximum length of a URL in different browsers?

Limit request line directive sets the maximum length of a URL. By default, it is set to 8190, which gives you a lot of room. However other servers and some browses, limit the length more.

Because all parameters are passed on the URL line, items that were in password of hidden fields will also be displayed in the URL of course. Neither mobile should be used for real security measures and should be considered cosmetic security at best.

On postback, how can I check which control cause postback in Page_Init event

If you need to check which control caused the postback, then you could just directly compare ["__EVENTTARGET"] to the control you are interested in:

if (specialControl.UniqueID == Page.Request.Params["__EVENTTARGET"])
{
    /*do special stuff*/
}

This assumes you're just going to be comparing the result from any GetPostBackControl(...) extension method anyway. It may not handle EVERY situation, but if it works it is simpler. Plus, you won't scour the page looking for a control you didn't care about to begin with.

Task continuation on UI thread

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.

C++ IDE for Linux?

If you like Eclipse for Java, I suggest Eclipse CDT. Despite C/C++ support isn't so powerful as is for Java, it still offers most of the features. It has a nice feature named Managed Project that makes working with C/C++ projects easier if you don't have experience with Makefiles. But you can still use Makefiles. I do C and Java coding and I'm really happy with CDT. I'm developing the firmware for a embedded device in C and a application in Java that talks to this device, and is really nice to use the same environment for both. I guess it probably makes me more productive.

Running Facebook application on localhost

2013 August. Facebook doesn't allow to set domain with port for an App, as example "localhost:3000".

So you can use https://pagekite.net to tunnel your localhost:port to proper domain.

Rails developers can use http://progrium.com/localtunnel/ for free.

  • Facebook allows only one domain for App at the time. If you are trying to add another one, as localhost, it will show some kind of different error about domain. Be sure to use only one domain for callback and for app domain setting at the time.

How to avoid Sql Query Timeout

Do you have an index defined over the Status column and MemberType column?

curl_init() function not working

For PHP 7 and Windows x64

libeay32.dll, libssh2.dll and ssleay32.dll should not be in apache/bin and should only exist in php directory and add php directory in system environment variable. This work for me.

Obvisouly in php.ini you should have enable php_curl.dll as well.

How many spaces will Java String.trim() remove?

String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");

How to call shell commands from Ruby

I'm definitely not a Ruby expert, but I'll give it a shot:

$ irb 
system "echo Hi"
Hi
=> true

You should also be able to do things like:

cmd = 'ls'
system(cmd)

How to set Apache Spark Executor memory

As far as i know it wouldn't be possible to change the spark.executor.memory at run time. If you are running a stand-alone version, with pyspark and graphframes, you can launch the pyspark REPL by executing the following command:

pyspark --driver-memory 2g --executor-memory 6g --packages graphframes:graphframes:0.7.0-spark2.4-s_2.11

Be sure to change the SPARK_VERSION environment variable appropriately regarding the latest released version of Spark

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Worked for me. All the similar ones didn't.

Using python's mock patch.object to change the return value of a method called within another method

Let me clarify what you're talking about: you want to test Foo in a testcase, which calls external method uses_some_other_method. Instead of calling the actual method, you want to mock the return value.

class Foo:
    def method_1():
       results = uses_some_other_method()
    def method_n():
       results = uses_some_other_method()

Suppose the above code is in foo.py and uses_some_other_method is defined in module bar.py. Here is the unittest:

import unittest
import mock

from foo import Foo


class TestFoo(unittest.TestCase):

    def setup(self):
        self.foo = Foo()

    @mock.patch('foo.uses_some_other_method')
    def test_method_1(self, mock_method):
        mock_method.return_value = 3
        self.foo.method_1(*args, **kwargs)

        mock_method.assert_called_with(*args, **kwargs)

If you want to change the return value every time you passed in different arguments, mock provides side_effect.

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

So, eventually I did that thing that all developers hate doing. I went and checked the server log files and found a report of a syntax error in line n.

tail -n 20 /var/log/apache2/error.log

Set and Get Methods in java?

Setters and getters are used to replace directly accessing member variables from external classes. if you use a setter and getter in accessing a property, you can include initialization, error checking, complex transformations, etc. Some examples:

private String x;

public void setX(String newX) {
    if (newX == null) {
        x = "";
    } else {
        x = newX;
    }
}

public String getX() {
    if (x == null) {
        return "";
    } else {
       return x;
    }
}

Load vs. Stress testing

Load Testing: Load testing is meant to test the system by constantly and steadily increasing the load on the system till the time it reaches the threshold limit.

Example For example, to check the email functionality of an application, it could be flooded with 1000 users at a time. Now, 1000 users can fire the email transactions (read, send, delete, forward, reply) in many different ways. If we take one transaction per user per hour, then it would be 1000 transactions per hour. By simulating 10 transactions/user, we could load test the email server by occupying it with 10000 transactions/hour.

Stress Testing: Under stress testing, various activities to overload the existing resources with excess jobs are carried out in an attempt to break the system down.

Example: As an example, a word processor like Writer1.1.0 by OpenOffice.org is utilized in development of letters, presentations, spread sheets etc… Purpose of our stress testing is to load it with the excess of characters.

To do this, we will repeatedly paste a line of data, till it reaches its threshold limit of handling large volume of text. As soon as the character size reaches 65,535 characters, it would simply refuse to accept more data. The result of stress testing on Writer 1.1.0 produces the result that, it does not crash under the stress and that it handle the situation gracefully, which make sure that application is working correctly even under rigorous stress conditions.

how to find host name from IP with out login to the host

  • For Windows, try:

    NBTSTAT -A 10.100.3.104
    

    or

    ping -a 10.100.3.104
    
  • For Linux, try:

    nmblookup -A 10.100.3.104
    

They are almost same.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

How do you automatically set text box to Uppercase?

The issue with CSS Styling is that it's not changing the data, and if you don't want to have a JS function then try...

<input onkeyup="this.value = this.value.toUpperCase()" />

on it's own you'll see the field capitalise on keyup, so it might be desirable to combine this with the style='text-transform:uppercase' others have suggested.

Vue.js data-bind style backgroundImage not working

For single repeated component this technic work for me

<div class="img-section" :style=img_section_style >

computed: {
            img_section_style: function(){
                var bgImg= this.post_data.fet_img
                return {
                    "color": "red",
                    "border" : "5px solid ",
                    "background": 'url('+bgImg+')'
                }
            },
}

Fill DataTable from SQL Server database

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

public DataTable fillDataTable(string table)
{
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = new SqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        return dt;
    }
}

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

Fatal error: Call to undefined function mysql_connect()

If you get this error after upgrading to PHP 7.0, then you are using deprecated libraries.

mysql_connect — Open a connection to a MySQL Server
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

More here: http://php.net/manual/en/function.mysql-connect.php

Round double value to 2 decimal places

You can use the below code to format it to two decimal places

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:22.368511]];

NSLog(@"Result...%@",numberString);//Result 22.37

Swift 4:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .up

let str = String(describing: formatter.string(from: 12.2345)!)

print(str)

How to add a "open git-bash here..." context menu to the windows explorer?

When you install git-scm found in "https://git-scm.com/downloads" uncheck the "Only show new options" located at the very bottom of the installation window

Make sure you check

  • Windows Explorer integration
    • Git Bash Here
    • Git GUI Here

Click Next and you're good to go!

jQuery UI Tabs - How to Get Currently Selected Tab Index

When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event. Also, if this line

var selectedTab = $("#TabList").tabs().data("selected.tabs");

is ran in the event like this:

$("#TabList").bind("tabsselect", function(event, ui) {
  var selectedTab = $("#TabList").tabs().data("selected.tabs");
});

selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.

However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.

javascript get child by id

In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():

function test(el){
  el.querySelector("#child").style.display = "none";
}

For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.

As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").

Get a list of all functions and procedures in an Oracle database

 SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE') 
 and owner = 'Schema_name' order by object_name

here 'Schema_name' is a name of schema, example i have a schema named PMIS, so the example will be

SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE') 
and owner = 'PMIS' order by object_name

enter image description here

Ref: https://www.plsql.co/list-all-procedures-from-a-schema-of-oracle-database.html

jQuery: how to trigger anchor link's click event

 window.open($('#myanchor').attr('href'));

               $('#myanchor')[0].click();

Store mysql query output into a shell variable

Other way:

Your Script:

#!/bin/sh

# Set these variables
MyUSER="root"   # DB_USERNAME
MyPASS="yourPass"   # DB_PASSWORD
MyHOST="yourHost"    # DB_HOSTNAME
DB_NAME="dbName"
CONTAINER="containerName" #if use docker

# Get data
data=$($MyHOST -u $MyUSER -p$MyPASS $DB_NAME -h $CONTAINER -e "SELECT data1,data2 from table_name LIMIT 1;"  -B --skip-column-names)

# Set data
data1=$(echo $data | awk '{print $1}')
data2=$(echo $data | awk '{print $2}')

# Print data
echo $data1 $data2

Compare a date string to datetime in SQL Server?

Just compare the year, month and day values.

Declare @DateToSearch DateTime
Set @DateToSearch = '14 AUG 2008'

SELECT * 
FROM table1
WHERE Year(column_datetime) = Year(@DateToSearch)
      AND Month(column_datetime) = Month(@DateToSearch)
      AND Day(column_datetime) = Day(@DateToSearch)

How can I get the order ID in WooCommerce?

it worked. Just modified it

global $woocommerce, $post;

$order = new WC_Order($post->ID);

//to escape # from order id 

$order_id = trim(str_replace('#', '', $order->get_order_number()));

Difference between rake db:migrate db:reset and db:schema:load

Rails 5

db:create - Creates the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.

db:create:all - Creates the database for all environments.

db:drop - Drops the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.

db:drop:all - Drops the database for all environments.

db:migrate - Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.

db:migrate:redo - Runs db:migrate:down and db:migrate:up or db:migrate:rollback and db:migrate:up depending on the specified migration.

db:migrate:up - Runs the up for the given migration VERSION.

db:migrate:down - Runs the down for the given migration VERSION.

db:migrate:status - Displays the current migration status.

db:migrate:rollback - Rolls back the last migration.

db:version - Prints the current schema version.

db:forward - Pushes the schema to the next version.

db:seed - Runs the db/seeds.rb file.

db:schema:load Recreates the database from the schema.rb file. Deletes existing data.

db:schema:dump Dumps the current environment’s schema to db/schema.rb.

db:structure:load - Recreates the database from the structure.sql file.

db:structure:dump - Dumps the current environment’s schema to db/structure.sql. (You can specify another file with SCHEMA=db/my_structure.sql)

db:setup Runs db:create, db:schema:load and db:seed.

db:reset Runs db:drop and db:setup. db:migrate:reset - Runs db:drop, db:create and db:migrate.

db:test:prepare - Check for pending migrations and load the test schema. (If you run rake without any arguments it will do this by default.)

db:test:clone - Recreate the test database from the current environment’s database schema.

db:test:clone_structure - Similar to db:test:clone, but it will ensure that your test database has the same structure, including charsets and collations, as your current environment’s database.

db:environment:set - Set the current RAILS_ENV environment in the ar_internal_metadata table. (Used as part of the protected environment check.)

db:check_protected_environments - Checks if a destructive action can be performed in the current RAILS_ENV environment. Used internally when running a destructive action such as db:drop or db:schema:load.

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

Eclipse: The declared package does not match the expected package

Just go into the build path and change the source path to be src/prefix1 instead of src.

It may be easiest to right-click on the src directory and select "Build Path / Remove from build path", then find the src/prefix1 directory, right-click it and select "Build Path / Use as source folder".

How can I loop over entries in JSON?

To decode json, you have to pass the json string. Currently you're trying to pass an object:

>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>

You can fetch the data with response.read().

How to disable Google Chrome auto update?

On a Mac, you can change the update frequency to a very large value. See:

For myself, I ran the following command in Terminal:

defaults write com.google.Keystone.Agent checkInterval 18000000

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

How many parameters are too many?

It heavily depends on the environment you're working in. Take for example javascript. In javascript the best way to pass in parameters is using objects with key/value pairs, which in practice means you only have one parameter. In other systems the sweet spot will be at three or four.

In the end, it all boils down to personal taste.

Radio buttons and label to display in same line

I was having the similar issue of keeping all radio buttons on the same line. After trying all the things I could, nothing worked for me except the following. What I mean is simply using table resolved the issue allowing radio buttons to appear in the same line.

<table>
<tr>
    <td>
        <label>
            @Html.RadioButton("p_sortForPatch", "byName", new { @checked = "checked", @class = "radio" }) By Name
        </label>
    </td>
    <td>
        <label>
            @Html.RadioButton("p_sortForPatch", "byDate", new { @class = "radio" }) By Date
        </label>
    </td>
</tr>
</table>

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
//OR    
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
//OR    
SET autocommit = ON;

How to clean project cache in Intellij idea like Eclipse's clean?

Maybe not THE answer, but it's definitely AN answer.

If nothing else is working for you, go the nuclear option: Close IDEA and delete the ".../.IntelliJIdea/system" directory using your local file system tools.

The .IntelliJIdea directory is usually found in your home directory. Your IDE configuration is in the ".../.IntelliJIdea/config" directory, so it should be fine.

Obviously, this is not the "IDEA" way to do it and would be completely unsupported by JetBrains. Also - I don't use Android Studio so I dunno if this will cause problems, but there you go.

It's worked for me before when I've had problems getting IDEA to start and nothing else works to get me going. Maybe back up your entire .IntelliJIdea directory if you have a morbid fear of losing all your work >.<

Inserting one list into another list in java?

An object is only once in memory. Your first addition to list just adds the object references.

anotherList.addAll will also just add the references. So still only 100 objects in memory.

If you change list by adding/removing elements, anotherList won't be changed. But if you change any object in list, then it's content will be also changed, when accessing it from anotherList, because the same reference is being pointed to from both lists.

How to randomly pick an element from an array

You can also use

public static int getRandom(int[] array) {
    int rnd = (int)(Math.random()*array.length);
    return array[rnd];
}

Math.random() returns an double between 0.0 (inclusive) to 1.0 (exclusive)

Multiplying this with array.length gives you a double between 0.0 (inclusive) and array.length (exclusive)

Casting to int will round down giving you and integer between 0 (inclusive) and array.length-1 (inclusive)

@UniqueConstraint and @Column(unique = true) in hibernate annotation

As said before, @Column(unique = true) is a shortcut to UniqueConstraint when it is only a single field.

From the example you gave, there is a huge difference between both.

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;

This code implies that both mask and group have to be unique, but separately. That means that if, for example, you have a record with a mask.id = 1 and tries to insert another record with mask.id = 1, you'll get an error, because that column should have unique values. The same aplies for group.

On the other hand,

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)

Implies that the values of mask + group combined should be unique. That means you can have, for example, a record with mask.id = 1 and group.id = 1, and if you try to insert another record with mask.id = 1 and group.id = 2, it'll be inserted successfully, whereas in the first case it wouldn't.

If you'd like to have both mask and group to be unique separately and to that at class level, you'd have to write the code as following:

@Table(
        name = "product_serial_group_mask",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "mask"),
                @UniqueConstraint(columnNames = "group")
        }
)

This has the same effect as the first code block.

Determine if running on a rooted device

if [[ "`adb shell which su | grep -io "permission denied"`" != "permission denied" ]]; then
   echo "Yes. Rooted device."
 else
   echo "No. Device not rooted. Only limited tasks can be performed. Done."
    zenity --warning --title="Device Not Rooted" --text="The connected Android Device is <b>NOT ROOTED</b>. Only limited tasks can be performed." --no-wrap
fi

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

How do I update the GUI from another thread?

When I encountered the same issue I sought help from Google, but rather than give me a simple solution it confused me more by giving examples of MethodInvoker and blah blah blah. So I decided to solve it on my own. Here is my solution:

Make a delegate like this:

Public delegate void LabelDelegate(string s);

void Updatelabel(string text)
{
   if (label.InvokeRequired)
   {
       LabelDelegate LDEL = new LabelDelegate(Updatelabel);
       label.Invoke(LDEL, text);
   }
   else
       label.Text = text
}

You can call this function in a new thread like this

Thread th = new Thread(() => Updatelabel("Hello World"));
th.start();

Don't be confused with Thread(() => .....). I use an anonymous function or lambda expression when I work on a thread. To reduce the lines of code you can use the ThreadStart(..) method too which I am not supposed to explain here.

Is there an effective tool to convert C# code to Java code?

We have an application that we need to maintain in both C# and Java. Since we actively maintain this product, a one-time port wasn't an option. We investigated Net2Java and the Mainsoft tools, but neither met our requirements (Net2Java for lack of robustness and Mainsoft for cost and lack of source code conversion). We created our own tool called CS2J that runs as part of our nightly build script and does a very effective port of our C# code to Java. Right now it is precisely good enough to translate our application, but would have a long way to go before being considered a comprehensive tool. We've licensed the technology to a few parties with similar needs and we're toying with the idea of releasing it publicly, but our core business just keeps us too busy these days.

How to refresh Gridview after pressed a button in asp.net

I was totally lost on why my Gridview.Databind() would not refresh.

My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:

gvServerConfiguration.Databind()
uppServerConfiguration.Update()

uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.

Hope this helps someone.

where to place CASE WHEN column IS NULL in this query

That looks like it might belong in the select statement:

SELECT id, col1, col2, col3, (CASE WHEN table3.col3 IS NULL THEN table2.col3 AS col4 ELSE table3.col3 as col4 END)
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
LEFT OUTER JOIN table3
ON table1.id = table3.id

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

How to copy a file to a remote server in Python using SCP or SSH?

A very simple approach is the following:

import os
os.system('sshpass -p "password" scp user@host:/path/to/file ./')

No python library are required (only os), and it works, however using this method relies on another ssh client to be installed. This could result in undesired behavior if ran on another system.

Common MySQL fields and their appropriate data types

Someone's going to post a much better answer than this, but just wanted to make the point that personally I would never store a phone number in any kind of integer field, mainly because:

  1. You don't need to do any kind of arithmetic with it, and
  2. Sooner or later someone's going to try to (do something like) put brackets around their area code.

In general though, I seem to almost exclusively use:

  • INT(11) for anything that is either an ID or references another ID
  • DATETIME for time stamps
  • VARCHAR(255) for anything guaranteed to be under 255 characters (page titles, names, etc)
  • TEXT for pretty much everything else.

Of course there are exceptions, but I find that covers most eventualities.

Perform debounce in React.js

If you are using redux you can do this in a very elegant way with middleware. You can define a Debounce middleware as:

var timeout;
export default store => next => action => {
  const { meta = {} } = action;
  if(meta.debounce){
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      next(action)
    }, meta.debounce)
  }else{
    next(action)
  }
}

You can then add debouncing to action creators, such as:

export default debouncedAction = (payload) => ({
  type : 'DEBOUNCED_ACTION',
  payload : payload,
  meta : {debounce : 300}
}

There's actually already middleware you can get off npm to do this for you.

How to unload a package without restarting R

detach(package:PackageName) works and there is no need to use quotes.

How to get TimeZone from android mobile?

Have you tried to use TimeZone.getDefault():

Most applications will use TimeZone.getDefault() which returns a TimeZone based on the time zone where the program is running.

Ref: http://developer.android.com/reference/java/util/TimeZone.html

ReferenceError: variable is not defined

It's declared inside a closure, which means it can only be accessed there. If you want a variable accessible globally, you can remove the var:

$(function(){
    value = "10";
});
value; // "10"

This is equivalent to writing window.value = "10";.

php date validation

Though checkdate is good, this seems much concise function to validate and also you can give formats. [Source]

function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function was copied from this answer or php.net


The extra ->format() is needed for cases where the date is invalid but createFromFormat still manages to create a DateTime object. For example:

// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');

// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');

Batch File: ( was unexpected at this time

Oh, dear. A few little problems...

As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.

Two other matters of which you should be aware:

First, set/p will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:

 set "var="
 set /p var=

That is, of course, if you don't WANT enter to repeat the existing value.
Another useful form is

 set "var=default"
 set /p var=

or

 set "var=default"
 set /p "var=[%var%]"

(which prompts with the default value; !var! if in a block statement with delayedexpansion)

Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment (which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)

"Couldn't read dependencies" error with npm

Recently, I've started to get an error:

npm ERR! install Couldn't read dependencies
npm ERR! Error: Invalid version: "1.0"

So, you may need to specify version of your package with 3 numbers, e.g. 1.0.0 instead of 1.0 if you get similar error.

Getting and removing the first character of a string

Use this function from stringi package

> x <- 'hello stackoverflow'
> stri_sub(x,2)
[1] "ello stackoverflow"

Android Center text on canvas

This worked for me :

 paint.setTextAlign(Paint.Align.CENTER);
        int xPos = (newWidth / 2);
        int yPos = (newHeight / 2);
        canvas.drawText("Hello", xPos, yPos, paint);

if anyone finds any problem please ket me know

bootstrap datepicker today as default

I used this a little example and it worked.

$('#date').datetimepicker({
    defaultDate: new Date()
});

demo : http://jsfiddle.net/m2fjw57b/1/

Reset Entity-Framework Migrations

In Entity Framework Core.

  1. Remove all files from migrations folder.

  2. Type in console

    dotnet ef database drop -f -v
    dotnet ef migrations add Initial
    dotnet ef database update
    

UPD: Do that only if you don't care about your current persisted data. If you do, use Greg Gum's answer

ToString() function in Go

Another example with a struct :

package types

import "fmt"

type MyType struct {
    Id   int    
    Name string
}

func (t MyType) String() string {
    return fmt.Sprintf(
    "[%d : %s]",
    t.Id, 
    t.Name)
}

Be careful when using it,
concatenation with '+' doesn't compile :

t := types.MyType{ 12, "Blabla" }

fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly

jQuery: How can I show an image popup onclick of the thumbnail?

This is the most popular (9500 stars) and light weight (20KB minify, 7.5KB minify+gzip) popup gallery I think: Magnific-Popup

How can I create a product key for my C# application?

You can check LicenseSpot. It provides:

  • Free Licensing Component
  • Online Activation
  • API to integrate your app and online store
  • Serial number generation
  • Revoke licenses
  • Subscription Management

Generating a PNG with matplotlib when DISPLAY is undefined

What system are you on? It looks like you have a system with X11, but the DISPLAY environment variable was not properly set. Try executing the following command and then rerunning your program:

export DISPLAY=localhost:0

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

If this issue occurs, kindly check web.config in below section

Below section gives the version of particular dll used

after checking this section in web.config, open solution explorer and select reference from the project tree as shown . Solution Explorer->Reference

After expanding reference, find the dll which caused the error. Right click on the dll reference and check for version like shown in the image above.

If both config dll version and referenced dll is different you would get this exception. Make sure both are of same version which would help.

SVG rounded corner

You have explicitly set your stroke-linejoin to round but your stroke-width to 0, so of course you're not going to see rounded corners if you have no stroke to round.

Here's a modified example with rounded corners made through strokes:
http://jsfiddle.net/8uxqK/1/

<path d="M64.5 45.5 82.5 45.5 82.5 64.5 64.5 64.5 z"
      stroke-width="5"
      stroke-linejoin="round"
      stroke="#808600"
      fill="#a0a700" />

Otherwise—if you need an actual rounded shape fill and not just a rounded fatty stroke—you must do what @Jlange says and make an actual rounded shape.

C# Copy a file to another location with a different name

One method is:

File.Copy(oldFilePathWithFileName, newFilePathWithFileName);

Or you can use the FileInfo.CopyTo() method too something like this:

FileInfo file = new FileInfo(oldFilePathWithFileName);
file.CopyTo(newFilePathWithFileName);

Example:

File.Copy(@"c:\a.txt", @"c:\b.txt");

or

FileInfo file = new FileInfo(@"c:\a.txt");
file.CopyTo(@"c:\b.txt");

Maven dependencies are failing with a 501 error

Add the following repository in pom.xml.

<project>
...
    <repositories>
        <repository>
            <id>central</id>
            <name>Maven Plugin Repository</name>
            <url>https://repo1.maven.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
...
</project>

Adding rows to tbody of a table using jQuery

With Lodash you can create a template and you can do that following way:

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-12">
                <table id="tblEntAttributes" class="table">
                    <tbody>
                        <tr>
                            <td>
                                chkboxId
                            </td>
                            <td>
                               chkboxValue
                            </td>
                            <td>
                                displayName
                            </td>
                            <td>
                               logicalName
                            </td>
                            <td>
                                dataType
                            </td>
                        </tr>
                    </tbody>
                </table>
                <button class="btn btn-primary" id="test">appendTo</button>
            </div>
        </div>
     </div>

And here goes the javascript:

        var count = 1;
        window.addEventListener('load', function () {
            var compiledRow = _.template("<tr><td><input type=\"checkbox\" id=\"<%= chkboxId %>\" value=\"<%= chkboxValue %>\"></td><td><%= displayName %></td><td><%= logicalName %></td><td><%= dataType %></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>");
            document.getElementById('test').addEventListener('click', function (e) {
                var ajaxData = { 'chkboxId': 'chkboxId-' + count, 'chkboxValue': 'chkboxValue-' + count, 'displayName': 'displayName-' + count, 'logicalName': 'logicalName-' + count, 'dataType': 'dataType-' + count };
                var tableRowData = compiledRow(ajaxData);
                $("#tblEntAttributes tbody").append(tableRowData);
                count++;
            });
        });

Here it is in jsbin

How to run Gulp tasks sequentially one after the other

According to the Gulp docs:

Are your tasks running before the dependencies are complete? Make sure your dependency tasks are correctly using the async run hints: take in a callback or return a promise or event stream.

To run your sequence of tasks synchronously:

  1. Return the event stream (e.g. gulp.src) to gulp.task to inform the task of when the stream ends.
  2. Declare task dependencies in the second argument of gulp.task.

See the revised code:

gulp.task "coffee", ->
    return gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean", ['coffee'], ->
      return gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"

Android TabLayout Android Design

I had to collect information from various sources to put together a functioning TabLayout. The following is presented as a complete use case that can be modified as needed.

Make sure the module build.gradle file contains a dependency on com.android.support:design.

dependencies {
    compile 'com.android.support:design:23.1.1'
}

In my case, I am creating an About activity in the application with a TabLayout. I added the following section to AndroidMainifest.xml. Setting the parentActivityName allows the home arrow to take the user back to the main activity.

<!-- android:configChanges="orientation|screenSize" makes the activity not reload when the orientation changes. -->
<activity
    android:name=".AboutActivity"
    android:label="@string/about_app"
    android:theme="@style/MyApp.About"
    android:parentActivityName=".MainActivity"
    android:configChanges="orientation|screenSize" >

    <!-- android.support.PARENT_ACTIVITY is necessary for API <= 15. -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainActivity" />
</activity>

styles.xml contains the following entries. This app has a white AppBar for the main activity and a blue AppBar for the About activity. We need to set colorPrimaryDark for the About activity so that the status bar above the AppBar is blue.

<style name="MyApp" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorAccent">@color/blue</item>
</style>

<style name="MyApp.About" />

<!-- ThemeOverlay.AppCompat.Dark.ActionBar" makes the text and the icons in the AppBar white. -->
<style name="MyApp.DarkAppBar" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="MyApp.AppBarOverlay" parent="ThemeOverlay.AppCompat.ActionBar" />

<style name="MyApp.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

There is also a styles.xml (v19). It is located at src/main/res/values-v19/styles.xml. This file is only applied if the API of the device is >= 19.

<!-- android:windowTranslucentStatus requires API >= 19.  It makes the system status bar transparent.
  When it is specified the root layout should include android:fitsSystemWindows="true".
  colorPrimaryDark goes behind the status bar, which is then darkened by the overlay. -->
<style name="MyApp.About">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="colorPrimaryDark">@color/blue</item>
</style>

AboutActivity.java contains the following code. In my case I have a fixed number of tabs (7) so I could remove all the code dealing with dynamic tabs.

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class AboutActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about_coordinatorlayout);

        // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
        Toolbar supportAppBar = (Toolbar) findViewById(R.id.about_toolbar);
        setSupportActionBar(supportAppBar);

        // Display the home arrow on supportAppBar.
        final ActionBar appBar = getSupportActionBar();
        assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
        appBar.setDisplayHomeAsUpEnabled(true);

        //  Setup the ViewPager.
        ViewPager aboutViewPager = (ViewPager) findViewById(R.id.about_viewpager);
        assert aboutViewPager != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutViewPager might be null.
        aboutViewPager.setAdapter(new aboutPagerAdapter(getSupportFragmentManager()));

        // Setup the TabLayout and connect it to the ViewPager.
        TabLayout aboutTabLayout = (TabLayout) findViewById(R.id.about_tablayout);
        assert aboutTabLayout != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutTabLayout might be null.
        aboutTabLayout.setupWithViewPager(aboutViewPager);
    }

    public class aboutPagerAdapter extends FragmentPagerAdapter {
        public aboutPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        // Get the count of the number of tabs.
        public int getCount() {
            return 7;
        }

        @Override
        // Get the name of each tab.  Tab numbers start at 0.
        public CharSequence getPageTitle(int tab) {
            switch (tab) {
                case 0:
                    return getString(R.string.version);

                case 1:
                    return getString(R.string.permissions);

                case 2:
                    return getString(R.string.privacy_policy);

                case 3:
                    return getString(R.string.changelog);

                case 4:
                    return getString(R.string.license);

                case 5:
                    return getString(R.string.contributors);

                case 6:
                    return getString(R.string.links);

                default:
                    return "";
            }
        }

        @Override
        // Setup each tab.
        public Fragment getItem(int tab) {
            return AboutTabFragment.createTab(tab);
        }
    }
}

AboutTabFragment.java is used to populate each tab. In my case, the first tab has a LinearLayout inside of a ScrollView and all the others have a WebView as the root layout.

import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;

public class AboutTabFragment extends Fragment {
    private int tabNumber;

    // AboutTabFragment.createTab stores the tab number in the bundle arguments so it can be referenced from onCreate().
    public static AboutTabFragment createTab(int tab) {
        Bundle thisTabArguments = new Bundle();
        thisTabArguments.putInt("Tab", tab);
        AboutTabFragment thisTab = new AboutTabFragment();
        thisTab.setArguments(thisTabArguments);
        return thisTab;
    }

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

        // Store the tab number in tabNumber.
        tabNumber = getArguments().getInt("Tab");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View tabLayout;

        // Load the about tab layout.  Tab numbers start at 0.
        if (tabNumber == 0) {
            // Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
            // The fragment will take care of attaching the root automatically.
            tabLayout = inflater.inflate(R.layout.about_tab_version, container, false);
        } else { // load a WebView for all the other tabs.  Tab numbers start at 0.
            // Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
            // The fragment will take care of attaching the root automatically.
            tabLayout = inflater.inflate(R.layout.about_tab_webview, container, false);
            WebView tabWebView = (WebView) tabLayout;

            switch (tabNumber) {
                case 1:
                tabWebView.loadUrl("file:///android_asset/about_permissions.html");
                    break;

                case 2:
                    tabWebView.loadUrl("file:///android_asset/about_privacy_policy.html");
                    break;

                case 3:
                    tabWebView.loadUrl("file:///android_asset/about_changelog.html");
                    break;

                case 4:
                    tabWebView.loadUrl("file:///android_asset/about_license.html");
                    break;

                case 5:
                    tabWebView.loadUrl("file:///android_asset/about_contributors.html");
                    break;

                case 6:
                    tabWebView.loadUrl("file:///android_asset/about_links.html");
                    break;

                default:
                    break;
            }
        }

        return tabLayout;
    }
}

about_coordinatorlayout.xml is as follows:

<!-- android:fitsSystemWindows="true" moves the AppBar below the status bar.
  When it is specified the theme should include <item name="android:windowTranslucentStatus">true</item>
  to make the status bar a transparent, darkened overlay. -->
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/about_coordinatorlayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true" >

    <!-- the LinearLayout with orientation="vertical" moves the ViewPager below the AppBarLayout. -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <!-- We need to set android:background="@color/blue" here or any space to the right of the TabLayout on large devices will be white. -->
        <android.support.design.widget.AppBarLayout
            android:id="@+id/about_appbarlayout"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:background="@color/blue"
            android:theme="@style/MyApp.AppBarOverlay" >

            <!-- android:theme="@style/PrivacyBrowser.DarkAppBar" makes the text and icons in the AppBar white. -->
            <android.support.v7.widget.Toolbar
                android:id="@+id/about_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/blue"
                android:theme="@style/MyApp.DarkAppBar"
                app:popupTheme="@style/MyApp.PopupOverlay" />

            <android.support.design.widget.TabLayout
                android:id="@+id/about_tablayout"
                xmlns:android.support.design="http://schemas.android.com/apk/res-auto"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android.support.design:tabBackground="@color/blue"
                android.support.design:tabTextColor="@color/light_blue"
                android.support.design:tabSelectedTextColor="@color/white"
                android.support.design:tabIndicatorColor="@color/white"
                android.support.design:tabMode="scrollable" />
        </android.support.design.widget.AppBarLayout>

        <!-- android:layout_weight="1" makes about_viewpager fill the rest of the screen. -->
        <android.support.v4.view.ViewPager
            android:id="@+id/about_viewpager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

about_tab_version.xml is as follows:

<!-- The ScrollView allows the LinearLayout to scroll if it exceeds the height of the page. -->
<ScrollView
    android:id="@+id/about_version_scrollview"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent" >

    <LinearLayout
        android:id="@+id/about_version_linearlayout"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:padding="16dp" >

        <!-- Include whatever content you want in this tab here. -->

    </LinearLayout>
</ScrollView>

And about_tab_webview.xml:

<!-- This WebView displays inside of the tabs in AboutActivity. -->
<WebView
    android:id="@+id/about_tab_webview"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

There are also entries in strings.xml

<string name="about_app">About App</string>
<string name="version">Version</string>
<string name="permissions">Permissions</string>
<string name="privacy_policy">Privacy Policy</string>
<string name="changelog">Changelog</string>
<string name="license">License</string>
<string name="contributors">Contributors</string>
<string name="links">Links</string>

And colors.xml

<color name="blue">#FF1976D2</color>
<color name="light_blue">#FFBBDEFB</color>
<color name="white">#FFFFFFFF</color>

src/main/assets contains the HTML files referenced in AboutTabFragemnt.java.

Pass all variables from one shell script to another?

You have basically two options:

  1. Make the variable an environment variable (export TESTVARIABLE) before executing the 2nd script.
  2. Source the 2nd script, i.e. . test2.sh and it will run in the same shell. This would let you share more complex variables like arrays easily, but also means that the other script could modify variables in the source shell.

UPDATE:

To use export to set an environment variable, you can either use an existing variable:

A=10
# ...
export A

This ought to work in both bash and sh. bash also allows it to be combined like so:

export A=10

This also works in my sh (which happens to be bash, you can use echo $SHELL to check). But I don't believe that that's guaranteed to work in all sh, so best to play it safe and separate them.

Any variable you export in this way will be visible in scripts you execute, for example:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

The fact that these are both shell scripts is also just incidental. Environment variables can be passed to any process you execute, for example if we used python instead it might look like:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.py

b.py:

#!/usr/bin/python

import os

print 'The message is:', os.environ['MESSAGE']

Sourcing:

Instead we could source like this:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

This more or less "imports" the contents of b.sh directly and executes it in the same shell. Notice that we didn't have to export the variable to access it. This implicitly shares all the variables you have, as well as allows the other script to add/delete/modify variables in the shell. Of course, in this model both your scripts should be the same language (sh or bash). To give an example how we could pass messages back and forth:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

echo "[A] The message is: $MESSAGE"

b.sh:

#!/bin/sh

echo "[B] The message is: $MESSAGE"

MESSAGE="goodbye"

Then:

$ ./a.sh
[B] The message is: hello
[A] The message is: goodbye

This works equally well in bash. It also makes it easy to share more complex data which you could not express as an environment variable (at least without some heavy lifting on your part), like arrays or associative arrays.

Export multiple classes in ES6 modules

Hope this helps:

// Export (file name: my-functions.js)
export const MyFunction1 = () => {}
export const MyFunction2 = () => {}
export const MyFunction3 = () => {}

// if using `eslint` (airbnb) then you will see warning, so do this:
const MyFunction1 = () => {}
const MyFunction2 = () => {}
const MyFunction3 = () => {}

export {MyFunction1, MyFunction2, MyFunction3};

// Import
import * as myFns from "./my-functions";

myFns.MyFunction1();
myFns.MyFunction2();
myFns.MyFunction3();


// OR Import it as Destructured
import { MyFunction1, MyFunction2, MyFunction3 } from "./my-functions";

// AND you can use it like below with brackets (Parentheses) if it's a function 
// AND without brackets if it's not function (eg. variables, Objects or Arrays)  
MyFunction1();
MyFunction2();

Laravel: getting a a single value from a MySQL query

Using query builder, get the single column value such as groupName

  $groupName = DB::table('users')->where('username', $username)->pluck('groupName');

For Laravel 5.1

 $groupName=DB::table('users')->where('username', $username)->value('groupName');

Or, Using user model, get the single column value

 $groupName = User::where('username', $username)->pluck('groupName');

Or, get the first row and then split for getting single column value

 $data = User::where('username', $username)->first();
 if($data)
   $groupName=$data->groupName;

Get the value of a dropdown in jQuery

The best way is to use:

$("#yourid option:selected").text();

Depending on the requirement, you could also use this way:

var v = $("#yourid").val();
$("#yourid option[value="+v+"]").text()

Clear History and Reload Page on Login/Logout Using Ionic Framework

.state(url: '/url', controller: Ctl, templateUrl: 'template.html', cache: false) cache: false ==> solved my problem !

How do I get first element rather than using [0] in jQuery?

You can use .get(0) as well but...you shouldn't need to do that with an element found by ID, that should always be unique. I'm hoping this is just an oversight in the example...if this is the case on your actual page, you'll need to fix it so your IDs are unique, and use a class (or another attribute) instead.

.get() (like [0]) gets the DOM element, if you want a jQuery object use .eq(0) or .first() instead :)

Declaration of Methods should be Compatible with Parent Methods in PHP

I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.

What I though

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

What I've finally done

namespace mycompany\CutreApi;

use \vendor\AwesomeApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new \mycompany\CutreApi\ClassOfVendor();
   }
}

So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.

One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.

Currently done

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function getWhatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.

Hope this can help someone.

What is 'Context' on Android?

Context is an "interface" to the global information about an application environment. In practice, Context is actually an abstract class, whose implementation is provided by the Android system.

It allows access to application-specific resources and classes, as well as up-calls for application-level operations, such as launching activities, broadcasting and receiving intents, etc.

In the following picture, you can see a hierarchy of classes, where Context is the root class of this hierarchy. In particular, it's worth emphasizing that Activity is a descendant of Context.

Activity diagram

Best way to handle multiple constructors in Java

Several people have recommended adding a null check. Sometimes that's the right thing to do, but not always. Check out this excellent article showing why you'd skip it.

http://misko.hevery.com/2009/02/09/to-assert-or-not-to-assert/

JavaScript: Alert.Show(message) From ASP.NET Code-behind

Here is an easy way:

Response.Write("<script>alert('Hello');</script>");

What is the best Java email address validation method?

I ported some of the code in Zend_Validator_Email:

@FacesValidator("emailValidator")
public class EmailAddressValidator implements Validator {

    private String localPart;
    private String hostName;
    private boolean domain = true;

    Locale locale;
    ResourceBundle bundle;

    private List<FacesMessage> messages = new ArrayList<FacesMessage>();

    private HostnameValidator hostnameValidator;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        setOptions(component);
        String email    = (String) value;
        boolean result  = true;
        Pattern pattern = Pattern.compile("^(.+)@([^@]+[^.])$");
        Matcher matcher = pattern.matcher(email);

        locale = context.getViewRoot().getLocale();
        bundle = ResourceBundle.getBundle("com.myapp.resources.validationMessages", locale);

        boolean length = true;
        boolean local  = true;

        if (matcher.find()) {
            localPart   = matcher.group(1);
            hostName    = matcher.group(2);

            if (localPart.length() > 64 || hostName.length() > 255) {
                length          = false;
                addMessage("enterValidEmail", "email.AddressLengthExceeded");
            } 

            if (domain == true) {
                hostnameValidator = new HostnameValidator();
                hostnameValidator.validate(context, component, hostName);
            }

            local = validateLocalPart();

            if (local && length) {
                result = true;
            } else {
                result = false;
            }

        } else {
            result          = false;
            addMessage("enterValidEmail", "invalidEmailAddress");
        }

        if (result == false) {
            throw new ValidatorException(messages);
        }

    }

    private boolean validateLocalPart() {
        // First try to match the local part on the common dot-atom format
        boolean result = false;

        // Dot-atom characters are: 1*atext *("." 1*atext)
        // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
        //        "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~"
        String atext = "a-zA-Z0-9\\u0021\\u0023\\u0024\\u0025\\u0026\\u0027\\u002a"
                + "\\u002b\\u002d\\u002f\\u003d\\u003f\\u005e\\u005f\\u0060\\u007b"
                + "\\u007c\\u007d\\u007e";
        Pattern regex = Pattern.compile("^["+atext+"]+(\\u002e+["+atext+"]+)*$");
        Matcher matcher = regex.matcher(localPart);
        if (matcher.find()) {
            result = true;
        } else {
            // Try quoted string format

            // Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE
            // qtext: Non white space controls, and the rest of the US-ASCII characters not
            //   including "\" or the quote character
            String noWsCtl = "\\u0001-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f";
            String qText = noWsCtl + "\\u0021\\u0023-\\u005b\\u005d-\\u007e";
            String ws = "\\u0020\\u0009";

            regex = Pattern.compile("^\\u0022(["+ws+qText+"])*["+ws+"]?\\u0022$");
            matcher = regex.matcher(localPart);
            if (matcher.find()) {
                result = true;
            } else {
                addMessage("enterValidEmail", "email.AddressDotAtom");
                addMessage("enterValidEmail", "email.AddressQuotedString");
                addMessage("enterValidEmail", "email.AddressInvalidLocalPart");
            }
        }

        return result;
    }

    private void addMessage(String detail, String summary) {
        String detailMsg = bundle.getString(detail);
        String summaryMsg = bundle.getString(summary);
        messages.add(new FacesMessage(FacesMessage.SEVERITY_ERROR, summaryMsg, detailMsg));
    }

    private void setOptions(UIComponent component) {
        Boolean domainOption = Boolean.valueOf((String) component.getAttributes().get("domain"));
        //domain = (domainOption == null) ? true : domainOption.booleanValue();
    }
}

With a hostname validator as follows:

@FacesValidator("hostNameValidator")
public class HostnameValidator implements Validator {

    private Locale locale;
    private ResourceBundle bundle;
    private List<FacesMessage> messages;
    private boolean checkTld = true;
    private boolean allowLocal = false;
    private boolean allowDNS = true;
    private String tld;
    private String[] validTlds = {"ac", "ad", "ae", "aero", "af", "ag", "ai",
        "al", "am", "an", "ao", "aq", "ar", "arpa", "as", "asia", "at", "au",
        "aw", "ax", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "biz",
        "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca",
        "cat", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co",
        "com", "coop", "cr", "cu", "cv", "cx", "cy", "cz", "de", "dj", "dk",
        "dm", "do", "dz", "ec", "edu", "ee", "eg", "er", "es", "et", "eu", "fi",
        "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh",
        "gi", "gl", "gm", "gn", "gov", "gp", "gq", "gr", "gs", "gt", "gu", "gw",
        "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in",
        "info", "int", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jobs",
        "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz",
        "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma",
        "mc", "md", "me", "mg", "mh", "mil", "mk", "ml", "mm", "mn", "mo",
        "mobi", "mp", "mq", "mr", "ms", "mt", "mu", "museum", "mv", "mw", "mx",
        "my", "mz", "na", "name", "nc", "ne", "net", "nf", "ng", "ni", "nl",
        "no", "np", "nr", "nu", "nz", "om", "org", "pa", "pe", "pf", "pg", "ph",
        "pk", "pl", "pm", "pn", "pr", "pro", "ps", "pt", "pw", "py", "qa", "re",
        "ro", "rs", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si",
        "sj", "sk", "sl", "sm", "sn", "so", "sr", "st", "su", "sv", "sy", "sz",
        "tc", "td", "tel", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to",
        "tp", "tr", "travel", "tt", "tv", "tw", "tz", "ua", "ug", "uk", "um",
        "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws",
        "ye", "yt", "yu", "za", "zm", "zw"};
    private Map<String, Map<Integer, Integer>> idnLength;

    private void init() {
        Map<Integer, Integer> biz = new HashMap<Integer, Integer>();
        biz.put(5, 17);
        biz.put(11, 15);
        biz.put(12, 20);

        Map<Integer, Integer> cn = new HashMap<Integer, Integer>();
        cn.put(1, 20);

        Map<Integer, Integer> com = new HashMap<Integer, Integer>();
        com.put(3, 17);
        com.put(5, 20);

        Map<Integer, Integer> hk = new HashMap<Integer, Integer>();
        hk.put(1, 15);

        Map<Integer, Integer> info = new HashMap<Integer, Integer>();
        info.put(4, 17);

        Map<Integer, Integer> kr = new HashMap<Integer, Integer>();
        kr.put(1, 17);

        Map<Integer, Integer> net = new HashMap<Integer, Integer>();
        net.put(3, 17);
        net.put(5, 20);

        Map<Integer, Integer> org = new HashMap<Integer, Integer>();
        org.put(6, 17);

        Map<Integer, Integer> tw = new HashMap<Integer, Integer>();
        tw.put(1, 20);

        Map<Integer, Integer> idn1 = new HashMap<Integer, Integer>();
        idn1.put(1, 20);

        Map<Integer, Integer> idn2 = new HashMap<Integer, Integer>();
        idn2.put(1, 20);

        Map<Integer, Integer> idn3 = new HashMap<Integer, Integer>();
        idn3.put(1, 20);

        Map<Integer, Integer> idn4 = new HashMap<Integer, Integer>();
        idn4.put(1, 20);

        idnLength = new HashMap<String, Map<Integer, Integer>>();

        idnLength.put("BIZ", biz);
        idnLength.put("CN", cn);
        idnLength.put("COM", com);
        idnLength.put("HK", hk);
        idnLength.put("INFO", info);
        idnLength.put("KR", kr);
        idnLength.put("NET", net);
        idnLength.put("ORG", org);
        idnLength.put("TW", tw);
        idnLength.put("?????", idn1);
        idnLength.put("??", idn2);
        idnLength.put("??", idn3);
        idnLength.put("??", idn4);

        messages = new ArrayList<FacesMessage>();
    }

    public HostnameValidator() {
        init();
    }

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String hostName = (String) value;

        locale = context.getViewRoot().getLocale();
        bundle = ResourceBundle.getBundle("com.myapp.resources.validationMessages", locale);

        Pattern ipPattern = Pattern.compile("^[0-9a-f:\\.]*$", Pattern.CASE_INSENSITIVE);
        Matcher ipMatcher = ipPattern.matcher(hostName);
        if (ipMatcher.find()) {
            addMessage("hostname.IpAddressNotAllowed");
            throw new ValidatorException(messages);
        }

        boolean result = false;

        // removes last dot (.) from hostname 
        hostName = hostName.replaceAll("(\\.)+$", "");
        String[] domainParts = hostName.split("\\.");

        boolean status = false;

        // Check input against DNS hostname schema
        if ((domainParts.length > 1) && (hostName.length() > 4) && (hostName.length() < 255)) {
            status = false;

            dowhile:
            do {
                // First check TLD
                int lastIndex = domainParts.length - 1;
                String domainEnding = domainParts[lastIndex];
                Pattern tldRegex = Pattern.compile("([^.]{2,10})", Pattern.CASE_INSENSITIVE);
                Matcher tldMatcher = tldRegex.matcher(domainEnding);
                if (tldMatcher.find() || domainEnding.equals("?????")
                        || domainEnding.equals("??")
                        || domainEnding.equals("??")
                        || domainEnding.equals("??")) {



                    // Hostname characters are: *(label dot)(label dot label); max 254 chars
                    // label: id-prefix [*ldh{61} id-prefix]; max 63 chars
                    // id-prefix: alpha / digit
                    // ldh: alpha / digit / dash

                    // Match TLD against known list
                    tld = (String) tldMatcher.group(1).toLowerCase().trim();
                    if (checkTld == true) {
                        boolean foundTld = false;
                        for (int i = 0; i < validTlds.length; i++) {
                            if (tld.equals(validTlds[i])) {
                                foundTld = true;
                            }
                        }

                        if (foundTld == false) {
                            status = false;
                            addMessage("hostname.UnknownTld");
                            break dowhile;
                        }
                    }

                    /**
                     * Match against IDN hostnames
                     * Note: Keep label regex short to avoid issues with long patterns when matching IDN hostnames
                     */
                    List<String> regexChars = getIdnRegexChars();

                    // Check each hostname part
                    int check = 0;
                    for (String domainPart : domainParts) {
                        // Decode Punycode domainnames to IDN
                        if (domainPart.indexOf("xn--") == 0) {
                            domainPart = decodePunycode(domainPart.substring(4));
                        }

                        // Check dash (-) does not start, end or appear in 3rd and 4th positions
                        if (domainPart.indexOf("-") == 0
                                || (domainPart.length() > 2 && domainPart.indexOf("-", 2) == 2 && domainPart.indexOf("-", 3) == 3)
                                || (domainPart.indexOf("-") == (domainPart.length() - 1))) {
                            status = false;
                            addMessage("hostname.DashCharacter");
                            break dowhile;
                        }

                        // Check each domain part
                        boolean checked = false;

                        for (int key = 0; key < regexChars.size(); key++) {
                            String regexChar = regexChars.get(key);
                            Pattern regex = Pattern.compile(regexChar);
                            Matcher regexMatcher = regex.matcher(domainPart);
                            status = regexMatcher.find();
                            if (status) {
                                int length = 63;

                                if (idnLength.containsKey(tld.toUpperCase())
                                        && idnLength.get(tld.toUpperCase()).containsKey(key)) {
                                    length = idnLength.get(tld.toUpperCase()).get(key);
                                }

                                int utf8Length;
                                try {
                                    utf8Length = domainPart.getBytes("UTF8").length;
                                    if (utf8Length > length) {
                                        addMessage("hostname.InvalidHostname");
                                    } else {
                                        checked = true;
                                        break;
                                    }
                                } catch (UnsupportedEncodingException ex) {
                                    Logger.getLogger(HostnameValidator.class.getName()).log(Level.SEVERE, null, ex);
                                }


                            }
                        }


                        if (checked) {
                            ++check;
                        }
                    }

                    // If one of the labels doesn't match, the hostname is invalid
                    if (check != domainParts.length) {
                        status = false;
                        addMessage("hostname.InvalidHostnameSchema");

                    }
                } else {
                    // Hostname not long enough
                    status = false;
                    addMessage("hostname.UndecipherableTld");
                }

            } while (false);

            if (status == true && allowDNS) {
                result = true;
            }

        } else if (allowDNS == true) {
            addMessage("hostname.InvalidHostname");
            throw new ValidatorException(messages);
        }

        // Check input against local network name schema;
        Pattern regexLocal = Pattern.compile("^(([a-zA-Z0-9\\x2d]{1,63}\\x2e)*[a-zA-Z0-9\\x2d]{1,63}){1,254}$", Pattern.CASE_INSENSITIVE);
        boolean checkLocal = regexLocal.matcher(hostName).find();
        if (allowLocal && !status) {
            if (checkLocal) {
                result = true;
            } else {
                // If the input does not pass as a local network name, add a message
                result = false;
                addMessage("hostname.InvalidLocalName");
            }
        }


        // If local network names are not allowed, add a message
        if (checkLocal && !allowLocal && !status) {
            result = false;
            addMessage("hostname.LocalNameNotAllowed");
        }

        if (result == false) {
            throw new ValidatorException(messages);
        }

    }

    private void addMessage(String msg) {
        String bundlMsg = bundle.getString(msg);
        messages.add(new FacesMessage(FacesMessage.SEVERITY_ERROR, bundlMsg, bundlMsg));
    }

    /**
     * Returns a list of regex patterns for the matched TLD
     * @param tld
     * @return 
     */
    private List<String> getIdnRegexChars() {
        List<String> regexChars = new ArrayList<String>();
        regexChars.add("^[a-z0-9\\x2d]{1,63}$");
        Document doc = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        try {
            InputStream validIdns = getClass().getClassLoader().getResourceAsStream("com/myapp/resources/validIDNs_1.xml");
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(validIdns);
            doc.getDocumentElement().normalize();
        } catch (SAXException ex) {
            Logger.getLogger(HostnameValidator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HostnameValidator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(HostnameValidator.class.getName()).log(Level.SEVERE, null, ex);
        }

        // prepare XPath
        XPath xpath = XPathFactory.newInstance().newXPath();

        NodeList nodes = null;
        String xpathRoute = "//idn[tld=\'" + tld.toUpperCase() + "\']/pattern/text()";

        try {
            XPathExpression expr;
            expr = xpath.compile(xpathRoute);
            Object res = expr.evaluate(doc, XPathConstants.NODESET);
            nodes = (NodeList) res;
        } catch (XPathExpressionException ex) {
            Logger.getLogger(HostnameValidator.class.getName()).log(Level.SEVERE, null, ex);
        }


        for (int i = 0; i < nodes.getLength(); i++) {
            regexChars.add(nodes.item(i).getNodeValue());
        }

        return regexChars;
    }

    /**
     * Decode Punycode string
     * @param encoded
     * @return 
         */
    private String decodePunycode(String encoded) {
        Pattern regex = Pattern.compile("([^a-z0-9\\x2d]{1,10})", Pattern.CASE_INSENSITIVE);
        Matcher matcher = regex.matcher(encoded);
        boolean found = matcher.find();

        if (encoded.isEmpty() || found) {
            // no punycode encoded string, return as is
            addMessage("hostname.CannotDecodePunycode");
            throw new ValidatorException(messages);
        }

        int separator = encoded.lastIndexOf("-");
            List<Integer> decoded = new ArrayList<Integer>();
        if (separator > 0) {
            for (int x = 0; x < separator; ++x) {
                decoded.add((int) encoded.charAt(x));
            }
        } else {
            addMessage("hostname.CannotDecodePunycode");
            throw new ValidatorException(messages);
        }

        int lengthd = decoded.size();
        int lengthe = encoded.length();

        // decoding
        boolean init = true;
        int base = 72;
        int index = 0;
        int ch = 0x80;

        int indexeStart = (separator == 1) ? (separator + 1) : 0;
        for (int indexe = indexeStart; indexe < lengthe; ++lengthd) {
            int oldIndex = index;
            int pos = 1;
            for (int key = 36; true; key += 36) {
                int hex = (int) encoded.charAt(indexe++);
                int digit = (hex - 48 < 10) ? hex - 22
                        : ((hex - 65 < 26) ? hex - 65
                        : ((hex - 97 < 26) ? hex - 97
                        : 36));

                index += digit * pos;
                int tag = (key <= base) ? 1 : ((key >= base + 26) ? 26 : (key - base));
                if (digit < tag) {
                    break;
                }
                pos = (int) (pos * (36 - tag));
            }
            int delta = (int) (init ? ((index - oldIndex) / 700) : ((index - oldIndex) / 2));
            delta += (int) (delta / (lengthd + 1));
            int key;
            for (key = 0; delta > 910; key += 36) {
                delta = (int) (delta / 35);
            }
            base = (int) (key + 36 * delta / (delta + 38));
            init = false;
            ch += (int) (index / (lengthd + 1));
            index %= (lengthd + 1);
            if (lengthd > 0) {
                for (int i = lengthd; i > index; i--) {
                    decoded.set(i, decoded.get(i - 1));
                }
            }

            decoded.set(index++, ch);
        }

        // convert decoded ucs4 to utf8 string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < decoded.size(); i++) {
            int value = decoded.get(i);
            if (value < 128) {
                sb.append((char) value);
            } else if (value < (1 << 11)) {
                sb.append((char) (192 + (value >> 6)));
                sb.append((char) (128 + (value & 63)));
            } else if (value < (1 << 16)) {
                sb.append((char) (224 + (value >> 12)));
                sb.append((char) (128 + ((value >> 6) & 63)));
                sb.append((char) (128 + (value & 63)));
            } else if (value < (1 << 21)) {
                sb.append((char) (240 + (value >> 18)));
                sb.append((char) (128 + ((value >> 12) & 63)));
                sb.append((char) (128 + ((value >> 6) & 63)));
                sb.append((char) (128 + (value & 63)));
            } else {
                addMessage("hostname.CannotDecodePunycode");
                throw new ValidatorException(messages);
            }
        }

        return sb.toString();

    }

    /**
     * Eliminates empty values from input array
     * @param data
     * @return 
     */
    private String[] verifyArray(String[] data) {
        List<String> result = new ArrayList<String>();
        for (String s : data) {
            if (!s.equals("")) {
                result.add(s);
            }
        }

        return result.toArray(new String[result.size()]);
    }
}

And a validIDNs.xml with regex patterns for the different tlds (too big to include:)

<idnlist>
    <idn>
        <tld>AC</tld>
        <pattern>^[\u002d0-9a-zà-öø-ÿaaaccccddeeeeggghhiijklll?lnnn?oœrrrsssštttuuuuuwyzzž]{1,63}$</pattern>
    </idn>
    <idn>
        <tld>AR</tld>
        <pattern>^[\u002d0-9a-zà-ãç-êìíñ-õü]{1,63}$</pattern>
    </idn>
    <idn>
        <tld>AS</tld>
        <pattern>/^[\u002d0-9a-zà-öø-ÿaaaccccddeeeeegggghhiiiiijk?llllnnn?oooœrrrsssštttuuuuuuwyzz]{1,63}$</pattern>
    </idn>
    <idn>
        <tld>AT</tld>
        <pattern>/^[\u002d0-9a-zà-öø-ÿœšž]{1,63}$</pattern>
    </idn>
    <idn>
        <tld>BIZ</tld>
        <pattern>^[\u002d0-9a-zäåæéöøü]{1,63}$</pattern>
        <pattern>^[\u002d0-9a-záéíñóúü]{1,63}$</pattern>
        <pattern>^[\u002d0-9a-záéíóöúüou]{1,63}$</pattern>
    </id>
</idlist>

How to save .xlsx data to file as a blob

I've found a solution worked for me:

const handleDownload = async () => {
   const req = await axios({
     method: "get",
     url: `/companies/${company.id}/data`,
     responseType: "blob",
   });
   var blob = new Blob([req.data], {
     type: req.headers["content-type"],
   });
   const link = document.createElement("a");
   link.href = window.URL.createObjectURL(blob);
   link.download = `report_${new Date().getTime()}.xlsx`;
   link.click();
 };

I just point a responseType: "blob"

Get last key-value pair in PHP array

As the key is needed, the accepted solution doesn't work.

This:

end($array);
return array(key($array) => array_pop($array));

will return exactly as the example in the question.

Where is Maven Installed on Ubuntu

Ubuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you'll always know where to find your stuff.

As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the "properties". Under properties, you'll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try 'echo $PATH' on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the "home" is typically in /usr/lib or /usr/share.

For instance, according to http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/, maven is installed like:

The Apt-get installation will install all the required files in the following folder structure

/usr/bin/mvn

/usr/share/maven2/

/etc/maven2

P.S The Maven configuration is store in /etc/maven2

Note, it's not just apt-get that will do this, it's any .deb package installer.

Visual Studio - How to change a project's folder name and solution name without breaking the solution

You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.

#pragma pack effect

A compiler may place structure members on particular byte boundaries for reasons of performance on a particular architecture. This may leave unused padding between members. Structure packing forces members to be contiguous.

This may be important for example if you require a structure to conform to a particular file or communications format where the data you need the data to be at specific positions within a sequence. However such usage does not deal with endian-ness issues, so although used, it may not be portable.

It may also to exactly overlay the internal register structure of some I/O device such as a UART or USB controller for example, in order that register access be through a structure rather than direct addresses.

iOS: present view controller programmatically

You need to set storyboard Id from storyboard identity inspector

 AddTaskViewController *add=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboard_id"];
 [self presentViewController:add animated:YES completion:nil];

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

How to add two strings as if they were numbers?

MDN docs for parseInt
MDN docs for parseFloat

In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!

parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)

Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.

http://jsfiddle.net/EtX6G/

var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];

Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);

function Append(text) {
    body.appendChild(document.createTextNode(text));
    body.appendChild(document.createElement('br'));
}

Why can't I change my input value in React even with the onChange listener

In react, state will not change until you do it by using this.setState({});. That is why your console message showing old values.

How can I remove a style added with .css() function?

The accepted answer works but leaves an empty style attribute on the DOM in my tests. No big deal, but this removes it all:

removeAttr( 'style' );

This assumes you want to remove all dynamic styling and return back to the stylesheet styling.

Retrieving JSON Object Literal from HttpServletRequest

are you looking for this ?

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = request.getReader();
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } finally {
        reader.close();
    }
    System.out.println(sb.toString());
}

Query to check index on a table

Simply you can find index name and column names of a particular table using below command

SP_HELPINDEX 'tablename'

It work's for me

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

Sql Server equivalent of a COUNTIF aggregate function

I had to use COUNTIF() in my case as part of my SELECT columns AND to mimic a % of the number of times each item appeared in my results.

So I used this...

SELECT COL1, COL2, ... ETC
       (1 / SELECT a.vcount 
            FROM (SELECT vm2.visit_id, count(*) AS vcount 
                  FROM dbo.visitmanifests AS vm2 
                  WHERE vm2.inactive = 0 AND vm2.visit_id = vm.Visit_ID 
                  GROUP BY vm2.visit_id) AS a)) AS [No of Visits],
       COL xyz
FROM etc etc

Of course you will need to format the result according to your display requirements.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

How to multiply duration by integer?

My turn:

https://play.golang.org/p/RifHKsX7Puh

package main

import (
    "fmt"
    "time"
)

func main() {
    var n int = 77
    v := time.Duration( 1.15 * float64(n) ) * time.Second

    fmt.Printf("%v %T", v, v)
}

It helps to remember the simple fact, that underlyingly the time.Duration is a mere int64, which holds nanoseconds value.

This way, conversion to/from time.Duration becomes a formality. Just remember:

  • int64
  • always nanosecs

How to check if a variable is not null?

There is another possible scenario I have just come across.

I did an ajax call and got data back as null, in a string format. I had to check it like this:

if(value != 'null'){}

So, null was a string which read "null" rather than really being null.

EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.

MySQL update CASE WHEN/THEN/ELSE

Try this

UPDATE `table` SET `uid` = CASE
    WHEN id = 1 THEN 2952
    WHEN id = 2 THEN 4925
    WHEN id = 3 THEN 1592
    ELSE `uid`
    END
WHERE id  in (1,2,3)

How do I truncate a .NET string?

Because performance testing is fun: (using linqpad extension methods)

var val = string.Concat(Enumerable.Range(0, 50).Select(i => i % 10));

foreach(var limit in new[] { 10, 25, 44, 64 })
    new Perf<string> {
        { "newstring" + limit, n => new string(val.Take(limit).ToArray()) },
        { "concat" + limit, n => string.Concat(val.Take(limit)) },
        { "truncate" + limit, n => val.Substring(0, Math.Min(val.Length, limit)) },
        { "smart-trunc" + limit, n => val.Length <= limit ? val : val.Substring(0, limit) },
        { "stringbuilder" + limit, n => new StringBuilder(val, 0, Math.Min(val.Length, limit), limit).ToString() },
    }.Vs();

The truncate method was "significantly" faster. #microoptimization

Early

  • truncate10 5788 ticks elapsed (0.5788 ms) [in 10K reps, 5.788E-05 ms per]
  • smart-trunc10 8206 ticks elapsed (0.8206 ms) [in 10K reps, 8.206E-05 ms per]
  • stringbuilder10 10557 ticks elapsed (1.0557 ms) [in 10K reps, 0.00010557 ms per]
  • concat10 45495 ticks elapsed (4.5495 ms) [in 10K reps, 0.00045495 ms per]
  • newstring10 72535 ticks elapsed (7.2535 ms) [in 10K reps, 0.00072535 ms per]

Late

  • truncate44 8835 ticks elapsed (0.8835 ms) [in 10K reps, 8.835E-05 ms per]
  • stringbuilder44 13106 ticks elapsed (1.3106 ms) [in 10K reps, 0.00013106 ms per]
  • smart-trunc44 14821 ticks elapsed (1.4821 ms) [in 10K reps, 0.00014821 ms per]
  • newstring44 144324 ticks elapsed (14.4324 ms) [in 10K reps, 0.00144324 ms per]
  • concat44 174610 ticks elapsed (17.461 ms) [in 10K reps, 0.0017461 ms per]

Too Long

  • smart-trunc64 6944 ticks elapsed (0.6944 ms) [in 10K reps, 6.944E-05 ms per]
  • truncate64 7686 ticks elapsed (0.7686 ms) [in 10K reps, 7.686E-05 ms per]
  • stringbuilder64 13314 ticks elapsed (1.3314 ms) [in 10K reps, 0.00013314 ms per]
  • newstring64 177481 ticks elapsed (17.7481 ms) [in 10K reps, 0.00177481 ms per]
  • concat64 241601 ticks elapsed (24.1601 ms) [in 10K reps, 0.00241601 ms per]

.gitignore all the .DS_Store files in every folder and subfolder

You should add following lines while creating a project. It will always ignore .DS_Store to be pushed to the repository.

*.DS_Store this will ignore .DS_Store while code commit.
git rm --cached .DS_Store this is to remove .DS_Store files from your repository, in case you need it, you can uncomment it.

## ignore .DS_Store file.
# git rm --cached .DS_Store
*.DS_Store

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

For those who didn't solve the problem setting route middleware in App\Http\Kernel, try to set global middleware. In App\Http\Middleware\Cors:

public function handle($request, Closure $next)
{
    return $next($request)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}

In App\Http\Kernel:

protected $middleware = [
    ...
    \App\Http\Middleware\Cors::class,
];

Dynamically converting java object of Object class to a given class when class name is known

@SuppressWarnings("unchecked")
private static <T extends Object> T cast(Object obj) {
    return (T) obj;
}

How to set selected index JComboBox by value

You should use model

comboBox.getModel().setSelectedItem(object);

difference between throw and throw new Exception()

Your second example will reset the exception's stack trace. The first most accurately preserves the origins of the exception. Also you've unwrapped the original type which is key in knowing what actually went wrong... If the second is required for functionality - e.g. To add extended info or re-wrap with special type such as a custom 'HandleableException' then just be sure that the InnerException property is set too!

in_array() and multidimensional array

I was looking for a function that would let me search for both strings and arrays (as needle) in the array (haystack), so I added to the answer by @jwueller.

Here's my code:

/**
 * Recursive in_array function
 * Searches recursively for needle in an array (haystack).
 * Works with both strings and arrays as needle.
 * Both needle's and haystack's keys are ignored, only values are compared.
 * Note: if needle is an array, all values in needle have to be found for it to
 * return true. If one value is not found, false is returned.
 * @param  mixed   $needle   The array or string to be found
 * @param  array   $haystack The array to be searched in
 * @param  boolean $strict   Use strict value & type validation (===) or just value
 * @return boolean           True if in array, false if not.
 */
function in_array_r($needle, $haystack, $strict = false) {
     // array wrapper
    if (is_array($needle)) {
        foreach ($needle as $value) {
            if (in_array_r($value, $haystack, $strict) == false) {
                // an array value was not found, stop search, return false
                return false;
            }
        }
        // if the code reaches this point, all values in array have been found
        return true;
    }

    // string handling
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle)
            || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

What is LDAP used for?

The main idea of LDAP is to keep in one place all the information of a user (contact details, login, password, permissions), so that it is easier to maintain by network administrators. For example you can:

  • use the same login/passwd to login on an Intranet and on your local computer.
  • give specific permissions to a group of user. For example some could access some specific page of your Intranet, or some specific directories on a shared drive.
  • get all the contact details of the people in a company on Outlook for example.

adding directory to sys.path /PYTHONPATH

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

Vertical Alignment of text in a table cell

Try

_x000D_
_x000D_
td.description {_x000D_
  line-height: 15px_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_

Set the line-height value to the desired value.

How to override the properties of a CSS class using another CSS class

You should override by increasing Specificity of your styling. There are different ways of increasing the Specificity. Usage of !important which effects specificity, is a bad practice because it breaks natural cascading in your style sheet.

Following diagram taken from css-tricks.com will help you produce right specificity for your element based on a points structure. Whichever specificity has higher points, will win. Sounds like a game - doesn't it?

enter image description here

Checkout sample calculations here on css-tricks.com. This will help you understand the concept very well and it will only take 2 minutes.

If you then like to produce and/or compare different specificities by yourself, try this Specificity Calculator: https://specificity.keegan.st/ or you can just use traditional paper/pencil.

For further reading try MDN Web Docs.

All the best for not using !important.

How to apply a function to two columns of Pandas dataframe

I suppose you don't want to change get_sublist function, and just want to use DataFrame's apply method to do the job. To get the result you want, I've wrote two help functions: get_sublist_list and unlist. As the function name suggest, first get the list of sublist, second extract that sublist from that list. Finally, We need to call apply function to apply those two functions to the df[['col_1','col_2']] DataFrame subsequently.

import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']

def get_sublist(sta,end):
    return mylist[sta:end+1]

def get_sublist_list(cols):
    return [get_sublist(cols[0],cols[1])]

def unlist(list_of_lists):
    return list_of_lists[0]

df['col_3'] = df[['col_1','col_2']].apply(get_sublist_list,axis=1).apply(unlist)

df

If you don't use [] to enclose the get_sublist function, then the get_sublist_list function will return a plain list, it'll raise ValueError: could not broadcast input array from shape (3) into shape (2), as @Ted Petrou had mentioned.

Swift: print() vs println() vs NSLog()

Moreover, Swift 2 has debugPrint() (and CustomDebugStringConvertible protocol)!

Don't forget about debugPrint() which works like print() but most suitable for debugging.

Examples:

  • Strings
    • print("Hello World!") becomes Hello World
    • debugPrint("Hello World!") becomes "Hello World" (Quotes!)
  • Ranges
    • print(1..<6) becomes 1..<6
    • debugPrint(1..<6) becomes Range(1..<6)

Any class can customize their debug string representation via CustomDebugStringConvertible protocol.

How do I use WPF bindings with RelativeSource?

If you want to bind to another property on the object:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

If you want to get a property on an ancestor:

{Binding Path=PathToProperty,
    RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

or, shorter (this only works for OneWay bindings):

{TemplateBinding Path=PathToProperty}

jQuery: How to capture the TAB keypress within a Textbox

Above shown methods did not work for me, may be i am using bit old jquery, then finally the below shown code snippet works for - posting just in case somebody in my same position

$('#textBox').live('keydown', function(e) {
    if (e.keyCode == 9) {
        e.preventDefault();
        alert('tab');
    }
});

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

How can I get file extensions with JavaScript?

I just realized that it's not enough to put a comment on p4bl0's answer, though Tom's answer clearly solves the problem:

return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");

Which programming languages can be used to develop in Android?

  • At launch, Java was the only officially supported programming language for building distributable third-party Android software.

  • Android Native Development Kit (Android NDK) which will allow developers to build Android software components with C and C++.

  • In addition to delivering support for native code, Google is also extending Android to support popular dynamic scripting languages. Earlier this month, Google launched the Android Scripting Environment (ASE) which allows third-party developers to build simple Android applications with perl, JRuby, Python, LUA and BeanShell. For having idea and usage of ASE, refer this Example link.

  • Scala is also supported. For having examples of Scala, refer these Example link-1 , Example link-2 , Example link-3 .

  • Just now i have referred one Article Here in which i found some useful information as follows:

    1. programming language is Java but bridges from other languages exist (C# .net - Mono, etc).
    2. can run script languages like LUA, Perl, Python, BeanShell, etc.

  • I have read 2nd article at Google Releases 'Simple' Android Programming Language . For example of this, refer this .

  • Just now (2 Aug 2010) i have read an article which describes regarding "Frink Programming language and Calculating Tool for Android", refer this links Link-1 , Link-2

  • On 4-Aug-2010, i have found Regarding RenderScript. Basically, It is said to be a C-like language for high performance graphics programming, which helps you easily write efficient Visual effects and animations in your Android Applications. Its not released yet as it isn't finished.

How to find Google's IP address?

Google maintains a server infrastructure that grows dynamically with the ever increasing internet demands. This link by google describes the method to remain up to date with their IP address ranges.

When you need the literal IP addresses for Google Apps mail servers, start by using one of the common DNS lookup commands (nslookup, dig, host) to retrieve the SPF records for the domain _spf.google.com, like so:

nslookup -q=TXT _spf.google.com 8.8.8.8

This returns a list of the domains included in Google's SPF record, such as: _netblocks.google.com, _netblocks2.google.com, _netblocks3.google.com

Now look up the DNS records associated with those domains, one at a time, like so:

nslookup -q=TXT _netblocks.google.com 8.8.8.8
nslookup -q=TXT _netblocks2.google.com 8.8.8.8
nslookup -q=TXT _netblocks3.google.com 8.8.8.8

The results of these commands contain the current range of addresses.

What is the difference between null=True and blank=True in Django?

null is for database and blank is for fields validation that you want to show on user interface like textfield to get the last name of person. If lastname=models.charfield (blank=true) it didnot ask user to enter last name as this is the optional field now. If lastname=models.charfield (null=true) then it means that if this field doesnot get any value from user then it will store in database as an empty string " ".

When and how should I use a ThreadLocal variable?

Thread-local variables are often used to prevent sharing in designs based on mutable Singletons or global variables.

It can be used in scenarios like making seperate JDBC connection for each thread when you are not using a Connection Pool.

private static ThreadLocal<Connection> connectionHolder
           = new ThreadLocal<Connection>() {
      public Connection initialValue() {
           return DriverManager.getConnection(DB_URL);
          }
     };

public static Connection getConnection() {
      return connectionHolder.get();
} 

When you call getConnection, it will return a connection associated with that thread.The same can be done with other properties like dateformat, transaction context that you don't want to share between threads.

You could have also used local variables for the same, but these resource usually take up time in creation,so you don't want to create them again and again whenever you perform some business logic with them. However, ThreadLocal values are stored in the thread object itself and as soon as the thread is garbage collected, these values are gone too.

This link explains use of ThreadLocal very well.

Android: How to Programmatically set the size of a Layout

Java

This should work:

// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);

If you want to convert dip to pixels, use this:

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());

Kotlin

Disable activity slide-in animation when launching new activity?

The FLAG_ACTIVITY_NO_ANIMATION flag works fine for disabling the animation when starting activities.

To disable the similar animation that is triggered when calling finish() on an Activity, i.e the animation slides from right to left instead, you can call overridePendingTransition(0, 0) after calling finish() and the next animation will be excluded.

This also works on the in-animation if you call overridePendingTransition(0, 0) after calling startActivity(...).

ImportError: No module named sqlalchemy

Did you install flask-sqlalchemy? It looks like you have SQLAlchemy installed but not the Flask extension. Try pip install Flask-SQLAlchemy in your project's virtualenv to install it from PyPI.

I get conflicting provisioning settings error when I try to archive to submit an iOS app

Using Xcode 10: None of the other solutions here worked for me.

This error appears to be something you can't fix in Xcode 10

I had to revert to Xcode 9 to resolve this issue, and then update back to Xcode 10 so I could run my application on iOS 12 on a non-emulator device.

Any other solutions found on Stack Overflow or elsewhere, used in Xcode 10, sent me into an endless cycle of provisioning conflicts or signing certificate issues. It seems like signing is broken in Xcode 10 whether you're using the automatic method or manually selecting provisioning profiles and certificates.

You can revert to Xcode 9 by first deleting Xcode 10 from your Applications folder. Then, install Xcode 9 using the .xip file listed on this Apple Developers page.

In Xcode 9, use the automatic build option. You may have to uncheck 'Automatically manage signing' and reselect it, and you also may be required to revoke an existing certificate at developer.apple.com.

After you get the app to successfully build in Xcode 9, you can update back to Xcode 10 using the App Store. After reopening the application in Xcode 10, everything still worked. You may not need to do this, but I needed to in order to build for iOS 12 which requires Xcode 10.

jQuery changing font family and font size

Full working solution :

HTML:

<form id="myform">
    <button>erase</button>
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana ">Verdana </option>
        <option value="Impact ">Impact </option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>

    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>

<br/>

<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
    <div id="float">
        <p>
            Text into container
        </p>
    </div>
</div>

jQuery:

$("#fs").change(function() {
    //alert($(this).val());
    $('.changeMe').css("font-family", $(this).val());

});

$("#size").change(function() {
    $('.changeMe').css("font-size", $(this).val() + "px");
});

Fiddle here: http://jsfiddle.net/AaT9b/

Select rows from a data frame based on values in a vector

Another option would be to use a keyed data.table:

library(data.table)
setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]

which results in:

   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4

What this does:

  • setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.
  • Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

setDT(dt)[J(vc), on=.(fct)]

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

setDT(dt, key = 'fct')[J(vc), nomatch = 0]

or:

setDT(dt)[J(vc), on=.(fct), nomatch = 0]