Programs & Examples On #Rdoc

RDoc is the default embedded documentation generator for Ruby. Rdoc generates structured documentation that can be accessed via a web browser or the command-line by analyzing the code and specially formatted comments. Even in the absence of comments, rdoc will generate documentation using a programs structure.

ASP.NET Core - Swashbuckle not creating swagger.json file

I had the same problem. Check http://localhost:XXXX/swagger/v1/swagger.json. If you get any a errors, fix them.

For example, I had an ambiguous route in a base controller class and I got the error: "Ambiguous HTTP method for action. Actions require an explicit HttpMethod binding for Swagger 2.0.". If you use base controllers make sure your public methods use the HttpGet/HttpPost/HttpPut/HttpDelete OR Route attributes to avoid ambiguous routes.

Then, also, I had defined both HttpGet("route") AND Route("route") attributes in the same method, which was the last issue for swagger.

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

Use .htaccess to redirect HTTP to HTTPs

None if this worked for me. First of all I had to look at my provider to see how they activate SSL in .htaccess my provider gives

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{HTTP:HTTPS} !on
   RewriteRule (.*) https://%{SERVER_NAME}/$1 [QSA,L,R=301]
</IfModule>

But what took me days of research is I had to add to wp-config.php the following lines as my provided site is behind a proxy :

/**
 * Force le SSL
 */
define('FORCE_SSL_ADMIN', true);
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) $_SERVER['HTTPS']='on';

httpd-xampp.conf: How to allow access to an external IP besides localhost?

Open for new app "HTTPD" (Apache server) in your Firewall

Take a look at this: https://www.youtube.com/watch?v=eqgUGF3NnuM

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

**

bundle install --no-deployment

**

$ jekyll help

jekyll 4.0.0 -- Jekyll is a blog-aware, static site generator in Ruby

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

This could be because of wrong configuration, esp if your other sites are working fine.

<VirtualHost cmsdemo.git:88>
    DocumentRoot "C:/Projects/rwp/"
    ServerName cmsdemo.git
    <Directory C:/Projects/cmsdemo/>
        Require all granted 
        AllowOverride All
    </Directory>
</VirtualHost>

Notice in DocumentRoot I am specifying one folder and in Directory, I am specifying another hence 403 Error. This fixed my problem.

Android sqlite how to check if a record exists

Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:

  public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
    String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
    return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
  }

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.

Proxy Error

The proxy server received an invalid response from an upstream server.
 The proxy server could not handle the request GET /lin/Campaignn.jsp.

As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.

Laravel - Forbidden You don't have permission to access / on this server

For those who using Mamp or Mamp pro:

Open MAMP Pro
Click on “Hosts”
Click on “Extended” (UPDATE: Only if you are using MAMP Pro 3.0.6)
Check “Indexes”
Click “Save”
That’s it! Reload your localhost starting page and it should work properly.

500 Internal Server Error for php file not for html

I know this question is old, however I ran into this problem on Windows 8.1 while trying to use .htaccess files for rewriting. My solution was simple, I forgot to modify the following line in httpd.conf

#LoadModule rewrite_module modules/mod_rewrite.so

to

LoadModule rewrite_module modules/mod_rewrite.so

Restarted the apache monitor, now all works well. Just posting this as an answer because someone in the future may run across the same issue with a simple fix.

Good luck!

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

I had a similar issue. I was using jQuery.map but I forgot to use jQuery.map(...).get() at the end to work with a normal array.

Why do I get a "permission denied" error while installing a gem?

I think the problem happened when you use rbenv. Try the below commands to fix it.

rbenv shell {rb_version}
rbenv global {rb_version}
or 
rbenv local {rb_version}

No input file specified

The No input file specified is a message you are presented with because of the implementation of PHP on your server, which in this case indicates a CGI implementation (can be verified with phpinfo()).

Now, to properly explain this, you need to have some basic understanding on how your system works with URL's. Based on your .htaccess file, it seems that your CMS expects the URL to passed along as a PATH_INFO variable. CGI and FastCGI implementations do not have PATH_INFO available, so when trying to pass the URI along, PHP fails with that message.

We need to find an alternative.

One option is to try and fix this. Looking into the documentation for core php.ini directives you can see that you can change the workings for your implementation. Although, GoDaddy probably won't allow you to change PHP settings on a shared enviroment.

We need to find an alternative to modifying PHP settings
Looking into system/uri.php on line 40, you will see that the CMS attempts two types of URI detection - the first being PATH_INFO, which we just learned won't work - the other being the REQUEST_URI.

This should basically, be enough - but the parsing of the URI passed, will cause you more trouble, as the URI, which you could pass to REQUEST_URI variable, forces parse_url() to only return the URL path - which basically puts you back to zero.

Now, there's actually only one possibilty left - and that's changing the core of the CMS. The URI detection part is insufficient.

Add QUERY_STRING to the array on line 40 as the first element in system/uri.php and change your .htaccess to look like this:

RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule ^(.*)$ index.php?/$1 [L]

This will pass the URI you request to index.php as QUERY_STRING and have the URI detection to find it.

This, on the other hand, makes it impossible to update the CMS without changing core files till this have been fixed. That sucks...

Need a better option?
Find a better CMS.

What is .htaccess file?

You are allow to use php_value to change php setting in .htaccess file. Same like how php.ini did.

Example:

php_value date.timezone Asia/Kuala_Lumpur

For other php setting, please read http://www.php.net/manual/en/ini.list.php

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

.htaccess not working apache

If you have tried all of the above, which are all valid and good answers, and your htaccess file is not working or being read change the directive in the apache2.conf file. Under Ubuntu the path is /etc/apache2/apache2.conf

Change the <Directory> directive pointing to your public web pages, where the htaccess file resides. Change from AllowOverride None to AllowOverride All

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

I had the same problem and found the answer and explanation on the Ubuntu Ask! forum https://askubuntu.com/questions/421233/enabling-htaccess-file-to-rewrite-path-not-working

Error message "Forbidden You don't have permission to access / on this server"

This is pretty ridiculous, but I got the 403 Forbidden when the file I was trying to download wasn't there on the filesystem. The apache error is not very accurate in this case, and the whole thing worked after I simply put the file where it was supposed to be.

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Incase you have multiple versions of Postgres installed on your machine. You can remove all via brew command as:

brew uninstall --force postgresql

How to calculate combination and permutation in R?

The function combn is in the standard utils package (i.e. already installed)

choose is also already available in the Special {base}

CodeIgniter 500 Internal Server Error

Make sure your root index.php file has the correct permission, its permission must be 0755 or 0644

How to simulate a mouse click using JavaScript?

From the Mozilla Developer Network (MDN) documentation, HTMLElement.click() is what you're looking for. You can find out more events here.

header('HTTP/1.0 404 Not Found'); not doing anything

No, it probably is actually working. It's just not readily visible. Instead of just using the header call, try doing that, then including 404.php, and then calling die.

You can test the fact that the HTTP/1.0 404 Not Found works by creating a PHP file named, say, test.php with this content:

<?php

header("HTTP/1.0 404 Not Found");
echo "PHP continues.\n";
die();
echo "Not after a die, however.\n";

Then viewing the result with curl -D /dev/stdout reveals:

HTTP/1.0 404 Not Found
Date: Mon, 04 Apr 2011 03:39:06 GMT
Server: Apache
X-Powered-By: PHP/5.3.2
Content-Length: 14
Connection: close
Content-Type: text/html

PHP continues.

Chrome sendrequest error: TypeError: Converting circular structure to JSON

I normally use the circular-json npm package to solve this.

// Felix Kling's example
var a = {};
a.b = a;
// load circular-json module
var CircularJSON = require('circular-json');
console.log(CircularJSON.stringify(a));
//result
{"b":"~"}

Note: circular-json has been deprecated, I now use flatted (from the creator of CircularJSON):

// ESM
import {parse, stringify} from 'flatted/esm';

// CJS
const {parse, stringify} = require('flatted/cjs');

const a = [{}];
a[0].a = a;
a.push(a);

stringify(a); // [["1","0"],{"a":"0"}]

from: https://www.npmjs.com/package/flatted

Deny all, allow only one IP through htaccess

ErrorDocument 403 /maintenance.html
Order Allow,Deny
Allow from #:#:#:#:#:#

For me, this seems to work (Using IPv6 rather than IPv4) I don't know if this is different for some websites but for mine this works.

Simple and fast method to compare images for similarity

I face the same issues recently, to solve this problem(simple and fast algorithm to compare two images) once and for all, I contribute an img_hash module to opencv_contrib, you can find the details from this link.

img_hash module provide six image hash algorithms, quite easy to use.

Codes example

origin lenaorigin lena

blur lenablur lena

resize lenaresize lena

shift lenashift lena

#include <opencv2/core.hpp>
#include <opencv2/core/ocl.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/img_hash.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>

void compute(cv::Ptr<cv::img_hash::ImgHashBase> algo)
{
    auto input = cv::imread("lena.png");
    cv::Mat similar_img;

    //detect similiar image after blur attack
    cv::GaussianBlur(input, similar_img, {7,7}, 2, 2);
    cv::imwrite("lena_blur.png", similar_img);
    cv::Mat hash_input, hash_similar;
    algo->compute(input, hash_input);
    algo->compute(similar_img, hash_similar);
    std::cout<<"gaussian blur attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;

    //detect similar image after shift attack
    similar_img.setTo(0);
    input(cv::Rect(0,10, input.cols,input.rows-10)).
            copyTo(similar_img(cv::Rect(0,0,input.cols,input.rows-10)));
    cv::imwrite("lena_shift.png", similar_img);
    algo->compute(similar_img, hash_similar);
    std::cout<<"shift attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;

    //detect similar image after resize
    cv::resize(input, similar_img, {120, 40});
    cv::imwrite("lena_resize.png", similar_img);
    algo->compute(similar_img, hash_similar);
    std::cout<<"resize attack : "<<
               algo->compare(hash_input, hash_similar)<<std::endl;
}

int main()
{
    using namespace cv::img_hash;

    //disable opencl acceleration may(or may not) boost up speed of img_hash
    cv::ocl::setUseOpenCL(false);

    //if the value after compare <= 8, that means the images
    //very similar to each other
    compute(ColorMomentHash::create());

    //there are other algorithms you can try out
    //every algorithms have their pros and cons
    compute(AverageHash::create());
    compute(PHash::create());
    compute(MarrHildrethHash::create());
    compute(RadialVarianceHash::create());
    //BlockMeanHash support mode 0 and mode 1, they associate to
    //mode 1 and mode 2 of PHash library
    compute(BlockMeanHash::create(0));
    compute(BlockMeanHash::create(1));
}

In this case, ColorMomentHash give us best result

  • gaussian blur attack : 0.567521
  • shift attack : 0.229728
  • resize attack : 0.229358

Pros and cons of each algorithm

Performance under different attacks

The performance of img_hash is good too

Speed comparison with PHash library(100 images from ukbench) compute performance comparison performance

If you want to know the recommend thresholds for these algorithms, please check this post(http://qtandopencv.blogspot.my/2016/06/introduction-to-image-hash-module-of.html). If you are interesting about how do I measure the performance of img_hash modules(include speed and different attacks), please check this link(http://qtandopencv.blogspot.my/2016/06/speed-up-image-hashing-of-opencvimghash.html).

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

You're in luck bud...I had the same issue but had more tech knowledge on the matter and was able to determine that it was a mod_sec issue that hostgator has to fix/whitelist on their own. You cannot do it yourself. Simply ask the hostgator tech to check mod_sec settings on your server.

Enjoy your fixed issue ;D

.htaccess mod_rewrite - how to exclude directory from rewrite rule

RewriteEngine On

RewriteRule ^(wordpress)($|/) - [L]

How to make --no-ri --no-rdoc the default for gem install?

You just add the following line to your local ~/.gemrc file (it is in your home folder):

gem: --no-document

or you can add this line to the global gemrc config file.

Here is how to find it (in Linux):

strace gem source 2>&1 | grep gemrc

How can I create an error 404 in PHP?

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

Ruby: How to post a file via HTTP as multipart/form-data?

Well the solution with NetHttp has a drawback that is when posting big files it loads the whole file into memory first.

After playing a bit with it I came up with the following solution:

class Multipart

  def initialize( file_names )
    @file_names = file_names
  end

  def post( to_url )
    boundary = '----RubyMultipartClient' + rand(1000000).to_s + 'ZZZZZ'

    parts = []
    streams = []
    @file_names.each do |param_name, filepath|
      pos = filepath.rindex('/')
      filename = filepath[pos + 1, filepath.length - pos]
      parts << StringPart.new ( "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"" + param_name.to_s + "\"; filename=\"" + filename + "\"\r\n" +
      "Content-Type: video/x-msvideo\r\n\r\n")
      stream = File.open(filepath, "rb")
      streams << stream
      parts << StreamPart.new (stream, File.size(filepath))
    end
    parts << StringPart.new ( "\r\n--" + boundary + "--\r\n" )

    post_stream = MultipartStream.new( parts )

    url = URI.parse( to_url )
    req = Net::HTTP::Post.new(url.path)
    req.content_length = post_stream.size
    req.content_type = 'multipart/form-data; boundary=' + boundary
    req.body_stream = post_stream
    res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }

    streams.each do |stream|
      stream.close();
    end

    res
  end

end

class StreamPart
  def initialize( stream, size )
    @stream, @size = stream, size
  end

  def size
    @size
  end

  def read ( offset, how_much )
    @stream.read ( how_much )
  end
end

class StringPart
  def initialize ( str )
    @str = str
  end

  def size
    @str.length
  end

  def read ( offset, how_much )
    @str[offset, how_much]
  end
end

class MultipartStream
  def initialize( parts )
    @parts = parts
    @part_no = 0;
    @part_offset = 0;
  end

  def size
    total = 0
    @parts.each do |part|
      total += part.size
    end
    total
  end

  def read ( how_much )

    if @part_no >= @parts.size
      return nil;
    end

    how_much_current_part = @parts[@part_no].size - @part_offset

    how_much_current_part = if how_much_current_part > how_much
      how_much
    else
      how_much_current_part
    end

    how_much_next_part = how_much - how_much_current_part

    current_part = @parts[@part_no].read(@part_offset, how_much_current_part )

    if how_much_next_part > 0
      @part_no += 1
      @part_offset = 0
      next_part = read ( how_much_next_part  )
      current_part + if next_part
        next_part
      else
        ''
      end
    else
      @part_offset += how_much_current_part
      current_part
    end
  end
end

Vue.JS: How to call function after page loaded?

You can use the mounted() Vue Lifecycle Hook. This will allow you to call a method before the page loads.

This is an implementation example:

HTML:

<div id="app">
  <h1>Welcome our site {{ name }}</h1>
</div>

JS:

var app = new Vue ({
    el: '#app',
    data: {
        name: ''
    },
    mounted: function() {
        this.askName() // Calls the method before page loads
    },
    methods: {
        // Declares the method
        askName: function(){
            this.name = prompt(`What's your name?`)
        }
    }
})

This will get the prompt method's value, insert it in the variable name and output in the DOM after the page loads. You can check the code sample here.

You can read more about Lifecycle Hooks here.

How do I Search/Find and Replace in a standard string?

Why not implement your own replace?

void myReplace(std::string& str,
               const std::string& oldStr,
               const std::string& newStr)
{
  std::string::size_type pos = 0u;
  while((pos = str.find(oldStr, pos)) != std::string::npos){
     str.replace(pos, oldStr.length(), newStr);
     pos += newStr.length();
  }
}

How to select distinct query using symfony2 doctrine query builder?

you could write

select DISTINCT f from t;

as

select f from t group by f;

thing is, I am just currently myself getting into Doctrine, so I cannot give you a real answer. but you could as shown above, simulate a distinct with group by and transform that into Doctrine. if you want add further filtering then use HAVING after group by.

Structs data type in php?

You can use an array

$something = array(
   'key' => 'value',
   'key2' => 'value2'
);

or with standard object.

$something = new StdClass();

$something->key = 'value';
$something->key2 = 'value2';

"java.lang.OutOfMemoryError: PermGen space" in Maven build

When you say you increased MAVEN_OPTS, what values did you increase? Did you increase the MaxPermSize, as in example:

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"

(or on Windows:)

set MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m

You can also specify these JVM options in each maven project separately.

Hive insert query like SQL

You can't do insert into to insert single record. It's not supported by Hive. You may place all new records that you want to insert in a file and load that file into a temp table in Hive. Then using insert overwrite..select command insert those rows into a new partition of your main Hive table. The constraint here is your main table will have to be pre partitioned. If you don't use partition then your whole table will be replaced with these new records.

What is the difference between angular-route and angular-ui-router?

Basic thing you have to know: ng-router uses $location.path() and ui-router uses $state.go

Rest us all features.

Sorting a vector of custom objects

You are on the right track. std::sort will use operator< as comparison function by default. So in order to sort your objects, you will either have to overload bool operator<( const T&, const T& ) or provide a functor that does the comparison, much like this:

 struct C {
    int i;
    static bool before( const C& c1, const C& c2 ) { return c1.i < c2.i; }
 };

 bool operator<( const C& c1, const C& c2 ) { return c1.i > c2.i; }

 std::vector<C> values;

 std::sort( values.begin(), values.end() ); // uses operator<
 std::sort( values.begin(), values.end(), C::before );

The advantage of the usage of a functor is that you can use a function with access to the class' private members.

Using Excel OleDb to get sheet names IN SHEET ORDER

Can't find this in actual MSDN documentation, but a moderator in the forums said

I am afraid that OLEDB does not preserve the sheet order as they were in Excel

Excel Sheet Names in Sheet Order

Seems like this would be a common enough requirement that there would be a decent workaround.

How to create own dynamic type or dynamic object in C#?

ExpandoObject is what are you looking for.

dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

CSS Inset Borders

To produce a border inset within an element the only solution I've found (and I've tried all the suggestions in this thread to no avail) is to use a pseudo-element such as :before

E.g.

.has-inset-border:before {
  content: "foo"; /* you need something or it will be invisible at least on Chrome */
  color: transparent;
  position: absolute;
  left: 10px;
  right: 10px;
  top: 10px;
  bottom: 10px;
  border: 4px dashed red;
}

The box-sizing property won't work, as the border always ends up outside everything.

The box-shadow options has the dual disadvantages of not really working and not being supported as widely (and costing more CPU cycles to render, if you care).

Python's most efficient way to choose longest string in list?

def longestWord(some_list): 
    count = 0    #You set the count to 0
    for i in some_list: # Go through the whole list
        if len(i) > count: #Checking for the longest word(string)
            count = len(i)
            word = i
    return ("the longest string is " + word)

or much easier:

max(some_list , key = len)

how to change a selections options based on another select option selected?

Your if statement is setting the value. You want to compare it by doing this

if ($("#type").val() == "item1") {
 ...
}

daLizard is right though. You want an event handler. document.ready runs only once, when the page DOM is ready to be used.

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

How to import keras from tf.keras in Tensorflow?

Try from tensorflow.python import keras

with this, you can easily change keras dependent code to tensorflow in one line change.

You can also try from tensorflow.contrib import keras. This works on tensorflow 1.3

Edited: for tensorflow 1.10 and above you can use import tensorflow.keras as keras to get keras in tensorflow.

Run Stored Procedure in SQL Developer?

Though this question is quite old, I keep stumbling into same result without finding an easy way to run from sql developer. After couple of tries, I found an easy way to execute the stored procedure from sql developer itself.

  • Under packages, select your desired package and right click on the package name (not on the stored procedure name).

  • You will find option to run. Select that and supply the required arguments. Click OK and you can see the output in output variables section below

I'm using SQL developer version 4.1.3.20

Android sqlite how to check if a record exists

SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.

if(cursor.getCount()<=0){
    Log.v("tag","if 1 "+cursor.getCount());
    return false;
}
Log.v("tag","2 else  "+cursor.getCount());

return true;

if you not use cursor.moveToLast();

cursor.getCount() always give same integer (1) or current position of cursor.

What is the use of static synchronized method in java?

At run time every loaded class has an instance of a Class object. That is the object that is used as the shared lock object by static synchronized methods. (Any synchronized method or block has to lock on some shared object.)

You can also synchronize on this object manually if wanted (whether in a static method or not). These three methods behave the same, allowing only one thread at a time into the inner block:

class Foo {
    static synchronized void methodA() {
        // ...
    }

    static void methodB() {
        synchronized (Foo.class) {
            // ...
        }
    }

    static void methodC() {
        Object lock = Foo.class;
        synchronized (lock) {
            // ...
        }
    }
}

The intended purpose of static synchronized methods is when you want to allow only one thread at a time to use some mutable state stored in static variables of a class.

Nowadays, Java has more powerful concurrency features, in java.util.concurrent and its subpackages, but the core Java 1.0 constructs such as synchronized methods are still valid and usable.

VARCHAR to DECIMAL

Implemented using Custom Function. This will check whether the string value can be converted to Decimal safely

CREATE FUNCTION [dbo].[TryParseAsDecimal]
(
    @Value      NVARCHAR(4000)
    ,@Precision INT
    ,@Scale     INT
)

RETURNS BIT
AS
BEGIN

    IF(ISNUMERIC(@Value) =0) BEGIN
        RETURN CAST(0 AS BIT)
    END
    SELECT @Value = REPLACE(@Value,',','') --Removes the comma

    --This function validates only the first part eg '1234567.8901111111'
    --It validates only the values before the '.' ie '1234567.'
    DECLARE @Index          INT
    DECLARE @Part1Length    INT 
    DECLARE @Part1          VARCHAR(4000)   

    SELECT @Index = CHARINDEX('.', @Value, 0)
    IF (@Index>0) BEGIN
        --If decimal places, extract the left part only and cast it to avoid leading zeros (eg.'0000000001' => '1')
        SELECT @Part1 =LEFT(@Value, @Index-1);
        SELECT @Part1=SUBSTRING(@Part1, PATINDEX('%[^0]%', @Part1+'.'), LEN(@Part1));
        SELECT @Part1Length = LEN(@Part1);
    END
    ELSE BEGIN
        SELECT @Part1 =CAST(@Value AS DECIMAL);
        SELECT @Part1Length= LEN(@Part1)
    END 

    IF (@Part1Length > (@Precision-@Scale)) BEGIN
        RETURN CAST(0 AS BIT)
    END

    RETURN CAST(1 AS BIT)

END

How is a tag different from a branch in Git? Which should I use, here?

I like to think of branches as where you're going, tags as where you've been.

A tag feels like a bookmark of a particular important point in the past, such as a version release.

Whereas a branch is a particular path the project is going down, and thus the branch marker advances with you. When you're done you merge/delete the branch (i.e. the marker). Of course, at that point you could choose to tag that commit.

How to create a static library with g++?

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

How to return part of string before a certain character?

You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:

str.substring(0, str.indexOf(":"));

Where 'str' represents the variable with your string inside.

Click here for JSFiddle Example

Javascript

var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');

var left_text = input_string.substring(0, input_string.indexOf(":"));

output_element.innerText = left_text;

Html

<p>
  <h5>Input:</h5>
  <strong id="my-input">Left Text:Right Text</strong>
  <h5>Output:</h5>
  <strong id="my-output">XXX</strong>
</p>

CSS

body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
  width:90%;
  padding: 0.5em 1em;
  background-color: cyan;
}
#my-output { background-color: gold; }

Generating a UUID in Postgres for Insert statement?

PostgreSQL 13 supports natively gen_random_uuid ():

PostgreSQL includes one function to generate a UUID:

gen_random_uuid () ? uuid

This function returns a version 4 (random) UUID. This is the most commonly used type of UUID and is appropriate for most applications.

db<>fiddle demo

Load content of a div on another page

Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.

In short, you add the selector after the URL. For example:

$('#result').load('ajax/test.html #container');

Can I simultaneously declare and assign a variable in VBA?

You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

Python element-wise tuple operations like sum

simple solution without class definition that returns tuple

import operator
tuple(map(operator.add,a,b))

Export result set on Dbeaver to CSV

You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :

  1. Execute your query
  2. Right click any anywhere in the results
  3. click "Export resultset..." to open the export wizard
  4. Choose the format you want (CSV according to your question)
  5. Review the settings in the next panes when clicking "Next".
  6. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.


In newer versions of DBeaver you can just :

  1. right click the SQL of the query you want to export
  2. Execute > Export from query
  3. Choose the format you want (CSV according to your question)
  4. Review the settings in the next panes when clicking "Next".
  5. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.

Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.

How do I repair an InnoDB table?

Step 1.

Stop MySQL server

Step 2.

add this line to my.cnf ( In windows it is called my.ini )

set-variable=innodb_force_recovery=6

Step 3.

delete ib_logfile0 and ib_logfile1

Step 4.

Start MySQL server

Step 5.

Run this command:

mysqlcheck --database db_name table_name -uroot -p

After you have successfully fixed the crashed innodb table, don't forget to remove #set-variable=innodb_force_recovery=6 from my.cnf and then restart MySQL server again.

Why is there no String.Empty in Java?

Seems like this is the obvious answer:

String empty = org.apache.commons.lang.StringUtils.EMPTY;

Awesome because "empty initialization" code no longer has a "magic string" and uses a constant.

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

gitignore all files of extension in directory

I believe the simplest solution would be to use find. I do not like to have multiple .gitignore hanging around in sub-directories and I prefer to manage a unique, top-level .gitignore. To do so you could simply append the found files to your .gitignore. Supposing that /public/static/ is your project/git home I would use something like:

find . -type f -name *.js | cut -c 3- >> .gitignore

I found that cutting out the ./ at the beginning is often necessary for git to understand which files to avoid. Therefore the cut -c 3-.

INSERT INTO vs SELECT INTO

Select into creates new table for you at the time and then insert records in it from the source table. The newly created table has the same structure as of the source table.If you try to use select into for a existing table it will produce a error, because it will try to create new table with the same name. Insert into requires the table to be exist in your database before you insert rows in it.

How do I find my host and username on mysql?

Default user for MySQL is "root", and server "localhost".

LINUX: Link all files from one to another directory

The posted solutions will not link any hidden files. To include them, try this:

cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib not /mnt/usr/lib), you could do this:

cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

Java math function to convert positive int to negative and negative to positive?

We can reverse Java number int or double using this :

int x = 5;
int y = -7;

x = x - (x*2); // reverse to negative
y = y - (y*2); // reverse to positif

Simple algorithm to reverse number :)

Add an image in a WPF button

Use:

<Button Height="100" Width="100">
  <StackPanel>
    <Image Source="img.jpg" />
    <TextBlock Text="Blabla" />
  </StackPanel>
</Button>

It should work. But remember that you must have an image added to the resource on your project!

Removing Data From ElasticSearch

You can delete an index in python as follows

from elasticsearch import Elasticsearch

es = Elasticsearch([{'host':'localhost', 'port':'9200'}])

es.index(index='grades',doc_type='ist_samester',id=1,body={
    "Name":"Programming Fundamentals",
    "Grade":"A"
})

es.indices.delete(index='grades')

How to get Python requests to trust a self signed SSL certificate?

try:

r = requests.post(url, data=data, verify='/path/to/public_key.pem')

Submit a form in a popup, and then close the popup

Here's how I ended up doing this:

        <div id="divform">
            <form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
                <div>Certificate 1: <input type="file" name="cert1"/></div>
                <div>Certificate 2: <input type="file" name="cert2"/></div>

                <div><input type="button" value="Upload" onclick="closeSelf();"/></div>
            </form>
        </div>
        <div  id="closelink" style="display:none">
            <a href="javascript:window.close()">Click Here to Close this Page</a>
        </div>

function closeSelf(){
    document.forms['certform'].submit();
    hide(document.getElementById('divform'));
    unHide(document.getElementById('closelink'));

}

Where hide() and unhide() set the style.display to 'none' and 'block' respectively.

Not exactly what I had in mind, but this will have to do for the time being. Works on IE, Safari, FF and Chrome.

Can I convert long to int?

The following solution will truncate to int.MinValue/int.MaxValue if the value is out of Integer bounds.

myLong < int.MinValue ? int.MinValue : (myLong > int.MaxValue ? int.MaxValue : (int)myLong)

Node.js: how to consume SOAP XML web service

I managed to use soap,wsdl and Node.js You need to install soap with npm install soap

Create a node server called server.js that will define soap service to be consumed by a remote client. This soap service computes Body Mass Index based on weight(kg) and height(m).

const soap = require('soap');
const express = require('express');
const app = express();
/**
 * this is remote service defined in this file, that can be accessed by clients, who will supply args
 * response is returned to the calling client
 * our service calculates bmi by dividing weight in kilograms by square of height in metres
 */
const service = {
  BMI_Service: {
    BMI_Port: {
      calculateBMI(args) {
        //console.log(Date().getFullYear())
        const year = new Date().getFullYear();
        const n = args.weight / (args.height * args.height);
        console.log(n);
        return { bmi: n };
      }
    }
  }
};
// xml data is extracted from wsdl file created
const xml = require('fs').readFileSync('./bmicalculator.wsdl', 'utf8');
//create an express server and pass it to a soap server
const server = app.listen(3030, function() {
  const host = '127.0.0.1';
  const port = server.address().port;
});
soap.listen(server, '/bmicalculator', service, xml);

Next, create a client.js file that will consume soap service defined by server.js. This file will provide arguments for the soap service and call the url with SOAP's service ports and endpoints.

const express = require('express');
const soap = require('soap');
const url = 'http://localhost:3030/bmicalculator?wsdl';
const args = { weight: 65.7, height: 1.63 };
soap.createClient(url, function(err, client) {
  if (err) console.error(err);
  else {
    client.calculateBMI(args, function(err, response) {
      if (err) console.error(err);
      else {
        console.log(response);
        res.send(response);
      }
    });
  }
});

Your wsdl file is an xml based protocol for data exchange that defines how to access a remote web service. Call your wsdl file bmicalculator.wsdl

<definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl" 
  xmlns="http://schemas.xmlsoap.org/wsdl/" 
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
  xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <message name="getBMIRequest">
    <part name="weight" type="xsd:float"/>
    <part name="height" type="xsd:float"/>
  </message>

  <message name="getBMIResponse">
    <part name="bmi" type="xsd:float"/>
  </message>

  <portType name="Hello_PortType">
    <operation name="calculateBMI">
      <input message="tns:getBMIRequest"/>
      <output message="tns:getBMIResponse"/>
    </operation>
  </portType>

  <binding name="Hello_Binding" type="tns:Hello_PortType">
    <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="calculateBMI">
      <soap:operation soapAction="calculateBMI"/>
      <input>
        <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
      </input>
      <output>
        <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
      </output>
    </operation>
  </binding>

  <service name="BMI_Service">
    <documentation>WSDL File for HelloService</documentation>
    <port binding="tns:Hello_Binding" name="BMI_Port">
      <soap:address location="http://localhost:3030/bmicalculator/" />
    </port>
  </service>
</definitions>

Hope it helps

How to call a C# function from JavaScript?

Use Blazor http://learn-blazor.com/architecture/interop/

Here's the C#:

namespace BlazorDemo.Client
{
   public static class MyCSharpFunctions
   {
       public static void CsharpFunction()
       {
          // Notification.show();
       }
   }
}

Then the Javascript:

const CsharpFunction = Blazor.platform.findMethod(
"BlazorDemo.Client",
"BlazorDemo.Client",
"MyCSharpFunctions",
"CsharpFunction"
);
if (Javascriptcondition > 0) {
   Blazor.platform.callMethod(CsharpFunction, null)
}

Remove composer

If you install the composer as global on Ubuntu, you just need to find the composer location.

Use command

type composer

or

where composer

For Mac users, use command:

which composer

and then just remove the folder using rm command.

jQuery .ready in a dynamically inserted iframe

Found the solution to the problem.

When you click on a thickbox link that open a iframe, it insert an iframe with an id of TB_iframeContent.

Instead of relying on the $(document).ready event in the iframe code, I just have to bind to the load event of the iframe in the parent document:

$('#TB_iframeContent', top.document).load(ApplyGalleria);

This code is in the iframe but binds to an event of a control in the parent document. It works in FireFox and IE.

An item with the same key has already been added

I had the same issue , i was foreach looping over my object and adding the result into a Dictionary<string, string> and i had a `Duplicate in the key from the database

 foreach (var item in myObject)
        {
            myDictionary.Add(Convert.ToString(item.x), 
                                   item.y);

        }

item.x had a duplicate value

How to run a python script from IDLE interactive shell?

In IDLE, the following works :-

_x000D_
_x000D_
import helloworld
_x000D_
_x000D_
_x000D_

I don't know much about why it works, but it does..

How do I get the full url of the page I am on in C#

Request.Url.AbsoluteUri

This property does everything you need, all in one succinct call.

How to find length of digits in an integer?

It's been several years since this question was asked, but I have compiled a benchmark of several methods to calculate the length of an integer.

def libc_size(i): 
    return libc.snprintf(buf, 100, c_char_p(b'%i'), i) # equivalent to `return snprintf(buf, 100, "%i", i);`

def str_size(i):
    return len(str(i)) # Length of `i` as a string

def math_size(i):
    return 1 + math.floor(math.log10(i)) # 1 + floor of log10 of i

def exp_size(i):
    return int("{:.5e}".format(i).split("e")[1]) + 1 # e.g. `1e10` -> `10` + 1 -> 11

def mod_size(i):
    return len("%i" % i) # Uses string modulo instead of str(i)

def fmt_size(i):
    return len("{0}".format(i)) # Same as above but str.format

(the libc function requires some setup, which I haven't included)

size_exp is thanks to Brian Preslopsky, size_str is thanks to GeekTantra, and size_math is thanks to John La Rooy

Here are the results:

Time for libc size:      1.2204 µs
Time for string size:    309.41 ns
Time for math size:      329.54 ns
Time for exp size:       1.4902 µs
Time for mod size:       249.36 ns
Time for fmt size:       336.63 ns
In order of speed (fastest first):
+ mod_size (1.000000x)
+ str_size (1.240835x)
+ math_size (1.321577x)
+ fmt_size (1.350007x)
+ libc_size (4.894290x)
+ exp_size (5.976219x)

(Disclaimer: the function is run on inputs 1 to 1,000,000)

Here are the results for sys.maxsize - 100000 to sys.maxsize:

Time for libc size:      1.4686 µs
Time for string size:    395.76 ns
Time for math size:      485.94 ns
Time for exp size:       1.6826 µs
Time for mod size:       364.25 ns
Time for fmt size:       453.06 ns
In order of speed (fastest first):
+ mod_size (1.000000x)
+ str_size (1.086498x)
+ fmt_size (1.243817x)
+ math_size (1.334066x)
+ libc_size (4.031780x)
+ exp_size (4.619188x)

As you can see, mod_size (len("%i" % i)) is the fastest, slightly faster than using str(i) and significantly faster than others.

jQuery selector for the label of a checkbox

Another solution could be:

$("#comedyclubs").next()

How do I export (and then import) a Subversion repository?

Excerpt from my Blog-Note-to-myself:

Now you can import a dump file e.g. if you are migrating between machines / subversion versions. e.g. if I had created a dump file from the source repository and load it into the new repository as shown below.

Commands for Unix-like systems (from terminal):

svnadmin dump /path/to/your/old/repo > backup.dump
svnadmin load /path/to/your/new/repo < backup.dump.dmp

Commands for Microsoft Windows systems (from cmd shell):

svnadmin dump C:\path\to\your\old\repo > backup.dump
svnadmin load C:\path\to\your\old\repo < backup.dump

I have created a table in hive, I would like to know which directory my table is created in?

Further to pensz answer you can get more info using:

DESCRIBE EXTENDED my_table;

or

DESCRIBE EXTENDED my_table PARTITION (my_column='my_value');

Text in a flex container doesn't wrap in IE11

Add this to your code:

.child { width: 100%; }

We know that a block-level child is supposed to occupy the full width of the parent.

Chrome understands this.

IE11, for whatever reason, wants an explicit request.

Using flex-basis: 100% or flex: 1 also works.

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 400px;_x000D_
  border: 1px solid red;_x000D_
  align-items: center;_x000D_
}_x000D_
.child {_x000D_
  border: 1px solid blue;_x000D_
  width: calc(100% - 2px);       /* NEW; used calc to adjust for parent borders */_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">_x000D_
    Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
  </div>_x000D_
  <div class="child">_x000D_
    Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note: Sometimes it will be necessary to sort through the various levels of the HTML structure to pinpoint which container gets the width: 100%. CSS wrap text not working in IE

How to iterate over array of objects in Handlebars?

Using this and {{this}}. See code below in node.js:

var Handlebars= require("handlebars");
var randomList= ["James Bond", "Dr. No", "Octopussy", "Goldeneye"];
var source= "<ul>{{#each this}}<li>{{this}}</li>{{/each}}</ul>";
var template= Handlebars.compile(source);
console.log(template(randomList));

Console log output:

<ul><li>James Bond</li><li>Dr. No</li><li>Octopussy</li><li>Goldeneye</li></ul>

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax. Having fig is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')). You certainly don't have to use the returned figure object but many people do use it later so it's common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:

fig, ax = plt.subplots()

is more concise than this:

fig = plt.figure()
ax = fig.add_subplot(111)

Split column at delimiter in data frame

strsplit(c('a|b','b|c'),'|',fixed=TRUE)

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

Dismissing a Presented View Controller

Updated for Swift 3

I came here just wanting to dismiss the current (presented) View Controller. I'm making this answer for anyone coming here with the same purpose.

Navigation Controller

If you are using a navigation controller, then it is quite easy.

Go back to the previous view controller:

// Swift
self.navigationController?.popViewController(animated: true)

// Objective-C
[self.navigationController popViewControllerAnimated:YES];

Go back to the root view controller:

// Swift
self.navigationController?.popToRootViewController(animated: true)

// Objective-C
[self.navigationController popToRootViewControllerAnimated:YES];

(Thanks to this answer for the Objective-C.)

Modal View Controller

When a View Controller is presented modally, you can dismiss it (from the second view controller) by calling

// Swift
self.dismiss(animated: true, completion: nil)

// Objective-C
[self dismissViewControllerAnimated:YES completion:nil];

The documentation says,

The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.

So it works for the presented view controller to call it on itself. Here is a full example.

Delegates

The OP's question was about the complexity of using delegates to dismiss a view.

To this point I have not needed to use delegates since I usually have a navigation controller or modal view controllers, but if I do need to use the delegate pattern in the future, I will add an update.

Get first 100 characters from string, respecting full words

This works fine for me, I use it in my script

<?PHP
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!";
$small = some_function($big);
echo $small;

function some_function($string){
     $string = substr($string,0,100);
     $string = substr($string,0,strrpos($string," "));
     return $string;
}
?>

good luck

Update Jenkins from a war file

We run jenkins from the .war file with the following command.

java -Xmx2500M -jar jenkins.war --httpPort=3333 --prefix=/jenkins

You can even run the command from the ~/Downloads directory

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

I found it hard to decipher what is meant by "working directory of the VM". In my example, I was using the Java Service Wrapper program to execute a jar - the dump files were created in the directory where I had placed the wrapper program, e.g. c:\myapp\bin. The reason I discovered this is because the files can be quite large and they filled up the hard drive before I discovered their location.

How to scroll up or down the page to an anchor using jQuery?

Here is the solution that worked for me. This is a generic function which works for all of the a tags referring to a named a

$("a[href^=#]").on('click', function(event) { 
    event.preventDefault(); 
    var name = $(this).attr('href'); 
    var target = $('a[name="' + name.substring(1) + '"]'); 
    $('html,body').animate({ scrollTop: $(target).offset().top }, 'slow'); 
});

Note 1: Make sure that you use double quotes " in your html. If you use single quotes, change the above part of the code to var target = $("a[name='" + name.substring(1) + "']");

Note 2: In some cases, especially when you use the sticky bar from the bootstrap, the named a will hide beneath the navigation bar. In those cases (or any similar case), you can reduce the number of the pixels from your scroll to achieve the optimal location. For example: $('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow'); will take you to the target with 15 pixels left on the top.

How do I disable the resizable property of a textarea?

In reactjs, you can disable the resize widget using style props.

<textarea id={"multiline-id"} ref={'my-ref'} style={{resize: "none"}} className="text-area-additional-styles" />

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

jQuery Set Selected Option Using Next

From version 1.6.1 on, it's advisable to use the method prop for boolean attributes/properties such as selected, readonly, enabled,...

var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);

For more info, please refer to to http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/

What is the path that Django uses for locating and loading templates?

I also had issues with this part of the tutorial (used tutorial for version 1.7).

My mistake was that I only edited the 'Django administration' string, and did not pay enough attention to the manual.

This is the line from django/contrib/admin/templates/admin/base_site.html:

<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>

But after some time and frustration it became clear that there was the 'site_header or default:_' statement, which should be removed. So after removing the statement (like the example in the manual everything worked like expected).

Example manual:

<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>

How to read if a checkbox is checked in PHP?

Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set

Example:

    if(isset($_POST["testvariabel"]))
     {
       echo "testvariabel has been set!";
     }

How do I solve this "Cannot read property 'appendChild' of null" error?

Your condition id !== 0 will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null error.

Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
    if (container !== null) {
        container.appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
    if (container !== null) {
        container.appendChild(elem1);
    } else console.log("aaaaa");
}

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We had this error on Oracle RAC 11g on Windows, and the solution was to create the same OS directory tree and external file on both nodes.

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

    public ActionResult ActionName(string ReqParam1, string ReqParam2, string ReqParam3, string ReqParam4)
    {
        this.ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin","*");
         /*
                --Your code goes here --
         */
        return Json(new { ReturnData= "Data to be returned", Success=true }, JsonRequestBehavior.AllowGet);
    }

How to convert number of minutes to hh:mm format in TSQL?

For those who need convert minutes to time with more than 24h format:

DECLARE @minutes int = 7830
SELECT CAST(@minutes / 60 AS VARCHAR(8)) + ':' + FORMAT(@minutes % 60, 'D2') AS [Time]

Result:

130:30

Can an html element have multiple ids?

No. Every DOM element, if it has an id, has a single, unique id. You could approximate it using something like:

<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>

and then use navigation to get what you really want.

If you are just looking to apply styles, class names are better.

Prevent flicker on webkit-transition of webkit-transform

The rule:

-webkit-backface-visibility: hidden;

will not work for sprites or image backgrounds.

body {-webkit-transform:translate3d(0,0,0);}

screws up backgrounds that are tiled.

I prefer to make a class called no-flick and do this:

.no-flick{-webkit-transform:translate3d(0,0,0);}

pandas: filter rows of DataFrame with operator chaining

Filters can be chained using a Pandas query:

df = pd.DataFrame(np.random.randn(30, 3), columns=['a','b','c'])
df_filtered = df.query('a > 0').query('0 < b < 2')

Filters can also be combined in a single query:

df_filtered = df.query('a > 0 and 0 < b < 2')

Foreach with JSONArray and JSONObject

Apparently, org.json.simple.JSONArray implements a raw Iterator. This means that each element is considered to be an Object. You can try to cast:

for(Object o: arr){
    if ( o instanceof JSONObject ) {
        parse((JSONObject)o);
    }
}

This is how things were done back in Java 1.4 and earlier.

Zoom to fit all markers in Mapbox or Leaflet

Leaflet also has LatLngBounds that even has an extend function, just like google maps.

http://leafletjs.com/reference.html#latlngbounds

So you could simply use:

var latlngbounds = new L.latLngBounds();

The rest is exactly the same.

Create a day-of-week column in a Pandas dataframe using Python

df =df['Date'].dt.dayofweek

dayofweek is in numeric format

Setting the default active profile in Spring-boot

I do it this way

    System.setProperty("spring.profiles.default", "dev");

in the very beginning of main(...)

ERROR 1049 (42000): Unknown database 'mydatabasename'

If dump file contains:

CREATE DATABASE mydatabasename;
USE mydatabasename; 

You may just use in CLI:

mysql -uroot –pmypassword < mydatabase.sql

It works.

Android center view in FrameLayout doesn't work

I'd suggest a RelativeLayout instead of a FrameLayout.

Assuming that you want to have the TextView always below the ImageView I'd use following layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:src="@drawable/icon"
        android:visibility="visible"/>
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_below="@id/imageview"
        android:gravity="center"
        android:text="@string/hello"/>
</RelativeLayout>

Note that if you set the visibility of an element to gone then the space that element would consume is gone whereas when you use invisible instead the space it'd consume will be preserved.

If you want to have the TextView on top of the ImageView then simply leave out the android:layout_alignParentTop or set it to false and on the TextView leave out the android:layout_below="@id/imageview" attribute. Like this.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="false"
        android:layout_centerInParent="true"
        android:src="@drawable/icon"
        android:visibility="visible"/>
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="@string/hello"/>
</RelativeLayout>

I hope this is what you were looking for.

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.

var n = 5;
for (int i = 0; i < n; i++)
{
    //Create label
    Label label = new Label();
    label.Text = String.Format("Label {0}", i);
    //Position label on screen
    label.Left = 10;
    label.Top = (i + 1) * 20;
    //Create textbox
    TextBox textBox = new TextBox();
    //Position textbox on screen
    textBox.Left = 120;
    textBox.Top = (i + 1) * 20;
    //Add controls to form
    this.Controls.Add(label);
    this.Controls.Add(textBox);
}

This will not only add them to the form but position them decently as well.

Converting Hexadecimal String to Decimal Integer

You could take advantage of ASCII value for each letter and take off 55, easy and fast:

int asciiOffset = 55;
char hex = Character.toUpperCase('A');  // Only A-F uppercase
int val = hex - asciiOffset;
System.out.println("hexadecimal:" + hex);
System.out.println("decimal:" + val);

Output:
hexadecimal:A
decimal:10

Order by in Inner Join

Avoid SELECT * in your main query.

Avoid duplicate columns: the JOIN condition ensures One.One_Name and two.One_Name will be equal therefore you don't need to return both in the SELECT clause.

Avoid duplicate column names: rename One.ID and Two.ID using 'aliases'.

Add an ORDER BY clause using the column names ('alises' where applicable) from the SELECT clause.

Suggested re-write:

SELECT T1.ID AS One_ID, T1.One_Name, 
       T2.ID AS Two_ID, T2.Two_name
  FROM One AS T1
       INNER JOIN two AS T2
          ON T1.One_Name = T2.One_Name
 ORDER 
    BY One_ID;

Convert line endings

Doing this with POSIX is tricky:

  • POSIX Sed does not support \r or \15. Even if it did, the in place option -i is not POSIX

  • POSIX Awk does support \r and \15, however the -i inplace option is not POSIX

  • d2u and dos2unix are not POSIX utilities, but ex is

  • POSIX ex does not support \r, \15, \n or \12

To remove carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file

To add carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

In Python, what is the difference between ".append()" and "+= []"?

In addition to the aspects described in the other answers, append and +[] have very different behaviors when you're trying to build a list of lists.

>>> list1=[[1,2],[3,4]]
>>> list2=[5,6]
>>> list3=list1+list2
>>> list3
[[1, 2], [3, 4], 5, 6]
>>> list1.append(list2)
>>> list1
[[1, 2], [3, 4], [5, 6]]

list1+['5','6'] adds '5' and '6' to the list1 as individual elements. list1.append(['5','6']) adds the list ['5','6'] to the list1 as a single element.

How do I get the full path of the current file's directory?

IPython has a magic command %pwd to get the present working directory. It can be used in following way:

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

On IPython Jupyter Notebook %pwd can be used directly as following:

present_working_directory = %pwd

How to get all selected values of a multiple select box?

Same as the earlier answer but using underscore.js.

function getSelectValues(select) {
    return _.map(_.filter(select.options, function(opt) { 
        return opt.selected; }), function(opt) { 
            return opt.value || opt.text; });
}

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
print "Please choose what you'd like to do:"

print "0: Addition"
print "1: Subtraction"
print "2: Multiplication"
print "3: Division"
print "4: Quit Application"



#Capture the menu choice.
choice = raw_input()    

if choice == "0":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(addition(numberA, numberB)) + "\n"
elif choice == "1":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(subtraction(numberA, numberB)) + "\n"
elif choice == "2":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(multiplication(numberA, numberB)) + "\n"
elif choice == "3":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(division(numberA, numberB)) + "\n"
elif choice == "4":
    print "Bye!"
    keepProgramRunning = False
else:
    print "Please choose a valid option."
    print "\n"

In R, how to find the standard error of the mean?

The package sciplot has the built-in function se(x)

React component initialize state from props

Update for React 16.3 alpha introduced static getDerivedStateFromProps(nextProps, prevState) (docs) as a replacement for componentWillReceiveProps.

getDerivedStateFromProps is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.

Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. You may want to compare new and previous values if you only want to handle changes.

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

It is static, therefore it does not have direct access to this (however it does have access to prevState, which could store things normally attached to this e.g. refs)

edited to reflect @nerfologist's correction in comments

How long to brute force a salted SHA-512 hash? (salt provided)

There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

What is Shelving in TFS?

If you're using Gated builds, when a build is triggered, it creates a shelveset of your workspace that is submitted for build. If the build fails, the shelveset is rejected. If the build is successful, a changeset is created and committed to TFS. In either event, the person doing that check-in/build will have to reconcile the workspace, which is as simple as performing a Get Latest.

Is there a way to reduce the size of the git folder?

yes yes, git gc is the solution, naturally,

and locally - you can just delete the local repository and clone it again,

but there is something more important here...

the seconds you wait for that huge git & externals to process are collected to long minutes in which are collected to hours of inefficient time spent,

Create a new (entirely, not just a branch) repository from scratch, including the only recent version of files, naturally you'll loose all the history,

but when in code-world it is not time to get sentimental, there is no point dragging along the entire 5 years of code every commit or diff, you can still store the old git & externals somewhere, if you get nostalgic :]

but, at some point you really have to move along :]

your team will thank you!

Matplotlib color according to class labels

The accepted answer has it spot on, but if you might want to specify which class label should be assigned to a specific color or label you could do the following. I did a little label gymnastics with the colorbar, but making the plot itself reduces to a nice one-liner. This works great for plotting the results from classifications done with sklearn. Each label matches a (x,y) coordinate.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = [4,8,12,16,1,4,9,16]
y = [1,4,9,16,4,8,12,3]
label = [0,1,2,3,0,1,2,3]
colors = ['red','green','blue','purple']

fig = plt.figure(figsize=(8,8))
plt.scatter(x, y, c=label, cmap=matplotlib.colors.ListedColormap(colors))

cb = plt.colorbar()
loc = np.arange(0,max(label),max(label)/float(len(colors)))
cb.set_ticks(loc)
cb.set_ticklabels(colors)

Scatter plot color labels

Using a slightly modified version of this answer, one can generalise the above for N colors as follows:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

N = 23 # Number of labels

# setup the plot
fig, ax = plt.subplots(1,1, figsize=(6,6))
# define the data
x = np.random.rand(1000)
y = np.random.rand(1000)
tag = np.random.randint(0,N,1000) # Tag each point with a corresponding label    

# define the colormap
cmap = plt.cm.jet
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

# define the bins and normalize
bounds = np.linspace(0,N,N+1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x,y,c=tag,s=np.random.randint(100,500,N),cmap=cmap,     norm=norm)
# create the colorbar
cb = plt.colorbar(scat, spacing='proportional',ticks=bounds)
cb.set_label('Custom cbar')
ax.set_title('Discrete color mappings')
plt.show()

Which gives:

enter image description here

Angular 2 Show and Hide an element

For child component to show I was using *ngif="selectedState == 1"

Instead of that I used [hidden]="selectedState!=1"

It worked for me.. loading the child component properly and after hide and un-hide child component was not undefined after using this.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Return JsonResult from web api without its properties

I had a similar problem (differences being I wanted to return an object that was already converted to a json string and my controller get returns a IHttpActionResult)

Here is how I solved it. First I declared a utility class

public class RawJsonActionResult : IHttpActionResult
{
    private readonly string _jsonString;

    public RawJsonActionResult(string jsonString)
    {
        _jsonString = jsonString;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var content = new StringContent(_jsonString);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
        return Task.FromResult(response);
    }
}

This class can then be used in your controller. Here is a simple example

public IHttpActionResult Get()
{
    var jsonString = "{\"id\":1,\"name\":\"a small object\" }";
    return new RawJsonActionResult(jsonString);
}

How to disassemble a binary executable in Linux to get the assembly code?

You can come pretty damn close (but no cigar) to generating assembly that will reassemble, if that's what you are intending to do, using this rather crude and tediously long pipeline trick (replace /bin/bash with the file you intend to disassemble and bash.S with what you intend to send the output to):

objdump --no-show-raw-insn -Matt,att-mnemonic -Dz /bin/bash | grep -v "file format" | grep -v "(bad)" | sed '1,4d' | cut -d' ' -f2- | cut -d '<' -f2 | tr -d '>' | cut -f2- | sed -e "s/of\ section/#Disassembly\ of\ section/" | grep -v "\.\.\." > bash.S

Note how long this is, however. I really wish there was a better way (or, for that matter, a disassembler capable of outputting code that an assembler will recognize), but unfortunately there isn't.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How to split a large text file into smaller files with equal number of lines?

use split

Split a file into fixed-size pieces, creates output files containing consecutive sections of INPUT (standard input if none is given or INPUT is `-')

Syntax split [options] [INPUT [PREFIX]]

http://ss64.com/bash/split.html

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

The resolution to this problem for me, was to notify the sender that he did use the Public key that I sent them but rather someone elses. You should see the key that they used. Tell them to use the correct one.

How to install sshpass on mac?

Solution provided by lukesUbuntu from github works for me:

Just use brew

$ brew install http://git.io/sshpass.rb

Weird behavior of the != XPath operator

If $AccountNumber or $Balance is a node-set, then this behavior could easily happen. It's not because and is being treated as or.

For example, if $AccountNumber referred to nodes with the values 12345 and 66 and $Balance referred to nodes with the values 55 and 0, then $AccountNumber != '12345' would be true (because 66 is not equal to 12345) and $Balance != '0' would be true (because 55 is not equal to 0).

I'd suggest trying this instead:

<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">

$AccountNumber = '12345' or $Balance = '0' will be true any time there is an $AccountNumber with the value 12345 or there is a $Balance with the value 0, and if you apply not() to that, you will get a false result.

Android Relative Layout Align Center

This will definately work for you.

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/top_bg" >

    <Button
        android:id="@+id/btn_report_lbAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="@dimen/btn_back_margin_left"
        android:background="@drawable/btn_edit" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:text="FlitsLimburg"
        android:textColor="@color/white"
        android:textSize="@dimen/tv_header_text"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_refresh_lbAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="@dimen/btn_back_margin_right"
        android:background="@drawable/btn_refresh" />
</RelativeLayout>

Merge PDF files

Use Pypdf or its successor PyPDF2:

A Pure-Python library built as a PDF toolkit. It is capable of:
* splitting documents page by page,
* merging documents page by page,

(and much more)

Here's a sample program that works with both versions.

#!/usr/bin/env python
import sys
try:
    from PyPDF2 import PdfFileReader, PdfFileWriter
except ImportError:
    from pyPdf import PdfFileReader, PdfFileWriter

def pdf_cat(input_files, output_stream):
    input_streams = []
    try:
        # First open all the files, then produce the output file, and
        # finally close the input files. This is necessary because
        # the data isn't read from the input files until the write
        # operation. Thanks to
        # https://stackoverflow.com/questions/6773631/problem-with-closing-python-pypdf-writing-getting-a-valueerror-i-o-operation/6773733#6773733
        for input_file in input_files:
            input_streams.append(open(input_file, 'rb'))
        writer = PdfFileWriter()
        for reader in map(PdfFileReader, input_streams):
            for n in range(reader.getNumPages()):
                writer.addPage(reader.getPage(n))
        writer.write(output_stream)
    finally:
        for f in input_streams:
            f.close()

if __name__ == '__main__':
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    pdf_cat(sys.argv[1:], sys.stdout)

Get JavaScript object from array of objects by value of property

Try Array filter method for filter the array of objects with property.

var jsObjects = [
   {a: 1, b: 2}, 
   {a: 3, b: 4}, 
   {a: 5, b: 6}, 
   {a: 7, b: 8}
];

using array filter method:

var filterObj = jsObjects.filter(function(e) {
  return e.b == 6;
});

using for in loop :

for (var i in jsObjects) {
  if (jsObjects[i].b == 6) {
    console.log(jsObjects[i]); // {a: 5, b: 6}
  }
}

Working fiddle : https://jsfiddle.net/uq9n9g77/

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

see 5.5.x with the integrated OPcache module, volatile in a shared memory, much more performance and the dynamism principle of php remain untouched.

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

Insert Update trigger how to determine if insert or update

i do this:

select isnull((select top 1 1 from inserted t1),0) + isnull((select top 1 2 from deleted t1),0)

1 -> insert

2 -> delete

3 -> update

set @i = isnull((select top 1 1 from inserted t1),0) + isnull((select top 1 2 from deleted t1),0)
--select @i

declare @action varchar(1) = case @i when 1 then 'I' when 2 then 'D' when 3 then 'U' end
--select @action


select @action c1,* from inserted t1 where @i in (1,3) union all
select @action c1,* from deleted t1 where @i in (2)

MySQL add days to a date

UPDATE table SET nameofdatefield = ADDDATE(nameofdatefield, 2) WHERE ...

jQuery: Uncheck other checkbox on one checked

Bind a change handler, then just uncheck all of the checkboxes, apart from the one checked:

$('input.example').on('change', function() {
    $('input.example').not(this).prop('checked', false);  
});

Here's a fiddle

Getting a list of all subdirectories in the current directory

Much nicer than the above, because you don't need several os.path.join() and you will get the full path directly (if you wish), you can do this in Python 3.5 and above.

subfolders = [ f.path for f in os.scandir(folder) if f.is_dir() ]

This will give the complete path to the subdirectory. If you only want the name of the subdirectory use f.name instead of f.path

https://docs.python.org/3/library/os.html#os.scandir


Slightly OT: In case you need all subfolder recursively and/or all files recursively, have a look at this function, that is faster than os.walk & glob and will return a list of all subfolders as well as all files inside those (sub-)subfolders: https://stackoverflow.com/a/59803793/2441026

In case you want only all subfolders recursively:

def fast_scandir(dirname):
    subfolders= [f.path for f in os.scandir(dirname) if f.is_dir()]
    for dirname in list(subfolders):
        subfolders.extend(fast_scandir(dirname))
    return subfolders

Returns a list of all subfolders with their full paths. This again is faster than os.walk and a lot faster than glob.


An analysis of all functions

tl;dr:
- If you want to get all immediate subdirectories for a folder use os.scandir.
- If you want to get all subdirectories, even nested ones, use os.walk or - slightly faster - the fast_scandir function above.
- Never use os.walk for only top-level subdirectories, as it can be hundreds(!) of times slower than os.scandir.

  • If you run the code below, make sure to run it once so that your OS will have accessed the folder, discard the results and run the test, otherwise results will be screwed.
  • You might want to mix up the function calls, but I tested it, and it did not really matter.
  • All examples will give the full path to the folder. The pathlib example as a (Windows)Path object.
  • The first element of os.walk will be the base folder. So you will not get only subdirectories. You can use fu.pop(0) to remove it.
  • None of the results will use natural sorting. This means results will be sorted like this: 1, 10, 2. To get natural sorting (1, 2, 10), please have a look at https://stackoverflow.com/a/48030307/2441026


Results:

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439

Tested with W7x64, Python 3.8.1.

# -*- coding: utf-8 -*-
# Python 3


import time
import os
from glob import glob
from pathlib import Path


directory = r"<insert_folder>"
RUNS = 1


def run_os_walk():
    a = time.time_ns()
    for i in range(RUNS):
        fu = [x[0] for x in os.walk(directory)]
    print(f"os.walk\t\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_glob():
    a = time.time_ns()
    for i in range(RUNS):
        fu = glob(directory + "/*/")
    print(f"glob.glob\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_pathlib_iterdir():
    a = time.time_ns()
    for i in range(RUNS):
        dirname = Path(directory)
        fu = [f for f in dirname.iterdir() if f.is_dir()]
    print(f"pathlib.iterdir\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_os_listdir():
    a = time.time_ns()
    for i in range(RUNS):
        dirname = Path(directory)
        fu = [os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))]
    print(f"os.listdir\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_os_scandir():
    a = time.time_ns()
    for i in range(RUNS):
        fu = [f.path for f in os.scandir(directory) if f.is_dir()]
    print(f"os.scandir\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len(fu)}")


if __name__ == '__main__':
    run_os_scandir()
    run_os_walk()
    run_glob()
    run_pathlib_iterdir()
    run_os_listdir()

Exit a while loop in VBS/VBA

Use Do...Loop with Until keyword

num=0
Do Until //certain_condition_to_break_loop
 num=num+1
Loop

This loop will continue to execute, Until the condition becomes true

While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops

How can I tell which button was clicked in a PHP form submit?

Are you asking in php or javascript.

If it is in php, give the name of that and use the post or get method, after that you can use the option of isset or that particular button name is checked to that value.

If it is in js, use getElementById for that

JavaScript: undefined !== undefined?

I'd like to post some important information about undefined, which beginners might not know.

Look at the following code:

 /* 
  * Consider there is no code above. 
  * The browser runs these lines only.
  */

   // var a;  
   // --- commented out to point that we've forgotten to declare `a` variable 

   if ( a === undefined ) {
       alert('Not defined');
   } else {
       alert('Defined: ' + a);
   }

   alert('Doing important job below');

If you run this code, where variable a HAS NEVER BEEN DECLARED using var, you will get an ERROR EXCEPTION and surprisingly see no alerts at all.

Instead of 'Doing important job below', your script will TERMINATE UNEXPECTEDLY, throwing unhandled exception on the very first line.


Here is the only bulletproof way to check for undefined using typeof keyword, which was designed just for such purpose:

   /* 
    * Correct and safe way of checking for `undefined`: 
    */

   if ( typeof a === 'undefined' ) {
       alert(
           'The variable is not declared in this scope, \n' +
           'or you are pointing to unexisting property, \n' +
           'or no value has been set yet to the variable, \n' + 
           'or the value set was `undefined`. \n' +
           '(two last cases are equivalent, don\'t worry if it blows out your mind.'
           );
   }

   /* 
    *  Use `typeof` for checking things like that
    */

This method works in all possible cases.

The last argument to use it is that undefined can be potentially overwritten in earlier versions of Javascript:

     /* @ Trollface @ */
        undefined = 2;
     /* Happy debuging! */  

Hope I was clear enough.

Linking dll in Visual Studio

You don't add or link directly against a DLL, you link against the LIB produced by the DLL.

A LIB provides symbols and other necessary data to either include a library in your code (static linking) or refer to the DLL (dynamic linking).

To link against a LIB, you need to add it to the project Properties -> Linker -> Input -> Additional Dependencies list. All LIB files here will be used in linking. You can also use a pragma like so:

#pragma comment(lib, "dll.lib")

With static linking, the code is included in your executable and there are no runtime dependencies. Dynamic linking requires a DLL with matching name and symbols be available within the search path (which is not just the path or system directory).

Changing tab bar item image and text color iOS

From UITabBarItem class docs:

By default, the actual unselected and selected images are automatically created from the alpha values in the source images. To prevent system coloring, provide images with UIImageRenderingModeAlwaysOriginal.

The clue is not whether you use UIImageRenderingModeAlwaysOriginal, the important thing is when to use it.

To prevent the grey color for unselected items, you will just need to prevent the system colouring for the unselected image. Here is how to do this:

var firstViewController:UIViewController = UIViewController()
// The following statement is what you need
var customTabBarItem:UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "YOUR_IMAGE_NAME")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "YOUR_IMAGE_NAME"))
firstViewController.tabBarItem = customTabBarItem

As you can see, I asked iOS to apply the original color (white, yellow, red, whatever) of the image ONLY for the UNSELECTED state, and leave the image as it is for the SELECTED state.

Also, you may need to add a tint color for the tab bar in order to apply a different color for the SELECTED state (instead of the default iOS blue color). As per your screenshot above, you are applying white color for the selected state:

self.tabBar.tintColor = UIColor.whiteColor()

EDIT:

enter image description here

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

How to write log to file

If you run binary on linux machine you could use shell script.

overwrite into a file

./binaryapp > binaryapp.log

append into a file

./binaryapp >> binaryapp.log

overwrite stderr into a file

./binaryapp &> binaryapp.error.log

append stderr into a file

./binaryapp &>> binalyapp.error.log

it can be more dynamic using shell script file.

#1062 - Duplicate entry for key 'PRIMARY'

  1. Make sure PRIMARY KEY was selected AUTO_INCREMENT.
  2. Just enable Auto increment by :
    ALTER TABLE [table name] AUTO_INCREMENT = 1
  3. When you execute the insert command you have to skip this key.

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

There is a special security expression in spring security:

hasAnyRole(list of roles) - true if the user has been granted any of the roles specified (given as a comma-separated list of strings).

I have never used it but I think it is exactly what you are looking for.

Example usage:

<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
    ...
</security:authorize>

Here is a link to the reference documentation where the standard spring security expressions are described. Also, here is a discussion where I described how to create custom expression if you need it.

mysql stored-procedure: out parameter

try changing OUT to INOUT for your out_number parameter definition.

CREATE PROCEDURE my_sqrt(input_number INT, INOUT out_number FLOAT)

INOUT means that the input variable for out_number (@out_value in your case.) will also serve as the output variable from which you can select the value from.

Get first day of week in SQL Server

CREATE FUNCTION dbo.fnFirstWorkingDayOfTheWeek
(
    @currentDate date
)
RETURNS INT
AS
BEGIN
    -- get DATEFIRST setting
    DECLARE @ds int = @@DATEFIRST 
    -- get week day number under current DATEFIRST setting
    DECLARE @dow int = DATEPART(dw,@currentDate) 

    DECLARE @wd  int =  1+(((@dow+@ds) % 7)+5) % 7  -- this is always return Mon as 1,Tue as 2 ... Sun as 7 

    RETURN DATEADD(dd,1-@wd,@currentDate) 

END

animating addClass/removeClass with jQuery

You just need the jQuery UI effects-core (13KB), to enable the duration of the adding (just like Omar Tariq it pointed out)

Sorting by date & time in descending order?

This is one of the simplest ways to sort record by Date:

SELECT  `Article_Id` ,  `Title` ,  `Source_Link` ,  `Content` ,  `Source` , `Reg_Date`, UNIX_TIMESTAMP(  `Reg_Date` ) AS DATE
FROM article
ORDER BY DATE DESC 

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

On Gradle 5.x I use:

wrapper {
    gradleVersion = '5.5.1'
}

How can I create a copy of an Oracle table without copying the data?

WHERE 1 = 0 or similar false conditions work, but I dislike how they look. Marginally cleaner code for Oracle 12c+ IMHO is

CREATE TABLE bar AS SELECT * FROM foo FETCH FIRST 0 ROWS ONLY;

Same limitations apply: only column definitions and their nullability are copied into a new table.

Find the most popular element in int[] array

public int getPopularElement(int[] a)
{
  int count = 1, tempCount;
  int popular = a[0];
  int temp = 0;
  for (int i = 0; i < (a.length - 1); i++)
  {
    temp = a[i];
    tempCount = 0;
    for (int j = 1; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount > count)
    {
      popular = temp;
      count = tempCount;
    }
  }
  return popular;
}

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

How to read existing text files without defining path

There are many ways to get a path. See CurrentDirrectory mentioned. Also, you can get the full file name of your application by using Assembly.GetExecutingAssembly().Location and then use Path class to get a directory name.

How to access site through IP address when website is on a shared host?

According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.

Here there are two examples(wget and curl): $ wget --header 'Host:somerandomservice.com' http://67.225.235.59 $ curl --header 'Host:somerandomservice.com' http://67.225.235.59

Resources:

https://en.wikipedia.org/wiki/Shared_web_hosting_service

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23

Displaying unicode symbols in HTML

I know an answer has already been accepted, but wanted to point a few things out.

Setting the content-type and charset is obviously a good practice, doing it on the server is much better, because it ensures consistency across your application.

However, I would use UTF-8 only when the language of my application uses a lot of characters that are available only in the UTF-8 charset. If you want to show a unicode character or symbol in one of cases, you can do so without changing the charset of your page.

HTML renderers have always been able to display symbols which are not part of the encoding character set of the page, as long as you mention the symbol in its numeric character reference (NCR). Sounds weird but its true.

So, even if your html has a header that states it has an encoding of ansi or any of the iso charsets, you can display a check mark by using its html character reference, in decimal - &#10003; or in hex - &#x2713;

So its a little difficult to understand why you are facing this issue on your pages. Can you check if the NCR value is correct, this is a good reference http://www.fileformat.info/info/unicode/char/2713/index.htm

Webpack "OTS parsing error" loading fonts

The best and easiest method is to base64 encode the font file. And use it in font-face. For encoding, go to the folder having the font-file and use the command in terminal:

base64 Roboto.ttf > basecodedtext.txt

You will get an output file named basecodedtext.txt. Open that file. Remove any white spaces in that.

Copy that code and add the following line to the CSS file:

@font-face {
  font-family: "font-name";
  src: url(data:application/x-font-woff;charset=utf-8;base64,<<paste your code here>>) format('woff');
}  

Then you can use the font-family: "font-name" in your CSS.

Node Version Manager (NVM) on Windows

An alternative to nvm-windows, which is mentioned in other answers would be Nodist.

I've had some issues with nvm-windows and admin privileges, which Nodist doesn't seem to have.

How do I count unique visitors to my site?

$user_ip=$_SERVER['REMOTE_ADDR'];

$check_ip = mysql_query("select userip from pageview where page='yourpage'  and userip='$user_ip'");
if(mysql_num_rows($check_ip)>=1)
{

}
else
{
  $insertview = mysql_query("insert into pageview values('','yourpage','$user_ip')");

  $updateview = mysql_query("update totalview set totalvisit = totalvisit+1 where page='yourpage' ");
}

code from talkerscode official tutorial if you have any problem http://talkerscode.com/webtricks/create-a-simple-pageviews-counter-using-php-and-mysql.php

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

My fix is:

<?php  ob_start(); ?>
<!DOCTYPE html>
<html lang="de">
.....
....//your whole code
....
</html>
<?php
        ob_clean();
ob_end_flush();

ob_flush();

?>

Hope this will help someone in future, and in my case its a Kaspersky issue but the fix above works great :)

Force Intellij IDEA to reread all maven dependencies

There is also one useful setting that tells IntelliJ to check for new versions of dependencies even if the version numbers didn't change. We had a local maven repository and a snapshot project that was updated a few times but the version numbers stood the same. The problem was that IntelliJ/Maven didn't update this project because of the fixed version number.

To enable checking for a changed dependency although the version number didn't change go to the "Maven Projects" tab, select "Maven settings" and there activate "Always update snapshots".

What is the best project structure for a Python application?

In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses.

As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.

With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.

How do I use the CONCAT function in SQL Server 2008 R2?

Just for completeness - in SQL 2008 you would use the plus + operator to perform string concatenation.

Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I've been struggling with this myself and I finally believe I have it figured out. It's incredible how many failed answers there are on this question

All you have to do is remove the padding from all your .col elements, and remove the padding also from the .container-fluid.

I did this in my own project a little sloppily by adding the following to my css file:

.col, col-10, col-12, col-2, col-6 {
    padding: 0!important;
}

.container-fluid {
    padding: 0!important;
}

I just have the different col sizes there to account for all the different col sizes I'm using. I'm confident there is a cleaner way to write the css but this illustrates the end result.

When should I use the Visitor Design Pattern?

I'm not very familiar with the Visitor pattern. Let's see if I got it right. Suppose you have a hierarchy of animals

class Animal {  };
class Dog: public Animal {  };
class Cat: public Animal {  };

(Suppose it is a complex hierarchy with a well-established interface.)

Now we want to add a new operation to the hierarchy, namely we want each animal to make its sound. As far as the hierarchy is this simple, you can do it with straight polymorphism:

class Animal
{ public: virtual void makeSound() = 0; };

class Dog : public Animal
{ public: void makeSound(); };

void Dog::makeSound()
{ std::cout << "woof!\n"; }

class Cat : public Animal
{ public: void makeSound(); };

void Cat::makeSound()
{ std::cout << "meow!\n"; }

But proceeding in this way, each time you want to add an operation you must modify the interface to every single class of the hierarchy. Now, suppose instead that you are satisfied with the original interface, and that you want to make the fewest possible modifications to it.

The Visitor pattern allows you to move each new operation in a suitable class, and you need to extend the hierarchy's interface only once. Let's do it. First, we define an abstract operation (the "Visitor" class in GoF) which has a method for every class in the hierarchy:

class Operation
{
public:
    virtual void hereIsADog(Dog *d) = 0;
    virtual void hereIsACat(Cat *c) = 0;
};

Then, we modify the hierarchy in order to accept new operations:

class Animal
{ public: virtual void letsDo(Operation *v) = 0; };

class Dog : public Animal
{ public: void letsDo(Operation *v); };

void Dog::letsDo(Operation *v)
{ v->hereIsADog(this); }

class Cat : public Animal
{ public: void letsDo(Operation *v); };

void Cat::letsDo(Operation *v)
{ v->hereIsACat(this); }

Finally, we implement the actual operation, without modifying neither Cat nor Dog:

class Sound : public Operation
{
public:
    void hereIsADog(Dog *d);
    void hereIsACat(Cat *c);
};

void Sound::hereIsADog(Dog *d)
{ std::cout << "woof!\n"; }

void Sound::hereIsACat(Cat *c)
{ std::cout << "meow!\n"; }

Now you have a way to add operations without modifying the hierarchy anymore. Here is how it works:

int main()
{
    Cat c;
    Sound theSound;
    c.letsDo(&theSound);
}

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

Xcode project -> goto info.plist and Click + Button then Add (App Transport Security Settings)Expand, Allow Arbitrary Loads Set YES. Thanks

WPF Binding StringFormat Short Date String

Try this:

<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />

which is culture sensitive and requires .NET 3.5 SP1 or above.

NOTE: This is case sensitive. "d" is the short date format specifier while "D" is the long date format specifier.

There's a full list of string format on the MSDN page on Standard Date and Time Format Strings and a fuller explanation of all the options on this MSDN blog post

However, there is one gotcha with this - it always outputs the date in US format unless you set the culture to the correct value yourself.

If you do not set this property, the binding engine uses the Language property of the binding target object. In XAML this defaults to "en-US" or inherits the value from the root element (or any element) of the page, if one has been explicitly set.

Source

One way to do this is in the code behind (assuming you've set the culture of the thread to the correct value):

this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);

The other way is to set the converter culture in the binding:

<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />

Though this doesn't allow you to localise the output.

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

I was moving data directory on a cloned server and having troubles to login as postgres. Resetting postgres password like this worked for me.

root# su postgres
postgres$ psql -U postgres
psql (9.3.6) 
Type "help" for help. 
postgres=#\password 
Enter new password: 
Enter it again: 
postgres=#

Missing Maven dependencies in Eclipse project

My issue sounds similar so I'll add to the discussion. I had cancelled the import of an existing maven project into Eclipse which resulted in it not being allowed to Update and wouldn't properly finish the Work Space building.

What I had to do to resolve it was select Run As... -> Maven build... and under Goals I entered dependency:go-offline and ran that.

Then I right clicked the project and selected Maven -> Update Project... and updated that specific project.

This finally allowed it to create the source folders and finish the import.

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

Use Pre-request script tab to write javascript to get and save the date into a variable:

const dateNow= new Date();
pm.environment.set('currentDate', dateNow.toISOString());

and then use it in the request body as follows:

"currentDate": "{{currentDate}}"

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

I had the same issue - it sorted itself out in ~3 hours after I uploaded the app to the Play console. According to Google:

Warning: It may take up to 2-3 hours after uploading the APK for Google Play to recognize your updated APK version. If you try to test your application before your uploaded APK is recognized by Google Play, your application will receive a ‘purchase cancelled’ response with an error message “This version of the application is not enabled for In-app Billing.

While the message is not the same, I suspect the root cause to be the same.

Why is pydot unable to find GraphViz's executables in Windows 8?

The problem is that the path to GraphViz was not found by the pydot module as shown in the traceback:

'GraphViz\'s executables not found'

I solved this problem on my windows 7 machine by adding the GraphViz bin directory to my computer's PATH. Then restarting my python IDE to use the updated path.

  1. Install GraphViz if you haven't already (I used the MSI download)
  2. Get the path for gvedit.exe (for me it was "C:\Program Files (x86)\Graphviz2.34\bin\")
  3. Add this path to the computer's PATH
  4. One way to get to environment settings to set your path is to click on each of these button/menu options: start->computer->system properties->advanced settings->environment variables
  5. Click Edit User path
  6. Add this string to the end of your Variable value list (including semicolon): ;C:\Program Files (x86)\Graphviz2.34\bin
  7. Click OK
  8. Restart your Python IDE

How to append multiple values to a list in Python

If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.

There's also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.

The difference in months between dates in MySQL

SELECT * 
FROM emp_salaryrevise_view 
WHERE curr_year Between '2008' AND '2009' 
    AND MNTH Between '12' AND '1'

Regexp Java for password validation

simple example using regex

public class passwordvalidation {
    public static void main(String[] args) {
      String passwd = "aaZZa44@"; 
      String pattern = "(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}";
      System.out.println(passwd.matches(pattern));
   }
}

Explanations:

  • (?=.*[0-9]) a digit must occur at least once
  • (?=.*[a-z]) a lower case letter must occur at least once
  • (?=.*[A-Z]) an upper case letter must occur at least once
  • (?=.*[@#$%^&+=]) a special character must occur at least once
  • (?=\\S+$) no whitespace allowed in the entire string
  • .{8,} at least 8 characters

Determining complexity for recursive functions (Big O notation)

The time complexity, in Big O notation, for each function:


int recursiveFun1(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun1(n-1);
}

This function is being called recursively n times before reaching the base case so its O(n), often called linear.


int recursiveFun2(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun2(n-5);
}

This function is called n-5 for each time, so we deduct five from n before calling the function, but n-5 is also O(n). (Actually called order of n/5 times. And, O(n/5) = O(n) ).


int recursiveFun3(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun3(n/5);
}

This function is log(n) base 5, for every time we divide by 5 before calling the function so its O(log(n))(base 5), often called logarithmic and most often Big O notation and complexity analysis uses base 2.


void recursiveFun4(int n, int m, int o)
{
    if (n <= 0)
    {
        printf("%d, %d\n",m, o);
    }
    else
    {
        recursiveFun4(n-1, m+1, o);
        recursiveFun4(n-1, m, o+1);
    }
}

Here, it's O(2^n), or exponential, since each function call calls itself twice unless it has been recursed n times.



int recursiveFun5(int n)
{
    for (i = 0; i < n; i += 2) {
        // do something
    }

    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun5(n-5);
}

And here the for loop takes n/2 since we're increasing by 2, and the recursion takes n/5 and since the for loop is called recursively, therefore, the time complexity is in

(n/5) * (n/2) = n^2/10,

due to Asymptotic behavior and worst-case scenario considerations or the upper bound that big O is striving for, we are only interested in the largest term so O(n^2).


Good luck on your midterms ;)

How to set a JVM TimeZone Properly

The accepted answer above:

-Duser.timezone="Europe/Sofia" 

Didn't work for me exactly. I only was able to successfully change my timezone when I didn't have quotes around the parameters:

-Duser.timezone=Europe/Sofia

How do I capture the output of a script if it is being ran by the task scheduler?

Use the cmd.exe command processor to build a timestamped file name to log your scheduled task's output

To build upon answers by others here, it may be that you want to create an output file that has the date and/or time embedded in the name of the file. You can use the cmd.exe command processor to do this for you.

Note: This technique takes the string output of internal Windows environment variables and slices them up based on character position. Because of this, the exact values supplied in the examples below may not be correct for the region of Windows you use. Also, with some regional settings, some components of the date or time may introduce a space into the constructed file name when their value is less than 10. To mitigate this issue, surround your file name with quotes so that any unintended spaces in the file name won't break the command-line you're constructing. Experiment and find what works best for your situation.

Be aware that PowerShell is more powerful than cmd.exe. One way it is more powerful is that it can deal with different Windows regions. But this answer is about solving this issue using cmd.exe, not PowerShell, so we continue.

Using cmd.exe

You can access different components of the date and time by slicing the internal environment variables %date% and %time%, as follows (again, the exact slicing values are dependent on the region configured in Windows):

  • Year (4 digits): %date:~10,4%
  • Month (2 digits): %date:~4,2%
  • Day (2 digits): %date:~7,2%
  • Hour (2 digits): %time:~0,2%
  • Minute (2 digits): %time:~3,2%
  • Second (2 digits): %time:~6,2%

Suppose you want your log file to be named using this date/time format: "Log_[yyyyMMdd]_[hhmmss].txt". You'd use the following:

Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt

To test this, run the following command line:

cmd.exe /c echo "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"

Putting it all together, to redirect both stdout and stderr from your script to a log file named with the current date and time, use might use the following as your command line:

cmd /c YourProgram.cmd > "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1

Note the use of quotes around the file name to handle instances a date or time component may introduce a space character.

In my case, if the current date/time were 10/05/2017 9:05:34 AM, the above command-line would produce the following:

cmd /c YourProgram.cmd > "Log_20171005_ 90534.txt" 2>&1

Conveniently map between enum and int / String

Use an interface to show it who's boss.

public interface SleskeEnum {
    int id();

    SleskeEnum[] getValues();

}

public enum BonusType implements SleskeEnum {


  MONTHLY(1), YEARLY(2), ONE_OFF(3);

  public final int id;

  BonusType(int id) {
    this.id = id;
  }

  public SleskeEnum[] getValues() {
    return values();
  }

  public int id() { return id; }


}

public class Utils {

  public static SleskeEnum getById(SleskeEnum type, int id) {
      for(SleskeEnum t : type.getValues())
          if(t.id() == id) return t;
      throw new IllegalArgumentException("BonusType does not accept id " + id);
  }

  public static void main(String[] args) {

      BonusType shouldBeMonthly = (BonusType)getById(BonusType.MONTHLY,1);
      System.out.println(shouldBeMonthly == BonusType.MONTHLY);

      BonusType shouldBeMonthly2 = (BonusType)getById(BonusType.MONTHLY,1);
      System.out.println(shouldBeMonthly2 == BonusType.YEARLY);

      BonusType shouldBeYearly = (BonusType)getById(BonusType.MONTHLY,2);
      System.out.println(shouldBeYearly  == BonusType.YEARLY);

      BonusType shouldBeOneOff = (BonusType)getById(BonusType.MONTHLY,3);
      System.out.println(shouldBeOneOff == BonusType.ONE_OFF);

      BonusType shouldException = (BonusType)getById(BonusType.MONTHLY,4);
  }
}

And the result:

C:\Documents and Settings\user\My Documents>java Utils
true
false
true
true
Exception in thread "main" java.lang.IllegalArgumentException: BonusType does not accept id 4
        at Utils.getById(Utils.java:6)
        at Utils.main(Utils.java:23)

C:\Documents and Settings\user\My Documents>

Why is January month 0 in Java Calendar?

I'd say laziness. Arrays start at 0 (everyone knows that); the months of the year are an array, which leads me to believe that some engineer at Sun just didn't bother to put this one little nicety into the Java code.

Fixing slow initial load for IIS

I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.

How to get sp_executesql result into a variable?

DECLARE @vi INT
DECLARE @vQuery NVARCHAR(1000)

SET @vQuery = N'SELECT @vi= COUNT(*) FROM <TableName>'

EXEC SP_EXECUTESQL 
        @Query  = @vQuery
      , @Params = N'@vi INT OUTPUT'
      , @vi = @vi OUTPUT

SELECT @vi

How to prevent gcc optimizing some statements in C?

Instead of using the new pragmas, you can also use __attribute__((optimize("O0"))) for your needs. This has the advantage of just applying to a single function and not all functions defined in the same file.

Usage example:

void __attribute__((optimize("O0"))) foo(unsigned char data) {
    // unmodifiable compiler code
}

Getting DOM node from React child element

If you want to access any DOM element simply add ref attribute and you can directly access that element.

<input type="text" ref="myinput">

And then you can directly:

componentDidMount: function() 
{
    this.refs.myinput.select();

},

Their is no need of using ReactDOM.findDOMNode(), if you have added a ref to any element.

Sending Arguments To Background Worker?

Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();

And on the handler method:

private void WorkerDoWork(int value, string text) {
    ...
}

Java's L number (long) specification

It seems like these would be good to have because (I assume) if you could specify the number you're typing in is a short then java wouldn't have to cast it

Since the parsing of literals happens at compile time, this is absolutely irrelevant in regard to performance. The only reason having short and byte suffixes would be nice is that it lead to more compact code.

MySQL - How to select rows where value is in array?

Use the FIND_IN_SET function:

SELECT t.*
  FROM YOUR_TABLE t
 WHERE FIND_IN_SET(3, t.ids) > 0

How to get an object's properties in JavaScript / jQuery?

Scanning object for first intance of a determinated prop:

var obj = {a:'Saludos',
            b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
           d:'Hasta luego'
            }
function scan (element,list){
    var res;
    if (typeof(list) != 'undefined'){
        if (typeof(list) == 'object'){
            for(key in list){
               if (typeof(res) == 'undefined'){
                res = (key == element)?list[key]:scan(element,list[key]);
               }
            });
        }
    }
    return res;
}
console.log(scan('a',obj));

Why is my method undefined for the type object?

The line

Object EchoServer0;

says that you are allocating an Object named EchoServer0. This has nothing to do with the class EchoServer0. Furthermore, the object is not initialized, so EchoServer0 is null. Classes and identifiers have separate namespaces. This will actually compile:

String String = "abc";  // My use of String String was deliberate.

Please keep to the Java naming standards: classes begin with a capital letter, identifiers begin with a small letter, constants and enums are all-capitals.

public final String ME = "Eric Jablow";
public final double GAMMA = 0.5772;
public enum Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET}
public COLOR background = Color.RED;

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

Padding between ActionBar's home icon and title

I used AppBarLayout and custom ImageButton do to so.

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp"
    android:background="@android:color/transparent"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">

       <ImageView
           android:layout_width="32dp"
           android:layout_height="32dp"
           android:src="@drawable/selector_back_button"
           android:layout_centerVertical="true"
           android:layout_marginLeft="8dp"
           android:id="@+id/back_button"/>

       <android.support.v7.widget.Toolbar
           android:id="@+id/toolbar"
           android:layout_width="match_parent"
           android:layout_height="?attr/actionBarSize"
           app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </RelativeLayout>    
</android.support.design.widget.AppBarLayout>

My Java code:

findViewById(R.id.appbar).bringToFront();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
getSupportActionBar().setDisplayShowTitleEnabled(false);

How to read large text file on windows?

You should try TextPad, it can read a file of that size.

It's free to evaluate (you can evaluate indefinitely)

Use Fieldset Legend with bootstrap

That's because Bootstrap by default sets the width of the legend element to 100%. You can fix this by changing your legend.scheduler-border to also use:

legend.scheduler-border {
    width:inherit; /* Or auto */
    padding:0 10px; /* To give a bit of padding on the left and right */
    border-bottom:none;
}

JSFiddle example.

You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.

You may also want to add margin-bottom:0; to it as well to reduce the gap between the legend and the divider.

Getting All Variables In Scope

Although everyone answer "No" and I know that "No" is the right answer but if you really need to get local variables of a function there is a restricted way.

Consider this function:

var f = function() {
    var x = 0;
    console.log(x);
};

You can convert your function to a string:

var s = f + '';

You will get source of function as a string

'function () {\nvar x = 0;\nconsole.log(x);\n}'

Now you can use a parser like esprima to parse function code and find local variable declarations.

var s = 'function () {\nvar x = 0;\nconsole.log(x);\n}';
s = s.slice(12); // to remove "function () "
var esprima = require('esprima');
var result = esprima.parse(s);

and find objects with:

obj.type == "VariableDeclaration"

in the result (I have removed console.log(x) below):

{
    "type": "Program",
    "body": [
        {
            "type": "VariableDeclaration",
            "declarations": [
                {
                    "type": "VariableDeclarator",
                    "id": {
                        "type": "Identifier",
                        "name": "x"
                    },
                    "init": {
                        "type": "Literal",
                        "value": 0,
                        "raw": "0"
                    }
                }
            ],
            "kind": "var"
        }
    ]
}

I have tested this in Chrome, Firefox and Node.

But the problem with this method is that you just have the variables defined in the function itself. For example for this one:

var g = function() {
    var y = 0;
    var f = function() {
        var x = 0;
        console.log(x);
    };
}

you just have access to the x and not y. But still you can use chains of caller (arguments.callee.caller.caller.caller) in a loop to find local variables of caller functions. If you have all local variable names so you have scope variables. With the variable names you have access to values with a simple eval.

javascript jquery radio button click

this should be good

$(document).ready(function() {
    $('input:radio').change(function() {
       alert('ole');
    });
});

Query to get all rows from previous month

If there are no future dates ...

SELECT * 
FROM   table_name 
WHERE  date_created > (NOW() - INTERVAL 1 MONTH);

Tested.

How should I cast in VB.NET?

Cstr() is compiled inline for better performance.

CType allows for casts between types if a conversion operator is defined

ToString() Between base type and string throws an exception if conversion is not possible.

TryParse() From String to base typeif possible otherwise returns false

DirectCast used if the types are related via inheritance or share a common interface , will throw an exception if the cast is not possible, trycast will return nothing in this instance

Bash foreach loop

cat `cat filenames.txt`

will do the trick

How to make a Qt Widget grow with the window size?

I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

SQL Developer with JDK (64 bit) cannot find JVM

Step 1, go to C:\Users<you>\AppData\Roaming, delete the whole folder [sqldeveloper]

Step 2, click on your shortcut sqldeveloper to start Sql developer

Step 3, the window will popup again to ask for a JRE location, choose a suitable one.

If it still doesn't work, execute again from step 1 to 3, remember to change JRE location every time until it works.

CSS: Background image and padding

Use background-position: calc(100% - 20px) center, For pixel perfection calc() is the best solution.

_x000D_
_x000D_
ul {_x000D_
  width: 100px;_x000D_
}_x000D_
ul li {_x000D_
  border: 1px solid orange;_x000D_
  background: url("http://placehold.it/30x15") no-repeat calc(100% - 10px) center;_x000D_
}_x000D_
ul li:hover {_x000D_
  background-position: calc(100% - 20px) center;_x000D_
}
_x000D_
<ul>_x000D_
  <li>Hello</li>_x000D_
  <li>Hello world</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Hash string in c#

The shortest and fastest way ever. Only 1 line!

    public static string StringSha256Hash(string text) =>
        string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Remove file from SVN repository without deleting local copy

Deleting files and folders

If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu ? Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.

Delete completely:
right mouse click ? Menu ? Delete

Delete & Keep local:
Shift + right mouse click ? Menu ? Delete

How to access a preexisting collection with Mongoose?

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

or model mapped:

mongoose.model('Question', 
               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name

Programmatically get height of navigation bar

I have used:

let originY: CGFloat = self.navigationController!.navigationBar.frame.maxY

Working great if you want to get the navigation bar height AND its Y origin.

Using GSON to parse a JSON array

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

Seems to work fine. But there is an extra , Comma in your string.

[
    { 
        "number" : "3",
        "title" : "hello_world"
    },
    { 
        "number" : "2",
        "title" : "hello_world"
    }
]

When do I use path params vs. query params in a RESTful API?

In a REST API, you shouldn't be overly concerned by predictable URI's. The very suggestion of URI predictability alludes to a misunderstanding of RESTful architecture. It assumes that a client should be constructing URIs themselves, which they really shouldn't have to.

However, I assume that you are not creating a true REST API, but a 'REST inspired' API (such as the Google Drive one). In these cases the rule of thumb is 'path params = resource identification' and 'query params = resource sorting'. So, the question becomes, can you uniquely identify your resource WITHOUT status / region? If yes, then perhaps its a query param. If no, then its a path param.

HTH.

Can a shell script set environment variables of the calling shell?

You can instruct the child process to print its environment variables (by calling "env"), then loop over the printed environment variables in the parent process and call "export" on those variables.

The following code is based on Capturing output of find . -print0 into a bash array

If the parent shell is the bash, you can use

while IFS= read -r -d $'\0' line; do
    export "$line"
done < <(bash -s <<< 'export VARNAME=something; env -0')
echo $VARNAME

If the parent shell is the dash, then read does not provide the -d flag and the code gets more complicated

TMPDIR=$(mktemp -d)
mkfifo $TMPDIR/fifo
(bash -s << "EOF"
    export VARNAME=something
    while IFS= read -r -d $'\0' line; do
        echo $(printf '%q' "$line")
    done < <(env -0)
EOF
) > $TMPDIR/fifo &
while read -r line; do export "$(eval echo $line)"; done < $TMPDIR/fifo
rm -r $TMPDIR
echo $VARNAME

SSRS expression to format two decimal places does not show zeros

Please try the following code snippet,

IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value), 
Format(Avg(Fields!Vision_Score.Value)), 
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))

hope it will help, Thank-you.

convert string to specific datetime format?

"2011-05-19 10:30:14".to_time

What is the purpose of flush() in Java streams?

For performance issue, first data is to be written into Buffer. When buffer get full then data is written to output (File,console etc.). When buffer is partially filled and you want to send it to output(file,console) then you need to call flush() method manually in order to write partially filled buffer to output(file,console).

The point of test %eax %eax

Some x86 instructions are designed to leave the content of the operands (registers) as they are and just set/unset specific internal CPU flags like the zero-flag (ZF). You can think at the ZF as a true/false boolean flag that resides inside the CPU.

in this particular case, TEST instruction performs a bitwise logical AND, discards the actual result and sets/unsets the ZF according to the result of the logical and: if the result is zero it sets ZF = 1, otherwise it sets ZF = 0.

Conditional jump instructions like JE are designed to look at the ZF for jumping/notjumping so using TEST and JE together is equivalent to perform a conditional jump based on the value of a specific register:

example:

TEST EAX,EAX
JE some_address



the CPU will jump to "some_address" if and only if ZF = 1, in other words if and only if AND(EAX,EAX) = 0 which in turn it can occur if and only if EAX == 0

the equivalent C code is:

if(eax == 0)
{
    goto some_address
}

Compare two dates with JavaScript

The relational operators < <= > >= can be used to compare JavaScript dates:

var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 2);
d1 <  d2; // true
d1 <= d2; // true
d1 >  d2; // false
d1 >= d2; // false

However, the equality operators == != === !== cannot be used to compare (the value of) dates because:

  • Two distinct objects are never equal for either strict or abstract comparisons.
  • An expression comparing Objects is only true if the operands reference the same Object.

You can compare the value of dates for equality using any of these methods:

var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 1);
/*
 * note: d1 == d2 returns false as described above
 */
d1.getTime() == d2.getTime(); // true
d1.valueOf() == d2.valueOf(); // true
Number(d1)   == Number(d2);   // true
+d1          == +d2;          // true

Both Date.getTime() and Date.valueOf() return the number of milliseconds since January 1, 1970, 00:00 UTC. Both Number function and unary + operator call the valueOf() methods behind the scenes.

CreateProcess error=206, The filename or extension is too long when running main() method

it happens due to DataNucleus sometimes overwrite the Arguments with many paths.

You have to overwrite them with this:

-enhancerName ASM -api JDO -pu MediaToGo

Hope help you!

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Like the answer previous, but I'd put ::before, just for stacking purposes. If you want to include text over the overlay (a common use case), using ::before will should fix that.

.dimmed {
  position: relative;
}

.dimmed:before {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
}

How do I handle ImeOptions' done button click?

I ended up with a combination of Roberts and chirags answers:

((EditText)findViewById(R.id.search_field)).setOnEditorActionListener(
        new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // Identifier of the action. This will be either the identifier you supplied,
        // or EditorInfo.IME_NULL if being called due to the enter key being pressed.
        if (actionId == EditorInfo.IME_ACTION_SEARCH
                || actionId == EditorInfo.IME_ACTION_DONE
                || event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            onSearchAction(v);
            return true;
        }
        // Return true if you have consumed the action, else false.
        return false;
    }
});

Update: The above code would some times activate the callback twice. Instead I've opted for the following code, which I got from the Google chat clients:

public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    // If triggered by an enter key, this is the event; otherwise, this is null.
    if (event != null) {
        // if shift key is down, then we want to insert the '\n' char in the TextView;
        // otherwise, the default action is to send the message.
        if (!event.isShiftPressed()) {
            if (isPreparedForSending()) {
                confirmSendMessageIfNeeded();
            }
            return true;
        }
        return false;
    }

    if (isPreparedForSending()) {
        confirmSendMessageIfNeeded();
    }
    return true;
}

How do I create a new class in IntelliJ without using the mouse?

I do this a lot, and I don't have an insert key on my laptop, so I made my own keybinding for it. You can do this by opening Settings > IDE Settings > Keymap and navigating to Main menu > File > New... (I would recommend typing "new" into the search box - that will narrow it down considerably).

Then you can add a new keyboard shortcut for it by double clicking on that item and selecting Add Keyboard Shortcut.

How do I convert hex to decimal in Python?

>>> int("0xff", 16)
255

or

>>> int("FFFF", 16)
65535

Read the docs.