How to print an exception in Python 3?
[In Python3]
Let's say you want to handle an IndexError
and print the traceback, you can do the following:
from traceback import print_tb
empty_list = []
try:
x = empty_list[100]
except IndexError as index_error:
print_tb(index_error.__traceback__)
Note: You can use the format_tb
function instead of print_tb
to get the traceback as a string for logging purposes.
Hope this helps.
Get element from within an iFrame
Above answers gave good solutions using Javscript.
Here is a simple jQuery solution:
$('#iframeId').contents().find('div')
The trick here is jQuery's .contents()
method, unlike .children()
which can only get HTML elements, .contents()
can get both text nodes and HTML elements. That's why one can get document contents of an iframe by using it.
Further reading about jQuery .contents()
: .contents()
Note that the iframe and page have to be on the same domain.
How to ssh from within a bash script?
If you want the password prompt to go away then use key based authentication (described here).
To run commands remotely over ssh you have to give them as an argument to ssh, like the following:
root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'
What do I use for a max-heap implementation in Python?
This is a simple MaxHeap
implementation based on heapq
. Though it only works with numeric values.
import heapq
from typing import List
class MaxHeap:
def __init__(self):
self.data = []
def top(self):
return -self.data[0]
def push(self, val):
heapq.heappush(self.data, -val)
def pop(self):
return -heapq.heappop(self.data)
Usage:
max_heap = MaxHeap()
max_heap.push(3)
max_heap.push(5)
max_heap.push(1)
print(max_heap.top()) # 5
Grant SELECT on multiple tables oracle
If you want to grant to both tables and views try:
SELECT DISTINCT
|| OWNER
|| '.'
|| TABLE_NAME
|| ' to db_user;'
FROM
ALL_TAB_COLS
WHERE
TABLE_NAME LIKE 'TABLE_NAME_%';
For just views try:
SELECT
'grant select on '
|| OWNER
|| '.'
|| VIEW_NAME
|| ' to REPORT_DW;'
FROM
ALL_VIEWS
WHERE
VIEW_NAME LIKE 'VIEW_NAME_%';
Copy results and execute.
When to use If-else if-else over switch statements and vice versa
The tendency to avoid stuff because it takes longer to type is a bad thing, try to root it out. That said, overly verbose things are also difficult to read, so small and simple is important, but it's readability not writability that's important. Concise one-liners can often be more difficult to read than a simple well laid out 3 or 4 lines.
Use whichever construct best descibes the logic of the operation.
How can one use multi threading in PHP applications
You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won't wait for the command to finish.
I can't quite remember the php CLI syntax, but you'd want something like:
exec("/path/to/php -f '/path/to/file.php' | '/path/to/output.txt'");
I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.
Can we cast a generic object to a custom object type in javascript?
No.
But if you're looking to treat your person1
object as if it were a Person
, you can call methods on Person
's prototype on person1
with call
:
Person.prototype.getFullNamePublic = function(){
return this.lastName + ' ' + this.firstName;
}
Person.prototype.getFullNamePublic.call(person1);
Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName
method.
SVN Error - Not a working copy
This is what I did:
- rename trunk to trunk_
- create a new folder trunk
- Re-checkout and interrupt the process after few files are checked-out
- Move the files from trunk_ to trunk
- Do svn cleanup
- Do svn update. This will update the status of files and then all your files will be versioned.
How to make a drop down list in yii2?
It seems you've found your answer already but since you mentioned the active form I'll contribute with one more, even if it differs only ever so slightly.
<?php
$form = ActiveForm::begin();
echo $form->field($model, 'attribute')
->dropDownList(
$items, // Flat array ('id'=>'label')
['prompt'=>''] // options
);
ActiveForm::end();
?>
How to turn a vector into a matrix in R?
A matrix is really just a vector with a dim
attribute (for the dimensions). So you can add dimensions to vec
using the dim()
function and vec
will then be a matrix:
vec <- 1:49
dim(vec) <- c(7, 7) ## (rows, cols)
vec
> vec <- 1:49
> dim(vec) <- c(7, 7) ## (rows, cols)
> vec
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 8 15 22 29 36 43
[2,] 2 9 16 23 30 37 44
[3,] 3 10 17 24 31 38 45
[4,] 4 11 18 25 32 39 46
[5,] 5 12 19 26 33 40 47
[6,] 6 13 20 27 34 41 48
[7,] 7 14 21 28 35 42 49
IIS7 Cache-Control
Complementing Elmer's answer, as my edit was rolled back.
To cache static content for 365 days with public cache-control header, IIS can be configured with the following
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
</staticContent>
This will translate into a header like this:
Cache-Control: public,max-age=31536000
Note that max-age is a delta in seconds, being expressed by a positive 32bit integer as stated in RFC 2616 Sections 14.9.3 and 14.9.4. This represents a maximum value of 2^31 or 2,147,483,648 seconds (over 68 years). However, to better ensure compatibility between clients and servers, we adopt a recommended maximum of 365 days (one year).
As mentioned on other answers, you can use these directives also on the web.config of your site for all static content. As an alternative, you can use it only for contents in a specific location too (on the sample, 30 days public cache for contents in "cdn" folder):
<location path="cdn">
<system.webServer>
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00"/>
</staticContent>
</system.webServer>
</location>
Difference between logger.info and logger.debug
It depends on which level you selected in your log4j configuration file.
<Loggers>
<Root level="info">
...
If your level is "info" (by default), logger.debug(...)
will not be printed in your console.
However, if your level is "debug", it will.
Depending on the criticality level of your code, you should use the most accurate level among the following ones :
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
How to pass data to all views in Laravel 5?
I found this to be the easiest one. Create a new provider and user the '*'
wildcard to attach it to all views. Works in 5.3 as well :-)
<?php
namespace App\Providers;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
* @return void
*/
public function boot()
{
view()->composer('*', function ($view)
{
$user = request()->user();
$view->with('user', $user);
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
CSS-Only Scrollable Table with fixed headers
As I was recently in need of this, I will share a solution that uses 3 tables, but does not require JavaScript.
Table 1 (parent) contains two rows. The first row contains table 2 (child 1) for the column headers. The second row contains table 3 (child 2) for the scrolling content.
It must be noted the childTbl
must be 25px
shorter than the parentTbl
for the scroller to appear properly.
This is the source, where I got the idea from. I made it HTML5-friendly without the deprecated tags and the inline CSS.
_x000D_
_x000D_
.parentTbl table {_x000D_
border-spacing: 0;_x000D_
border-collapse: collapse;_x000D_
border: 0;_x000D_
width: 690px;_x000D_
}_x000D_
.childTbl table {_x000D_
border-spacing: 0;_x000D_
border-collapse: collapse;_x000D_
border: 1px solid #d7d7d7;_x000D_
width: 665px;_x000D_
}_x000D_
.childTbl th,_x000D_
.childTbl td {_x000D_
border: 1px solid #d7d7d7;_x000D_
}_x000D_
.scrollData {_x000D_
width: 690;_x000D_
height: 150px;_x000D_
overflow-x: hidden;_x000D_
}
_x000D_
<div class="parentTbl">_x000D_
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<div class="childTbl">_x000D_
<table class="childTbl">_x000D_
<tr>_x000D_
<th>Header 1</th>_x000D_
<th>Header 2</th>_x000D_
<th>Header 3</th>_x000D_
<th>Header 4</th>_x000D_
<th>Header 5</th>_x000D_
<th>Header 6</th>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class="scrollData childTbl">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Table Data 1</td>_x000D_
<td>Table Data 2</td>_x000D_
<td>Table Data 3</td>_x000D_
<td>Table Data 4</td>_x000D_
<td>Table Data 5</td>_x000D_
<td>Table Data 6</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_
This is reliable on different browsers, the downside would be having to hard code the table widths.
Read HttpContent in WebApi controller
Even though this solution might seem obvious, I just wanted to post it here so the next guy will google it faster.
If you still want to have the model as a parameter in the method, you can create a DelegatingHandler
to buffer the content.
internal sealed class BufferizingHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
await request.Content.LoadIntoBufferAsync();
var result = await base.SendAsync(request, cancellationToken);
return result;
}
}
And add it to the global message handlers:
configuration.MessageHandlers.Add(new BufferizingHandler());
This solution is based on the answer by Darrel Miller.
This way all the requests will be buffered.
What's the best way of scraping data from a website?
You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.
Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.
Tools
Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.
You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.
Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.
Language
PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.
A note on Regular expressions:
DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML.
A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.
Javascript-heavy sites
In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.
There are two approaches to this problem:
The low level approach:
You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.
The embedded browser approach:
Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.
If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.
You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.
Which approach is best?
That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.
The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.
Rate Limiting/Bot behaviour
You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.
Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.
You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.
Testing
Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.
There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.
The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.
You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.
Legal Issues
The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.
The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.
It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.
Who am I to write this giant wall of text anyway?
I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.
I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)
I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.
I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.
Plotting multiple curves same graph and same scale
(The typical method would be to use plot
just once to set up the limits, possibly to include the range of all series combined, and then to use points
and lines
to add the separate series.) To use plot
multiple times with par(new=TRUE)
you need to make sure that your first plot has a proper ylim
to accept the all series (and in another situation, you may need to also use the same strategy for xlim):
# first plot
plot(x, y1, ylim=range(c(y1,y2)))
# second plot EDIT: needs to have same ylim
par(new = TRUE)
plot(x, y2, ylim=range(c(y1,y2)), axes = FALSE, xlab = "", ylab = "")
This next code will do the task more compactly, by default you get numbers as points but the second one gives you typical R-type-"points":
matplot(x, cbind(y1,y2))
matplot(x, cbind(y1,y2), pch=1)
How to import a module given its name as string?
Note: imp is deprecated since Python 3.4 in favor of importlib
As mentioned the imp module provides you loading functions:
imp.load_source(name, path)
imp.load_compiled(name, path)
I've used these before to perform something similar.
In my case I defined a specific class with defined methods that were required.
Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:
import imp
import os
def load_from_file(filepath):
class_inst = None
expected_class = 'MyClass'
mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == '.py':
py_mod = imp.load_source(mod_name, filepath)
elif file_ext.lower() == '.pyc':
py_mod = imp.load_compiled(mod_name, filepath)
if hasattr(py_mod, expected_class):
class_inst = getattr(py_mod, expected_class)()
return class_inst
Laravel whereIn OR whereIn
$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery) use ($stakeholderId){
$subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
$subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
});
$result = $query->get();
return $result;
// OUTPUT @input $stakeholderId = 1
//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss
.rights
from dms_stakeholder_permissions
where dms_stakeholder_permissions
.stakeholder_id
= 4 or (dms_stakeholder_permissions
.stakeholder_id
= 1 and dms_stakeholder_permissions
.rights
in (1, 2, 3))
AngularJS accessing DOM elements inside directive template
You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.
Here is the directive:
app.directive("ngScopeElement", function () {
var directiveDefinitionObject = {
restrict: "A",
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
scope[iAttrs.ngScopeElement] = iElement;
}
};
}
};
return directiveDefinitionObject;
});
Usage:
app.directive("myDirective", function() {
return {
template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
link: function(scope, element, attrs) {
scope.list[0] // scope.list is the jqlite element,
// scope.list[0] is the native dom element
}
}
});
Some remarks:
- Due to the compile and link order for nested directives you can only access
scope.list
from myDirective
s postLink-Function, which you are very likely using anyway
ngScopeElement
uses a preLink-function, so that directives nested within the element having ng-scope-element
can already access scope.list
- not sure how this behaves performance-wise
When to use in vs ref vs out
An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.
Amazon S3 direct file upload from client browser - private key disclosure
Here is how you generate a policy document using node and serverless
"use strict";
const uniqid = require('uniqid');
const crypto = require('crypto');
class Token {
/**
* @param {Object} config SSM Parameter store JSON config
*/
constructor(config) {
// Ensure some required properties are set in the SSM configuration object
this.constructor._validateConfig(config);
this.region = config.region; // AWS region e.g. us-west-2
this.bucket = config.bucket; // Bucket name only
this.bucketAcl = config.bucketAcl; // Bucket access policy [private, public-read]
this.accessKey = config.accessKey; // Access key
this.secretKey = config.secretKey; // Access key secret
// Create a really unique videoKey, with folder prefix
this.key = uniqid() + uniqid.process();
// The policy requires the date to be this format e.g. 20181109
const date = new Date().toISOString();
this.dateString = date.substr(0, 4) + date.substr(5, 2) + date.substr(8, 2);
// The number of minutes the policy will need to be used by before it expires
this.policyExpireMinutes = 15;
// HMAC encryption algorithm used to encrypt everything in the request
this.encryptionAlgorithm = 'sha256';
// Client uses encryption algorithm key while making request to S3
this.clientEncryptionAlgorithm = 'AWS4-HMAC-SHA256';
}
/**
* Returns the parameters that FE will use to directly upload to s3
*
* @returns {Object}
*/
getS3FormParameters() {
const credentialPath = this._amazonCredentialPath();
const policy = this._s3UploadPolicy(credentialPath);
const policyBase64 = new Buffer(JSON.stringify(policy)).toString('base64');
const signature = this._s3UploadSignature(policyBase64);
return {
'key': this.key,
'acl': this.bucketAcl,
'success_action_status': '201',
'policy': policyBase64,
'endpoint': "https://" + this.bucket + ".s3-accelerate.amazonaws.com",
'x-amz-algorithm': this.clientEncryptionAlgorithm,
'x-amz-credential': credentialPath,
'x-amz-date': this.dateString + 'T000000Z',
'x-amz-signature': signature
}
}
/**
* Ensure all required properties are set in SSM Parameter Store Config
*
* @param {Object} config
* @private
*/
static _validateConfig(config) {
if (!config.hasOwnProperty('bucket')) {
throw "'bucket' is required in SSM Parameter Store Config";
}
if (!config.hasOwnProperty('region')) {
throw "'region' is required in SSM Parameter Store Config";
}
if (!config.hasOwnProperty('accessKey')) {
throw "'accessKey' is required in SSM Parameter Store Config";
}
if (!config.hasOwnProperty('secretKey')) {
throw "'secretKey' is required in SSM Parameter Store Config";
}
}
/**
* Create a special string called a credentials path used in constructing an upload policy
*
* @returns {String}
* @private
*/
_amazonCredentialPath() {
return this.accessKey + '/' + this.dateString + '/' + this.region + '/s3/aws4_request';
}
/**
* Create an upload policy
*
* @param {String} credentialPath
*
* @returns {{expiration: string, conditions: *[]}}
* @private
*/
_s3UploadPolicy(credentialPath) {
return {
expiration: this._getPolicyExpirationISODate(),
conditions: [
{bucket: this.bucket},
{key: this.key},
{acl: this.bucketAcl},
{success_action_status: "201"},
{'x-amz-algorithm': 'AWS4-HMAC-SHA256'},
{'x-amz-credential': credentialPath},
{'x-amz-date': this.dateString + 'T000000Z'}
],
}
}
/**
* ISO formatted date string of when the policy will expire
*
* @returns {String}
* @private
*/
_getPolicyExpirationISODate() {
return new Date((new Date).getTime() + (this.policyExpireMinutes * 60 * 1000)).toISOString();
}
/**
* HMAC encode a string by a given key
*
* @param {String} key
* @param {String} string
*
* @returns {String}
* @private
*/
_encryptHmac(key, string) {
const hmac = crypto.createHmac(
this.encryptionAlgorithm, key
);
hmac.end(string);
return hmac.read();
}
/**
* Create an upload signature from provided params
* https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html#signing-request-intro
*
* @param policyBase64
*
* @returns {String}
* @private
*/
_s3UploadSignature(policyBase64) {
const dateKey = this._encryptHmac('AWS4' + this.secretKey, this.dateString);
const dateRegionKey = this._encryptHmac(dateKey, this.region);
const dateRegionServiceKey = this._encryptHmac(dateRegionKey, 's3');
const signingKey = this._encryptHmac(dateRegionServiceKey, 'aws4_request');
return this._encryptHmac(signingKey, policyBase64).toString('hex');
}
}
module.exports = Token;
The configuration object used is stored in SSM Parameter Store and looks like this
{
"bucket": "my-bucket-name",
"region": "us-west-2",
"bucketAcl": "private",
"accessKey": "MY_ACCESS_KEY",
"secretKey": "MY_SECRET_ACCESS_KEY",
}
Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?
Based on NeverHopeless's elegant solution:
private static readonly KeyValuePair<long, string>[] Thresholds =
{
// new KeyValuePair<long, string>(0, " Bytes"), // Don't devide by Zero!
new KeyValuePair<long, string>(1, " Byte"),
new KeyValuePair<long, string>(2, " Bytes"),
new KeyValuePair<long, string>(1024, " KB"),
new KeyValuePair<long, string>(1048576, " MB"), // Note: 1024 ^ 2 = 1026 (xor operator)
new KeyValuePair<long, string>(1073741824, " GB"),
new KeyValuePair<long, string>(1099511627776, " TB"),
new KeyValuePair<long, string>(1125899906842620, " PB"),
new KeyValuePair<long, string>(1152921504606850000, " EB"),
// These don't fit into a int64
// new KeyValuePair<long, string>(1180591620717410000000, " ZB"),
// new KeyValuePair<long, string>(1208925819614630000000000, " YB")
};
/// <summary>
/// Returns x Bytes, kB, Mb, etc...
/// </summary>
public static string ToByteSize(this long value)
{
if (value == 0) return "0 Bytes"; // zero is plural
for (int t = Thresholds.Length - 1; t > 0; t--)
if (value >= Thresholds[t].Key) return ((double)value / Thresholds[t].Key).ToString("0.00") + Thresholds[t].Value;
return "-" + ToByteSize(-value); // negative bytes (common case optimised to the end of this routine)
}
Maybe there are excessive comments, but I tend to leave them to prevent myself from making the same mistakes over on future visits...
What is the basic difference between the Factory and Abstract Factory Design Patterns?
Factory method: You have a factory that creates objects that derive from a particular base class
Abstract factory: You have a factory that creates other factories, and these factories in turn create objects derived from base classes. You do this because you often don't just want to create a single object (as with Factory method) - rather, you want to create a collection of related objects.
Tuples( or arrays ) as Dictionary keys in C#
If you're on C# 7, you should consider using value tuples as your composite key. Value tuples typically offer better performance than the traditional reference tuples (Tuple<T1, …>
) since value tuples are value types (structs), not reference types, so they avoid the memory allocation and garbage collection costs. Also, they offer conciser and more intuitive syntax, allowing for their fields to be named if you so wish. They also implement the IEquatable<T>
interface needed for the dictionary.
var dict = new Dictionary<(int PersonId, int LocationId, int SubjectId), string>();
dict.Add((3, 6, 9), "ABC");
dict.Add((PersonId: 4, LocationId: 9, SubjectId: 10), "XYZ");
var personIds = dict.Keys.Select(k => k.PersonId).Distinct().ToList();
What are database normal forms and can you give examples?
Here's a quick, admittedly butchered response, but in a sentence:
1NF : Your table is organized as an unordered set of data, and there are no repeating columns.
2NF: You don't repeat data in one column of your table because of another column.
3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.
For more detail, see wikipedia...
How to get a URL parameter in Express?
Express 4.x
To get a URL parameter's value, use req.params
app.get('/p/:tagId', function(req, res) {
res.send("tagId is set to " + req.params.tagId);
});
// GET /p/5
// tagId is set to 5
If you want to get a query parameter ?tagId=5
, then use req.query
app.get('/p', function(req, res) {
res.send("tagId is set to " + req.query.tagId);
});
// GET /p?tagId=5
// tagId is set to 5
Express 3.x
URL parameter
app.get('/p/:tagId', function(req, res) {
res.send("tagId is set to " + req.param("tagId"));
});
// GET /p/5
// tagId is set to 5
Query parameter
app.get('/p', function(req, res) {
res.send("tagId is set to " + req.query("tagId"));
});
// GET /p?tagId=5
// tagId is set to 5
How can I create a unique constraint on my column (SQL Server 2008 R2)?
Set column as unique in SQL Server from the GUI:
They really make you run around the barn to do it with the GUI:
Make sure your column does not violate the unique constraint before you begin.
- Open SQL Server Management Studio.
- Right click your Table, click "Design".
- Right click the column you want to edit, a popup menu appears, click Indexes/Keys.
- Click the "Add" Button.
- Expand the "General" tab.
- Make sure you have the column you want to make unique selected in the "columns" box.
- Change the "Type" box to "Unique Key".
- Click "Close".
- You see a little asterisk in the file window, this means changes are not yet saved.
- Press Save or hit Ctrl+s. It should save, and your column should be unique.
Or set column as unique from the SQL Query window:
alter table location_key drop constraint pinky;
alter table your_table add constraint pinky unique(yourcolumn);
Changes take effect immediately:
Command(s) completed successfully.
Create new project on Android, Error: Studio Unknown host 'services.gradle.org'
I tried above answers and they didn't help in my case.
I solved it with this link help:
http://vjscrazzy.blogspot.co.il/2016/02/failed-to-sync-gradle-project.html
step 1) file>Setttings>appearance and behaviour> system setttings>HTTP
proxy> set No Proxy
step 2) build,execution and deployment> Build tools > gradle> now
under project level settings > select local gradle distribution>
gradle home = F:/Program Files/Android/Android
Studio/gradle/gradle-2.4
After that, I did these changes(because it still wrote me some other errors)
Android Studio asked me:
Android Studio asked me to update my Gradle version (which he didn't before)
Enable - Tools> Android> Enable ADB integration.
Also, if your working in a team with repositories, it's important to check that the version of the Andorid Studio is the same.
How to save the contents of a div as a image?
Do something like this:
A <div>
with ID of #imageDIV
, another one with ID #download
and a hidden <div>
with ID #previewImage
.
Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN
Then add this script:
var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#download").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "image.png").attr("href", newData);
});
The div will be saved as a PNG on clicking the #download
How to disable registration new users in Laravel
This might be new in 5.7, but there is now an options array to the auth method. Simply changing
Auth::routes();
to
Auth::routes(['register' => false]);
in your routes file after running php artisan make:auth
will disable user registration.
Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin
If you want to do without knowing frames beforehand, without subclassing and without Autolayout:
Swift 5 / Swift 4.x / Swift 3.x
extension UITextField {
func setBottomBorder() {
self.borderStyle = .none
self.layer.backgroundColor = UIColor.white.cgColor
self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.gray.cgColor
self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
self.layer.shadowOpacity = 1.0
self.layer.shadowRadius = 0.0
}
}
Call as yourTextField.setBottomBorder()
from anywhere without making sure of the frames to be right.
The Result looks like this:
Swift UI
struct MyTextField: View {
var myPlaceHolder: String
@Binding var text: String
var underColor: Color
var height: CGFloat
var body: some View {
VStack {
TextField(self.myPlaceHolder, text: $text)
.padding()
.font(.title)
Rectangle().frame(height: self.height)
.padding(.horizontal, 24).foregroundColor(self.underColor)
}
}
}
Generating random numbers with Swift
you can use this in specific rate:
let die = [1, 2, 3, 4, 5, 6]
let firstRoll = die[Int(arc4random_uniform(UInt32(die.count)))]
let secondRoll = die[Int(arc4random_uniform(UInt32(die.count)))]
Redirect output of mongo query to a csv file
I know this question is old but I spend an hour trying to export a complex query to csv and I wanted to share my thoughts. First I couldn't get any of the json to csv converters to work (although this one looked promising). What I ended up doing was manually writing the csv file in my mongo script.
This is a simple version but essentially what I did:
print("name,id,email");
db.User.find().forEach(function(user){
print(user.name+","+user._id.valueOf()+","+user.email);
});
This I just piped the query to stdout
mongo test export.js > out.csv
where test
is the name of the database I use.
How to show two figures using matplotlib?
Alternatively to calling plt.show()
at the end of the script, you can also control each figure separately doing:
f = plt.figure(1)
plt.hist........
............
f.show()
g = plt.figure(2)
plt.hist(........
................
g.show()
raw_input()
In this case you must call raw_input
to keep the figures alive.
This way you can select dynamically which figures you want to show
Note: raw_input()
was renamed to input()
in Python 3
PostgreSQL DISTINCT ON with different ORDER BY
Documentation says:
DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).
Official documentation
So you'll have to add the address_id
to the order by.
Alternatively, if you're looking for the full row that contains the most recent purchased product for each address_id
and that result sorted by purchased_at
then you're trying to solve a greatest N per group problem which can be solved by the following approaches:
The general solution that should work in most DBMSs:
SELECT t1.* FROM purchases t1
JOIN (
SELECT address_id, max(purchased_at) max_purchased_at
FROM purchases
WHERE product_id = 1
GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC
A more PostgreSQL-oriented solution based on @hkf's answer:
SELECT * FROM (
SELECT DISTINCT ON (address_id) *
FROM purchases
WHERE product_id = 1
ORDER BY address_id, purchased_at DESC
) t
ORDER BY purchased_at DESC
Problem clarified, extended and solved here: Selecting rows ordered by some column and distinct on another
catch forEach last iteration
The 2018 ES6+ ANSWER IS:
const arr = [1, 2, 3];
arr.forEach((val, key, arr) => {
if (Object.is(arr.length - 1, key)) {
// execute last item logic
console.log(`Last callback call at index ${key} with value ${val}` );
}
});
Why do we need the "finally" clause in Python?
You can use finally
to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception. (Or if you don't catch that specific exception.)
myfile = open("test.txt", "w")
try:
myfile.write("the Answer is: ")
myfile.write(42) # raises TypeError, which will be propagated to caller
finally:
myfile.close() # will be executed before TypeError is propagated
In this example you'd be better off using the with
statement, but this kind of structure can be used for other kinds of resources.
A few years later, I wrote a blog post about an abuse of finally
that readers may find amusing.
How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?
I know one aspect: Although CBC gives better security by changing the IV for each block, it's not applicable to randomly accessed encrypted content (like an encrypted hard disk).
So, use CBC (and the other sequential modes) for sequential streams and ECB for random access.
How do I make a Windows batch script completely silent?
You can redirect stdout to nul
to hide it.
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >nul
Just add >nul
to the commands you want to hide the output from.
Here you can see all the different ways of redirecting the std streams.
When is null or undefined used in JavaScript?
You get undefined for the various scenarios:
You declare a variable with var but never set it.
var foo;
alert(foo); //undefined.
You attempt to access a property on an object you've never set.
var foo = {};
alert(foo.bar); //undefined
You attempt to access an argument that was never provided.
function myFunction (foo) {
alert(foo); //undefined.
}
As cwolves pointed out in a comment on another answer, functions that don't return a value.
function myFunction () {
}
alert(myFunction());//undefined
A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object
and undefined is of type undefined
.
I should also note that null is valid in JSON but undefined is not:
JSON.parse(undefined); //syntax error
JSON.parse(null); //null
Save modifications in place with awk
@sudo_O has the right answer.
This can't work:
someprocess < file > file
The shell performs the redirections before handing control over to someprocess (redirections). The >
redirection will truncate the file to zero size (redirecting output). Therefore, by the time someprocess gets launched and wants to read from the file, there is no data for it to read.
How can I get the external SD card path for Android 4.0+?
In order to retrieve all the External Storages (whether they are SD cards or internal non-removable storages), you can use the following code:
final String state = Environment.getExternalStorageState();
if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) { // we can read the External Storage...
//Retrieve the primary External Storage:
final File primaryExternalStorage = Environment.getExternalStorageDirectory();
//Retrieve the External Storages root directory:
final String externalStorageRootDir;
if ( (externalStorageRootDir = primaryExternalStorage.getParent()) == null ) { // no parent...
Log.d(TAG, "External Storage: " + primaryExternalStorage + "\n");
}
else {
final File externalStorageRoot = new File( externalStorageRootDir );
final File[] files = externalStorageRoot.listFiles();
for ( final File file : files ) {
if ( file.isDirectory() && file.canRead() && (file.listFiles().length > 0) ) { // it is a real directory (not a USB drive)...
Log.d(TAG, "External Storage: " + file.getAbsolutePath() + "\n");
}
}
}
}
Alternatively, you might use System.getenv("EXTERNAL_STORAGE") to retrieve the primary External Storage directory (e.g. "/storage/sdcard0") and System.getenv("SECONDARY_STORAGE") to retieve the list of all the secondary directories (e.g. "/storage/extSdCard:/storage/UsbDriveA:/storage/UsbDriveB"). Remember that, also in this case, you might want to filter the list of secondary directories in order to exclude the USB drives.
In any case, please note that using hard-coded paths is always a bad approach (expecially when every manufacturer may change it as pleased).
Reading Xml with XmlReader in C#
Three years later, perhaps with the renewed emphasis on WebApi and xml data, I came across this question. Since codewise I am inclined to follow Skeet out of an airplane without a parachute, and seeing his initial code doubly corraborated by the MS Xml team article as well as an example in BOL Streaming Transform of Large Xml Docs, I very quickly overlooked the other comments, most specifically from 'pbz', who pointed out that if you have the same elements by name in succession, every other one is skipped because of the double read. And in fact, the BOL and MS blog articles both were parsing source documents with target elements nested deeper than second level, masking this side-effect.
The other answers address this problem. I just wanted to offer a slightly simpler revision that seems to work well so far, and takes into account that the xml might come from different sources, not just a uri, and so the extension works on the user managed XmlReader. The one assumption is that the reader is in its initial state, since otherwise the first 'Read()' might advance past a desired node:
public static IEnumerable<XElement> ElementsNamed(this XmlReader reader, string elementName)
{
reader.MoveToContent(); // will not advance reader if already on a content node; if successful, ReadState is Interactive
reader.Read(); // this is needed, even with MoveToContent and ReadState.Interactive
while(!reader.EOF && reader.ReadState == ReadState.Interactive)
{
// corrected for bug noted by Wes below...
if(reader.NodeType == XmlNodeType.Element && reader.Name.Equals(elementName))
{
// this advances the reader...so it's either XNode.ReadFrom() or reader.Read(), but not both
var matchedElement = XNode.ReadFrom(reader) as XElement;
if(matchedElement != null)
yield return matchedElement;
}
else
reader.Read();
}
}
Windows 8.1 gets Error 720 on connect VPN
Based on the Microsoft support KBs, this can occur if TCP/IP is damaged or is not bound to your dial-up adapter.You can try reinstalling or resetting TCP/IP as follows:
Reset TCP/IP to Original Configuration- Using the NetShell utility,
type this command (in CommandLine): netsh int ip reset [file_name.txt]
,
[file_name.txt] is the name of the file where the actions taken by
NetShell are record, for example netsh hint ip reset fixtcpip.txt.
Remove and re-install NIC – Open Controller and select System. Click
Hardware tab and select devices. Double-click on Network Adapter and
right-click on the NIC, select Uninstall. Restart the computer and
the Windows should auto detect the NIC and re-install it.
- Upgrade the NIC driver – You may download the latest NIC driver and
upgrade the driver.
Hope it could help.
Java abstract interface
It is not necessary to declare the interface abstract.
Just like declaring all those methods public (which they already are if the interface is public) or abstract (which they already are in an interface) is redundant.
No one is stopping you, though.
Other things you can explicitly state, but don't need to:
- call super() on the first line of a constructor
extends Object
- implement inherited interfaces
Is there other rules that applies with an abstract interface?
An interface is already "abstract". Applying that keyword again makes absolutely no difference.
How to preSelect an html dropdown list with php?
This answer is not relevant for particular recepient, but maybe useful for others.
I had similiar issue with 'selecting' right 'option' by value returned from database.
I solved it by adding additional tag with applied display:none.
<?php
$status = "NOT_ON_LIST";
$text = "<html>
<head>
</head>
<body>
<select id=\"statuses\">
<option value=\"status\" selected=\"selected\" style=\"display:none\">$status</option>
<option value=\"status\">OK</option>
<option value=\"status\">DOWN</option>
<option value=\"status\">UNKNOWN</option>
</select>
</body>
</html>";
print $text;
?>
How to check version of python modules?
This works in Jupyter Notebook on Windows, too! As long as Jupyter is launched from a bash-compliant command line such as Git Bash (MingW64), the solutions given in many of the answers can be used in Jupyter Notebook on Windows systems with one tiny tweak.
I'm running windows 10 Pro with Python installed via Anaconda, and the following code works when I launch Jupyter via Git Bash (but does not when I launch from the Anaconda prompt).
The tweak: Add an exclamation mark (!
) in front of pip
to make it !pip
.
>>>!pip show lxml | grep Version
Version: 4.1.0
>>>!pip freeze | grep lxml
lxml==4.1.0
>>>!pip list | grep lxml
lxml 4.1.0
>>>!pip show lxml
Name: lxml
Version: 4.1.0
Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
Home-page: http://lxml.de/
Author: lxml dev team
Author-email: [email protected]
License: BSD
Location: c:\users\karls\anaconda2\lib\site-packages
Requires:
Required-by: jupyter-contrib-nbextensions
HashSet vs. List performance
It's essentially pointless to compare two structures for performance that behave differently. Use the structure that conveys the intent. Even if you say your List<T>
wouldn't have duplicates and iteration order doesn't matter making it comparable to a HashSet<T>
, its still a poor choice to use List<T>
because its relatively less fault tolerant.
That said, I will inspect some other aspects of performance,
+------------+--------+-------------+-----------+----------+----------+-----------+
| Collection | Random | Containment | Insertion | Addition | Removal | Memory |
| | access | | | | | |
+------------+--------+-------------+-----------+----------+----------+-----------+
| List<T> | O(1) | O(n) | O(n) | O(1)* | O(n) | Lesser |
| HashSet<T> | O(n) | O(1) | n/a | O(1) | O(1) | Greater** |
+------------+--------+-------------+-----------+----------+----------+-----------+
Even though addition is O(1) in both cases, it will be relatively slower in HashSet since it involves cost of precomputing hash code before storing it.
The superior scalability of HashSet has a memory cost. Every entry is stored as a new object along with its hash code. This article might give you an idea.
How to increase Java heap space for a tomcat app
Easiest way of doing is: (In Linux/Ububuntu e.t.c)
Go to tomcat bin directory:
cd /opt/tomcat8.5/bin
create new file under bin directory "setenv.sh" and save below mention entries in it.
export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx2048m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"
and issue command:
./catalina.sh run
In your catalina log file you can see entry like this:
INFO [main] VersionLoggerListener.log Command line argument: -Xms512m
INFO [main] VersionLoggerListener.log Command line argument: -Xmx2048m
INFO [main] VersionLoggerListener.log Command line argument: -XX:MaxPermSize=256m
Which confirms that above changes took place.
Also, the value of "Xms512m" and "-Xmx2048m" can be modified accordingly in the setenv.sh file.
Startup of tomcat could be done in two steps as well.
cd /opt/tomcat8.5/bin
Step #1
run ./setenv.sh
Step #2
./startup.sh
If you're using systemd edit:
/usr/lib/systemd/system/tomcat8.service
and set
Environment=CATALINA_OPTS="-Xms512M -Xmx2048M -XX:MaxPermSize=256m"
How do I get my C# program to sleep for 50 msec?
You can't specify an exact sleep time in Windows. You need a real-time OS for that. The best you can do is specify a minimum sleep time. Then it's up to the scheduler to wake up your thread after that. And never call .Sleep()
on the GUI thread.
Fixed positioning in Mobile Safari
<meta name="viewport" content="width=320, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
Also making sure height=device-height
is not present in this meta tag helps prevent additional footer padding that normally would not exist on the page. The menubar height adds to the viewport height causing a fixed background to become scrollable.
Delaying AngularJS route change until model loaded to prevent flicker
This commit, which is part of version 1.1.5 and above, exposes the $promise
object of $resource
. Versions of ngResource including this commit allow resolving resources like this:
$routeProvider
resolve: {
data: function(Resource) {
return Resource.get().$promise;
}
}
controller
app.controller('ResourceCtrl', ['$scope', 'data', function($scope, data) {
$scope.data = data;
}]);
Getting output of system() calls in Ruby
You can use system() or %x[] depending what kind of result you need.
system() returning true if the command was found and ran successfully, false otherwise.
>> s = system 'uptime'
10:56 up 3 days, 23:10, 2 users, load averages: 0.17 0.17 0.14
=> true
>> s.class
=> TrueClass
>> $?.class
=> Process::Status
%x[..] on the other hand saves the results of the command as a string:
>> result = %x[uptime]
=> "13:16 up 4 days, 1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> p result
"13:16 up 4 days, 1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> result.class
=> String
Th blog post by Jay Fields explains in detail the differences between using system, exec and %x[..] .
Replace all whitespace with a line break/paragraph mark to make a word list
For reasonably modern versions of sed, edit the standard input to yield the standard output with
$ echo 't???? ß?ß??? ?? ??p??' | sed -E -e 's/[[:blank:]]+/\n/g'
t????
ß?ß???
??
??p??
If your vocabulary words are in files named lesson1
and lesson2
, redirect sed’s standard output to the file all-vocab
with
sed -E -e 's/[[:blank:]]+/\n/g' lesson1 lesson2 > all-vocab
What it means:
- The character class
[[:blank:]]
matches either a single space character or
a single tab character.
- Use
[[:space:]]
instead to match any single whitespace character (commonly space, tab, newline, carriage return, form-feed, and vertical tab).
- The
+
quantifier means match one or more of the previous pattern.
- So
[[:blank:]]+
is a sequence of one or more characters that are all space or tab.
- The
\n
in the replacement is the newline that you want.
- The
/g
modifier on the end means perform the substitution as many times as possible rather than just once.
- The
-E
option tells sed to use POSIX extended regex syntax and in particular for this case the +
quantifier. Without -E
, your sed command becomes sed -e 's/[[:blank:]]\+/\n/g'
. (Note the use of \+
rather than simple +
.)
Perl Compatible Regexes
For those familiar with Perl-compatible regexes and a PCRE-capable sed, use \s+
to match runs of at least one whitespace character, as in
sed -E -e 's/\s+/\n/g' old > new
or
sed -e 's/\s\+/\n/g' old > new
These commands read input from the file old
and write the result to a file named new
in the current directory.
Maximum portability, maximum cruftiness
Going back to almost any version of sed since Version 7 Unix, the command invocation is a bit more baroque.
$ echo 't???? ß?ß??? ?? ??p??' | sed -e 's/[ \t][ \t]*/\
/g'
t????
ß?ß???
??
??p??
Notes:
- Here we do not even assume the existence of the humble
+
quantifier and simulate it with a single space-or-tab ([ \t]
) followed by zero or more of them ([ \t]*
).
- Similarly, assuming sed does not understand
\n
for newline, we have to include it on the command line verbatim.
- The
\
and the end of the first line of the command is a continuation marker that escapes the immediately following newline, and the remainder of the command is on the next line.
- Note: There must be no whitespace preceding the escaped newline. That is, the end of the first line must be exactly backslash followed by end-of-line.
- This error prone process helps one appreciate why the world moved to visible characters, and you will want to exercise some care in trying out the command with copy-and-paste.
Note on backslashes and quoting
The commands above all used single quotes (''
) rather than double quotes (""
). Consider:
$ echo '\\\\' "\\\\"
\\\\ \\
That is, the shell applies different escaping rules to single-quoted strings as compared with double-quoted strings. You typically want to protect all the backslashes common in regexes with single quotes.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
PUT vs. POST in REST
At the risk of restating what has already been said, it seems important to remember that PUT implies that the client controls what the URL is going to end up being, when creating a resource. So part of the choice between PUT and POST is going to be about how much you can trust the client to provide correct, normalized URL that are coherent with whatever your URL scheme is.
When you can't fully trust the client to do the right thing, it would be
more appropriate to use POST to create a new item and then send the URL back to the client in the response.
How to convert an int value to string in Go?
package main
import (
"fmt"
"strconv"
)
func main(){
//First question: how to get int string?
intValue := 123
// keeping it in separate variable :
strValue := strconv.Itoa(intValue)
fmt.Println(strValue)
//Second question: how to concat two strings?
firstStr := "ab"
secondStr := "c"
s := firstStr + secondStr
fmt.Println(s)
}
Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.
@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {
@ApiObjectField(description = "The code which is to be verified.")
@NotBlank(message = "mandatory")
private final String code;
@ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
private final String maskedMobileNumber;
public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
public String getcode() {
return code;
}
public String getMaskedMobileNumber() {
return maskedMobileNumber;
}
}
The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been
public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
Saving awk output to variable
as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.
awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:
variable=$(ps -ef | awk '/port 10 \-/ {print $12}')
variable=`ps -ef | awk '/port 10 \-/ {print $12}'`
The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.
Preferred way of loading resources in Java
Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
Changes in import statement python3
To support both Python 2 and Python 3, use explicit relative imports as below. They are relative to the current module. They have been supported starting from 2.5.
from .sister import foo
from . import brother
from ..aunt import bar
from .. import uncle
Java Inheritance - calling superclass method
Whenever you create child class object then that object has all the features of parent class.
Here Super() is the facilty for accession parent.
If you write super() at that time parents's default constructor is called.
same if you write super.
this keyword refers the current object same as super key word facilty for accessing parents.
How to pass data from Javascript to PHP and vice versa?
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
Change language of Visual Studio 2017 RC
I solved this just created label on desktop with option/parameter --locale en-US
"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vs_installer.exe" --locale en-US
How to scp in Python?
Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.
Question mark characters displaying within text, why is this?
I usually curse MS word and then run the following Wscript.
// replace with path to a file that needs cleaning
PATH = "test.html"
var go=WScript.CreateObject("Scripting.FileSystemObject");
var content=go.GetFile(PATH).OpenAsTextStream().ReadAll();
var out=go.CreateTextFile("clean-"+PATH, true);
// symbols
content=content.replace(/“/g,'"');
content=content.replace(/”/g,'"');
content=content.replace(/’/g,"'");
content=content.replace(/–/g,"-");
content=content.replace(/©/g,"©");
content=content.replace(/®/g,"®");
content=content.replace(/°/g,"°");
content=content.replace(/¶/g,"<p>");
content=content.replace(/¿/g,"¿");
content=content.replace(/¡/g,'¡');
content=content.replace(/¢/g,'¢');
content=content.replace(/£/g,'£');
content=content.replace(/¥/g,'¥');
out.Write(content);
How do I display a text file content in CMD?
If you want it to display the content of the file live, and update when the file is altered, just use this script:
@echo off
:start
cls
type myfile.txt
goto start
That will repeat forever until you close the cmd window.
Rounding a number to the nearest 5 or 10 or X
I cannot add comment so I will use this
in a vbs run that and have fun figuring out why the 2 give a result of 2
you can't trust round
msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too
How to multiply values using SQL
Why are you grouping by? Do you mean order by?
SELECT player_name, player_salary, player_salary * 1.1 AS NewSalary
FROM players
ORDER BY player_salary, player_name;
JSON and escaping characters
hmm, well here's a workaround anyway:
function JSON_stringify(s, emit_unicode)
{
var json = JSON.stringify(s);
return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
test case:
js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"
jQuery textbox change event
The HTML4 spec for the <input>
element specifies the following script events are available:
onfocus, onblur, onselect, onchange,
onclick, ondblclick, onmousedown,
onmouseup, onmouseover, onmousemove,
onmouseout, onkeypress, onkeydown,
onkeyup
here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/
I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change
How can I match on an attribute that contains a certain string?
For the links which contains common url have to console in a variable. Then attempt it sequentially.
webelements allLinks=driver.findelements(By.xpath("//a[contains(@href,'http://122.11.38.214/dl/appdl/application/apk')]"));
int linkCount=allLinks.length();
for(int i=0; <linkCount;i++)
{
driver.findelement(allLinks[i]).click();
}
How can I insert values into a table, using a subquery with more than one result?
If you are inserting one record into your table, you can do
INSERT INTO yourTable
VALUES(value1, value2)
But since you want to insert more than one record, you can use a SELECT FROM
in your SQL statement.
so you will want to do this:
INSERT INTO prices (group, id, price)
SELECT 7, articleId, 1.50
from article
WHERE name LIKE 'ABC%'
Add days Oracle SQL
It's Simple.You can use
select (sysdate+2) as new_date from dual;
This will add two days from current date.
How to center an iframe horizontally?
Here I have put snippet for all of you who are suffering to make iframe or image in center of the screen horizontally.
Give me THUMBS UP VOTE if you like.?.
style > img & iframe > this is your tag name so change that if you're want any other tag in center
_x000D_
_x000D_
<html >_x000D_
<head> _x000D_
<style type=text/css>_x000D_
div{}_x000D_
img{_x000D_
margin: 0 auto;_x000D_
display:block;_x000D_
}_x000D_
iframe{ _x000D_
margin: 0 auto;_x000D_
display:block;_x000D_
}_x000D_
_x000D_
</style>_x000D_
</head>_x000D_
<body >_x000D_
_x000D_
<iframe src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4" width="320" height="180" frameborder="0" allowfullscreen="allowfullscreen"></iframe> _x000D_
_x000D_
<img src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg" width="320" height="180" />_x000D_
</body> _x000D_
</html>
_x000D_
_x000D_
_x000D_
type checking in javascript
A number is an integer if its modulo %1 is 0-
function isInt(n){
return (typeof n== 'number' && n%1== 0);
}
This is only as good as javascript gets- say +- ten to the 15th.
isInt(Math.pow(2,50)+.1)
returns true
, as does
Math.pow(2,50)+.1 == Math.pow(2,50)
Is there any way to set environment variables in Visual Studio Code?
For more advanced Go language scenarios, you can load an environment file, like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "${workspaceFolder}",
"envFile": "${workspaceFolder}/.env",
"args": [],
"showLog": true
}
]
}
Place the .env file in your folder and add vars like this:
KEY1="TEXT_VAL1"
KEY2='{"key1":val1","key2":"val2"}'
Details: https://medium.com/@reuvenharrison/using-visual-studio-code-to-debug-a-go-program-with-environment-variables-523fea268271
What order are the Junit @Before/@After called?
This isn't an answer to the tagline question, but it is an answer to the problems mentioned in the body of the question. Instead of using @Before or @After, look into using @org.junit.Rule because it gives you more flexibility. ExternalResource (as of 4.7) is the rule you will be most interested in if you are managing connections. Also, If you want guaranteed execution order of your rules use a RuleChain (as of 4.10). I believe all of these were available when this question was asked. Code example below is copied from ExternalResource's javadocs.
public static class UsesExternalResource {
Server myServer= new Server();
@Rule
public ExternalResource resource= new ExternalResource() {
@Override
protected void before() throws Throwable {
myServer.connect();
};
@Override
protected void after() {
myServer.disconnect();
};
};
@Test
public void testFoo() {
new Client().run(myServer);
}
}
What is exactly the base pointer and stack pointer? To what do they point?
ESP
is the current stack pointer, which will change any time a word or address is pushed or popped onto/off off the stack. EBP
is a more convenient way for the compiler to keep track of a function's parameters and local variables than using the ESP
directly.
Generally (and this may vary from compiler to compiler), all of the arguments to a function being called are pushed onto the stack by the calling function (usually in the reverse order that they're declared in the function prototype, but this varies). Then the function is called, which pushes the return address (EIP
) onto the stack.
Upon entry to the function, the old EBP
value is pushed onto the stack and EBP
is set to the value of ESP
. Then the ESP
is decremented (because the stack grows downward in memory) to allocate space for the function's local variables and temporaries. From that point on, during the execution of the function, the arguments to the function are located on the stack at positive offsets from EBP
(because they were pushed prior to the function call), and the local variables are located at negative offsets from EBP
(because they were allocated on the stack after the function entry). That's why the EBP
is called the Frame Pointer, because it points to the center of the function call frame.
Upon exit, all the function has to do is set ESP
to the value of EBP
(which deallocates the local variables from the stack, and exposes the entry EBP
on the top of the stack), then pop the old EBP
value from the stack, and then the function returns (popping the return address into EIP
).
Upon returning back to the calling function, it can then increment ESP
in order to remove the function arguments it pushed onto the stack just prior to calling the other function. At this point, the stack is back in the same state it was in prior to invoking the called function.
Pipe output and capture exit status in Bash
There is an internal Bash variable called $PIPESTATUS
; it’s an array that holds the exit status of each command in your last foreground pipeline of commands.
<command> | tee out.txt ; test ${PIPESTATUS[0]} -eq 0
Or another alternative which also works with other shells (like zsh) would be to enable pipefail:
set -o pipefail
...
The first option does not work with zsh
due to a little bit different syntax.
How to disable compiler optimizations in gcc?
Long time ago, but still needed.
info - https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
list - gcc -Q --help=optimizers test.c | grep enabled
disable as many as you like with:
gcc **-fno-web** -Q --help=optimizers test.c | grep enabled
How to make a HTML list appear horizontally instead of vertically using CSS only?
You will have to use something like below
_x000D_
_x000D_
#menu ul{_x000D_
list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
<div id="menu">_x000D_
<ul>_x000D_
<li>First menu item</li>_x000D_
<li>Second menu item</li>_x000D_
<li>Third menu item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Why doesn't catching Exception catch RuntimeException?
The premise of the question is flawed, because catching Exception
does catch RuntimeException
. Demo code:
public class Test {
public static void main(String[] args) {
try {
throw new RuntimeException("Bang");
} catch (Exception e) {
System.out.println("I caught: " + e);
}
}
}
Output:
I caught: java.lang.RuntimeException: Bang
Your loop will have problems if:
callbacks
is null
- anything modifies
callbacks
while the loop is executing (if it were a collection rather than an array)
Perhaps that's what you're seeing?
Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536
You can follow this.
Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex support library to your project:
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:
android {
defaultConfig {
...
minSdkVersion 21
targetSdkVersion 28
multiDexEnabled true
}
...
}
What is the relative performance difference of if/else versus switch statement in Java?
Use switch!
I hate to maintain if-else-blocks! Have a test:
public class SpeedTestSwitch
{
private static void do1(int loop)
{
int temp = 0;
for (; loop > 0; --loop)
{
int r = (int) (Math.random() * 10);
switch (r)
{
case 0:
temp = 9;
break;
case 1:
temp = 8;
break;
case 2:
temp = 7;
break;
case 3:
temp = 6;
break;
case 4:
temp = 5;
break;
case 5:
temp = 4;
break;
case 6:
temp = 3;
break;
case 7:
temp = 2;
break;
case 8:
temp = 1;
break;
case 9:
temp = 0;
break;
}
}
System.out.println("ignore: " + temp);
}
private static void do2(int loop)
{
int temp = 0;
for (; loop > 0; --loop)
{
int r = (int) (Math.random() * 10);
if (r == 0)
temp = 9;
else
if (r == 1)
temp = 8;
else
if (r == 2)
temp = 7;
else
if (r == 3)
temp = 6;
else
if (r == 4)
temp = 5;
else
if (r == 5)
temp = 4;
else
if (r == 6)
temp = 3;
else
if (r == 7)
temp = 2;
else
if (r == 8)
temp = 1;
else
if (r == 9)
temp = 0;
}
System.out.println("ignore: " + temp);
}
public static void main(String[] args)
{
long time;
int loop = 1 * 100 * 1000 * 1000;
System.out.println("warming up...");
do1(loop / 100);
do2(loop / 100);
System.out.println("start");
// run 1
System.out.println("switch:");
time = System.currentTimeMillis();
do1(loop);
System.out.println(" -> time needed: " + (System.currentTimeMillis() - time));
// run 2
System.out.println("if/else:");
time = System.currentTimeMillis();
do2(loop);
System.out.println(" -> time needed: " + (System.currentTimeMillis() - time));
}
}
My C# standard code for benchmarking
latex tabular width the same as the textwidth
The tabularx
package gives you
- the total width as a first parameter, and
- a new column type
X
, all X
columns will grow to fill up the total width.
For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
Print Pdf in C#
It is also possible to do it with an embedded web browser, note however that since this might be a local file, and also because it is not actually the browser directly and there is no DOM so there is no ready state.
Here is the code for the approach I worked out on a win form web browser control:
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate(@"path\to\file");
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
//Progress Changed fires multiple times, however after the Navigated event it is fired only once,
//and at this point it is ready to print
webBrowser1.ProgressChanged += (o, args) =>
{
webBrowser1.Print();//Note this does not print only brings up the print preview dialog
//Should be on a separate task to ensure the main thread
//can fully initialize the print dialog
Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);//We need to wait before we can send enter
//This assumes that the print preview is still in focus
Action g = () =>
{
SendKeys.SendWait("{ENTER}");
};
this.Invoke(g);
});
};
}
Slide right to left?
I ran into a similar problem while trying to code a menu for small screen sizes.
The solution I went with was to just shov it off the viewport.
I made this using SASS and JQuery (No JQuery UI), but this could all be achieved in native JS and CSS.
https://codepen.io/maxbethke/pen/oNzMLRa
_x000D_
_x000D_
var menuOpen = false
var init = () => {
$(".menu__toggle, .menu__blackout").on("click", menuToggle)
}
var menuToggle = () => {
console.log("Menu:Toggle");
$(".menu__blackout").fadeToggle();
if(menuOpen) { // close menu
$(".menu__collapse").css({
left: "-80vw",
right: "100vw"
});
} else { // open menu
$(".menu__collapse").css({
left: "0",
right: "20vw"
});
}
menuOpen = !menuOpen;
}
$(document).ready(init);
_x000D_
.menu__toggle {
position: absolute;
right: 0;
z-index: 1;
}
.menu__blackout {
display: none;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 10;
}
.menu__collapse {
position: absolute;
top: 0;
right: 100vw;
bottom: 0;
left: -80vw;
background: white;
-webkit-transition: ease-in-out all 1s;
transition: ease-in-out all 1s;
z-index: 11;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="menu__toggle">Toggle menu</button>
<menu class="menu">
<div class="menu__blackout"></div>
<div class="menu__collapse">
<ul class="list">
<li class="list__item">
<a class="list__item__link" href="#section1">Menu Item 1</a>
</li>
<li class="list__item">
<a class="list__item__link" href="#section2">Menu Item 2</a>
</li>
<li class="list__item">
<a class="list__item__link" href="#section3">Menu Item 3</a>
</li>
<li class="list__item">
<a class="list__item__link" href="#section4">Menu Item 4</a>
</li>
<li class="list__item">
<a class="list__item__link" href="#section5">Menu Item 5</a>
</li>
</ul>
</div>
</menu>
_x000D_
_x000D_
_x000D_
How to insert element into arrays at specific position?
For your first array, use array_splice()
:
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
array_splice($array_1, 3, 0, 'more');
print_r($array_1);
output:
Array(
[0] => zero
[1] => one
[2] => two
[3] => more
[4] => three
)
for the second one there is no order so you just have to do :
$array_2['more'] = '2.5';
print_r($array_2);
And sort the keys by whatever you want.
Shell script to get the process ID on Linux
If you already know the process then this will be useful:
PID=`ps -eaf | grep <process> | grep -v grep | awk '{print $2}'`
if [[ "" != "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
fi
How to copy a huge table data into another table in SQL Server
If your focus is Archiving (DW) and are dealing with VLDB with 100+ partitioned tables and you want to isolate most of these resource intensive work on a non production server (OLTP) here is a suggestion (OLTP -> DW)
1) Use backup / Restore to get the data onto the archive server (so now, on Archive or DW you will have Stage and Target database)
2) Stage database: Use partition switch to move data to corresponding stage table
3) Use SSIS to transfer data from staged database to target database for each staged table on both sides
4) Target database: Use partition switch on target database to move data from stage to base table
Hope this helps.
How to recursively delete an entire directory with PowerShell 2.0?
When deleting files recursively using a simple Remove-Item "folder" -Recurse
I sometimes see an intermittent error : [folder] cannot be removed because it is not empty.
This answer attempts to prevent that error by individually deleting the files.
function Get-Tree($Path,$Include='*') {
@(Get-Item $Path -Include $Include -Force) +
(Get-ChildItem $Path -Recurse -Include $Include -Force) |
sort pspath -Descending -unique
}
function Remove-Tree($Path,$Include='*') {
Get-Tree $Path $Include | Remove-Item -force -recurse
}
Remove-Tree some_dir
An important detail is the sorting of all the items with pspath -Descending
so that the leaves are deleted before the roots. The sorting is done on the pspath
parameter since that has more chance of working for providers other than the file system. The -Include
parameter is just a convenience if you want to filter the items to delete.
It's split into two functions since I find it useful to see what I'm about to delete by running
Get-Tree some_dir | select fullname
HttpContext.Current.User.Identity.Name is Empty
I struggled with this problem the past few days.
I suggest reading Scott Guthrie's blog post Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application
For me the problem was that although I had Windows Authentication enabled in IIS and I had <authentication mode="Windows" />
in the <system.web>
section of web.config, I was not preventing anonymous access. This last part was the key. You need to prevent anonymous access to ensure that the browser sends the credentials.
You can either configure IIS in Control Panel so that your site (or machine) uses Windows authentication and denies anonymous access or you can add the following to your web.config in the system.web section:
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
Docker remove <none> TAG images
You can go docker rmi $(docker images -f "dangling=true" -q)
. See the images documentation for more options.
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> 94870cda569b 4 seconds ago 673MB
python 2.7 320a06f42b5f 10 days ago 673MB
mysql latest e799c7f9ae9c 2 months ago 407MB
gcavalcante8808/semaphore latest 86e863e11461 2 months ago 537MB
redis latest e32ef7250bc1 2 months ago 184MB
rabbitmq 3.6.9-management 7e69e14cc496 2 months ago 179MB
rabbitmq 3.6.9 eb2e4968538a 2 months ago 179MB
jordan/rundeck latest 6d40b57b1572 2 months ago 660MB
rabbitmq 3.5.6-management dbfe8d18809a 19 months ago 304MB
$ docker rmi $(docker images --format '{{.ID}}' --filter=dangling=true)
Deleted: sha256:94870cda569b8cf5f42be25af107d464c993b4502a1472c1679bf2d213b6c0a6
How to write a comment in a Razor view?
Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.
Server side Comments:
Razor .cshtml
Like so:
@* Comment goes here *@
.aspx
For those looking for the older .aspx
view (and Asp.Net WebForms) server side comment syntax:
<%-- Comment goes here --%>
Client Side Comments
HTML Comment
<!-- Comment goes here -->
Javascript Comment
// One line Comment goes Here
/* Multiline comment
goes here */
As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).
How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?
[Updated to adapt to modern pandas
, which has isnull
as a method of DataFrame
s..]
You can use isnull
and any
to build a boolean Series and use that to index into your frame:
>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
>>> df.isnull().any(axis=1)
0 False
1 True
2 True
3 False
4 False
dtype: bool
>>> df[df.isnull().any(axis=1)]
0 1 2
1 0 NaN 0
2 0 0 NaN
[For older pandas
:]
You could use the function isnull
instead of the method:
In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
In [57]: df
Out[57]:
0 1 2
0 0 1 2
1 0 NaN 0
2 0 0 NaN
3 0 1 2
4 0 1 2
In [58]: pd.isnull(df)
Out[58]:
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
In [59]: pd.isnull(df).any(axis=1)
Out[59]:
0 False
1 True
2 True
3 False
4 False
leading to the rather compact:
In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]:
0 1 2
1 0 NaN 0
2 0 0 NaN
How to convert a file into a dictionary?
import re
my_file = open('file.txt','r')
d = {}
for i in my_file:
g = re.search(r'(\d+)\s+(.*)', i) # glob line containing an int and a string
d[int(g.group(1))] = g.group(2)
How to link home brew python version and set it as default
After installing python3 with brew install python3
I was getting the error:
Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/Frameworks
Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks
After typing brew link python3
the error was:
Linking /usr/local/Cellar/python/3.6.4_3... Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks
To solve the problem:
sudo mkdir -p /usr/local/Frameworks
sudo chown -R $(whoami) /usr/local/*
brew link python3
After this, I could open python3 by typing python3
(From https://github.com/Homebrew/homebrew-core/issues/20985)
How to determine the encoding of text?
If you know the some content of the file you can try to decode it with several encoding and see which is missing. In general there is no way since a text file is a text file and those are stupid ;)
Redirect to new Page in AngularJS using $location
It might help you!
AngularJs Code-sample
var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
$scope.ClickMeToRedirect = function () {
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
};
});
HTML Code-sample
<div ng-app="urlApp">
<div ng-controller="urlCtrl">
Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
</div>
</div>
How do I run pip on python for windows?
I have a Mac, but luckily this should work the same way:
pip
is a command-line thing. You don't run it in python.
For example, on my Mac, I just say:
$pip install somelib
pretty easy!
Blocks and yields in Ruby
There are two points I want to make about yield here. First, while a lot of answers here talk about different ways to pass a block to a method which uses yield, let's also talk about the control flow. This is especially relevant since you can yield MULTIPLE times to a block. Let's take a look at an example:
class Fruit
attr_accessor :kinds
def initialize
@kinds = %w(orange apple pear banana)
end
def each
puts 'inside each'
3.times { yield (@kinds.tap {|kinds| puts "selecting from #{kinds}"} ).sample }
end
end
f = Fruit.new
f.each do |kind|
puts 'inside block'
end
=> inside each
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
When the each method is invoked, it executes line by line. Now when we get to the 3.times block, this block will be invoked 3 times. Each time it invokes yield. That yield is linked to the block associated with the method that called the each method. It is important to notice that each time yield is invoked, it returns control back to the block of the each method in client code. Once the block is finished executing, it returns back to the 3.times block. And this happens 3 times. So that block in client code is invoked on 3 separate occasions since yield is explicitly called 3 separate times.
My second point is about enum_for and yield. enum_for instantiates the Enumerator class and this Enumerator object also responds to yield.
class Fruit
def initialize
@kinds = %w(orange apple)
end
def kinds
yield @kinds.shift
yield @kinds.shift
end
end
f = Fruit.new
enum = f.to_enum(:kinds)
enum.next
=> "orange"
enum.next
=> "apple"
So notice every time we invoke kinds with the external iterator, it will invoke yield only once. The next time we call it, it will invoke the next yield and so on.
There's an interesting tidbit with regards to enum_for. The documentation online states the following:
enum_for(method = :each, *args) ? enum
Creates a new Enumerator which will enumerate by calling method on obj, passing args if any.
str = "xyz"
enum = str.enum_for(:each_byte)
enum.each { |b| puts b }
# => 120
# => 121
# => 122
If you do not specify a symbol as an argument to enum_for, ruby will hook the enumerator to the receiver's each method. Some classes do not have an each method, like the String class.
str = "I like fruit"
enum = str.to_enum
enum.next
=> NoMethodError: undefined method `each' for "I like fruit":String
Thus, in the case of some objects invoked with enum_for, you must be explicit as to what your enumerating method will be.
What is difference between Errors and Exceptions?
Error is something that most of the time you cannot handle it.
Exception was meant to give you an opportunity to do something with it. like try something else or write to the log.
try{
//connect to database 1
}
catch(DatabaseConnctionException err){
//connect to database 2
//write the err to log
}
How to enter in a Docker container already running with a new TTY
nsenter
does that. However I also needed to enter a container in a simple way and nsenter didn't suffice for my needs. It was buggy in some occasions (black screen plus -wd flag not working). Furthermore I wanted to login as a specific user and in a specific directory.
I ended up making my own tool to enter containers. You can find it at: https://github.com/Pithikos/docker-enter
Its usage is as easy as
./docker-enter [-u <user>] [-d <directory>] <container ID>
Testing if a site is vulnerable to Sql Injection
The test has to be done on a page that queries a database so yes typically that is a login page because it's the page that can do the most harm but could be an unsecure page as well.
Generally you would have your database queries behind a secure login but if you just have a listing of items or something that you don't care if the world sees a hacker could append some sql injection to the end of the querystring.
The key with SQL Injection is the person doing the injection would have to know that your querying a database so if your not querying a database then no sql inject can be done. If your form is submitting to a database then yes they could SQL Inject that. It's always good practice to use either stored procedures to select/insert/update/delete or make sure you prepare or escape out all the statements that will be hitting the database.
Setting selected values for ng-options bound select elements
Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2
_x000D_
_x000D_
<select ng-model="objBillingAddress.StateId" >_x000D_
<option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
How to download image from url
.net Framework allows PictureBox Control to Load Images from url
and Save image in Laod Complete Event
protected void LoadImage() {
pictureBox1.ImageLocation = "PROXY_URL;}
void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e) {
pictureBox1.Image.Save(destination); }
Setting individual axis limits with facet_wrap and scales = "free" in ggplot2
I am not sure I understand what you want, but based on what I understood
the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"
you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")
worked for me, see the picture
I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code
Android: Getting "Manifest merger failed" error after updating to a new version of gradle
I'm not using different versions of libraries and got the same error, it's happened after remove buildToolsVersion
in AS RC 1, but adding tools:node="replace"
did the trick, just add this into your manifest.xml inside <application ..../>
block:
<meta-data
tools:node="replace"
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
ZIP file content type for HTTP request
If you want the MIME type for a file, you can use the following code:
- (NSString *)mimeTypeForPath:(NSString *)path
{
// get a mime type for an extension using MobileCoreServices.framework
CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
assert(UTI != NULL);
NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
assert(mimetype != NULL);
CFRelease(UTI);
return mimetype;
}
In the case of a ZIP file, this will return application/zip
.
How do you automatically set text box to Uppercase?
Try below solution, This will also take care when a user enters only blank space in the input field at the first index.
_x000D_
_x000D_
document.getElementById('capitalizeInput').addEventListener("keyup", () => {_x000D_
var inputValue = document.getElementById('capitalizeInput')['value']; _x000D_
if (inputValue[0] === ' ') {_x000D_
inputValue = '';_x000D_
} else if (inputValue) {_x000D_
inputValue = inputValue[0].toUpperCase() + inputValue.slice(1);_x000D_
}_x000D_
document.getElementById('capitalizeInput')['value'] = inputValue;_x000D_
});
_x000D_
<input type="text" id="capitalizeInput" autocomplete="off" />
_x000D_
_x000D_
_x000D_
Create a sample login page using servlet and JSP?
You're comparing the message with the empty string using ==
.
First, your comparison is wrong because the message will be null (and not the empty string).
Second, it's wrong because Objects must be compared with equals()
and not with ==
.
Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:
<c:id test="${!empty message}">
<c:out value="${message}"/>
</c:if>
Creating your own header file in C
foo.h
#ifndef FOO_H_ /* Include guard */
#define FOO_H_
int foo(int x); /* An example function declaration */
#endif // FOO_H_
foo.c
#include "foo.h" /* Include the header (not strictly necessary here) */
int foo(int x) /* Function definition */
{
return x + 5;
}
main.c
#include <stdio.h>
#include "foo.h" /* Include the header here, to obtain the function declaration */
int main(void)
{
int y = foo(3); /* Use the function here */
printf("%d\n", y);
return 0;
}
To compile using GCC
gcc -o my_app main.c foo.c
How to diff a commit with its parent?
If you know how far back, you can try something like:
# Current branch vs. parent
git diff HEAD^ HEAD
# Current branch, diff between commits 2 and 3 times back
git diff HEAD~3 HEAD~2
Prior commits work something like this:
# Parent of HEAD
git show HEAD^1
# Grandparent
git show HEAD^2
There are a lot of ways you can specify commits:
# Great grandparent
git show HEAD~3
See this page for details.
Database Structure for Tree Data Structure
You mention the most commonly implemented, which is Adjacency List:
https://blogs.msdn.microsoft.com/mvpawardprogram/2012/06/25/hierarchies-convert-adjacency-list-to-nested-sets
There are other models as well, including materialized path and nested sets:
http://communities.bmc.com/communities/docs/DOC-9902
Joe Celko has written a book on this subject, which is a good reference from a general SQL perspective (it is mentioned in the nested set article link above).
Also, Itzik Ben-Gann has a good overview of the most common options in his book "Inside Microsoft SQL Server 2005: T-SQL Querying".
The main things to consider when choosing a model are:
1) Frequency of structure change - how frequently does the actual structure of the tree change. Some models provide better structure update characteristics. It is important to separate structure changes from other data changes however. For example, you may want to model a company's organizational chart. Some people will model this as an adjacency list, using the employee ID to link an employee to their supervisor. This is usually a sub-optimal approach. An approach that often works better is to model the org structure separate from employees themselves, and maintain the employee as an attribute of the structure. This way, when an employee leaves the company, the organizational structure itself does not need to be changes, just the association with the employee that left.
2) Is the tree write-heavy or read-heavy - some structures work very well when reading the structure, but incur additional overhead when writing to the structure.
3) What types of information do you need to obtain from the structure - some structures excel at providing certain kinds of information about the structure. Examples include finding a node and all its children, finding a node and all its parents, finding the count of child nodes meeting certain conditions, etc. You need to know what information will be needed from the structure to determine the structure that will best fit your needs.
make an html svg object also a clickable link
Just don't use <object>
. Here's a solution that worked for me with <a>
and <svg>
tags:
<a href="<your-link>" class="mr-5 p-1 border-2 border-transparent text-gray-400 rounded-full hover:text-white focus:outline-none focus:text-white focus:bg-red-700 transition duration-150 ease-in-out" aria-label="Notifications">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="30"
height="30"><path class="heroicon-ui" fill="#fff" d="M17 16a3 3 0 1 1-2.83
2H9.83a3 3 0 1 1-5.62-.1A3 3 0 0 1 5 12V4H3a1 1 0 1 1 0-2h3a1 1 0 0 1 1
1v1h14a1 1 0 0 1 .9 1.45l-4 8a1 1 0 0 1-.9.55H5a1 1 0 0 0 0 2h12zM7 12h9.38l3-
6H7v6zm0 8a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm10 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>
</svg>
</a>
How do I use Docker environment variable in ENTRYPOINT array?
I tried to resolve with the suggested answer and still ran into some issues...
This was a solution to my problem:
ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}
# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]
Specifically targeting your problem:
RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]
What are all codecs and formats supported by FFmpeg?
The formats and codecs supported by your build of ffmpeg
can vary due the version, how it was compiled, and if any external libraries, such as libx264, were supported during compilation.
Formats (muxers and demuxers):
List all formats:
ffmpeg -formats
Display options specific to, and information about, a particular muxer:
ffmpeg -h muxer=matroska
Display options specific to, and information about, a particular demuxer:
ffmpeg -h demuxer=gif
Codecs (encoders and decoders):
List all codecs:
ffmpeg -codecs
List all encoders:
ffmpeg -encoders
List all decoders:
ffmpeg -decoders
Display options specific to, and information about, a particular encoder:
ffmpeg -h encoder=mpeg4
Display options specific to, and information about, a particular decoder:
ffmpeg -h decoder=aac
Reading the results
There is a key near the top of the output that describes each letter that precedes the name of the format, encoder, decoder, or codec:
$ ffmpeg -encoders
[…]
Encoders:
V..... = Video
A..... = Audio
S..... = Subtitle
.F.... = Frame-level multithreading
..S... = Slice-level multithreading
...X.. = Codec is experimental
....B. = Supports draw_horiz_band
.....D = Supports direct rendering method 1
------
[…]
V.S... mpeg4 MPEG-4 part 2
In this example V.S...
indicates that the encoder mpeg4
is a V
ideo encoder and supports S
lice-level multithreading.
Also see
What is a codec and how does it differ from a format?
Display MessageBox in ASP
If you want to do it from code behind, try this:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);
How to determine if a decimal/double is an integer?
Using int.TryParse will yield these results:
var shouldBeInt = 3;
var shouldntBeInt = 3.1415;
var iDontWantThisToBeInt = 3.000f;
Console.WriteLine(int.TryParse(shouldBeInt.ToString(), out int parser)); // true
Console.WriteLine(int.TryParse(shouldntBeInt.ToString(), out parser)); // false
Console.WriteLine(int.TryParse(iDontWantThisToBeInt.ToString(), out parser)); // true, even if I don't want this to be int
Console.WriteLine(int.TryParse("3.1415", out parser)); // false
Console.WriteLine(int.TryParse("3.0000", out parser)); // false
Console.WriteLine(int.TryParse("3", out parser)); // true
Console.ReadKey();
Convert python long/int to fixed size byte array
long/int to the byte array looks like exact purpose of struct.pack
. For long integers that exceed 4(8) bytes, you can come up with something like the next:
>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
parts.append(i & limit)
i >>= 32
>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'
>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L
PHP: How to get current time in hour:minute:second?
Anytime you have a question about a particular function in PHP, the easiest way to get quick answers is by visiting php.net, which has great documentation on all of the language's capabilities.
Looking up a function is easy, just visit http://php.net/<function name>
and it will forward you to the appropriate place. For the date function, we'll visit http://php.net/date.
We immediately learn a couple things about this function by examining its signature:
string date ( string $format [, int $timestamp = time() ] )
First, it returns a string. That's what the first string
in the above code means. Secondly, the first parameter is expected to be a string containing the format. There is an optional second parameter for passing in your own timestamp (to construct strings from some time other than now).
date("d-m-Y") // produces something like 03-12-2012
In this code, d
represents the day of the month (with a leading 0 is necessary). m
represents the month, again with a leading zero if necessary. And Y
represents the full 4-digit year. All of these are documented in the aforementioned link.
To satisfy your request of getting the hours, minutes, and seconds, we need to give a quick look at the documentation to see which characters represents those particular units of time. When we do that, we find the following:
h 12-hour format of an hour with leading zeros 01 through 12
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
With this in mind, we can no create a new format string:
date("d-m-Y h:i:s"); // produces something like 03-12-2012 03:29:13
Hope this is helpful, and I hope you find the documentation has benefiting to your development as I have to mine.
Import PEM into Java Key Store
There is also a GUI tool that allows visual JKS creation and certificates importing.
http://portecle.sourceforge.net/
Portecle is a user friendly GUI application for creating, managing and examining keystores, keys, certificates, certificate requests, certificate revocation lists and more.
Interfaces with static fields in java for sharing 'constants'
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.
But don't just take my word for it, Josh Bloch also says it's bad:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
C# Java HashMap equivalent
Dictionary
is probably the closest. System.Collections.Generic.Dictionary
implements the System.Collections.Generic.IDictionary
interface (which is similar to Java's Map
interface).
Some notable differences that you should be aware of:
- Adding/Getting items
- Java's HashMap has the
put
and get
methods for setting/getting items
myMap.put(key, value)
MyObject value = myMap.get(key)
- C#'s Dictionary uses
[]
indexing for setting/getting items
myDictionary[key] = value
MyObject value = myDictionary[key]
null
keys
- Java's
HashMap
allows null keys
- .NET's
Dictionary
throws an ArgumentNullException
if you try to add a null key
- Adding a duplicate key
- Java's
HashMap
will replace the existing value with the new one.
- .NET's
Dictionary
will replace the existing value with the new one if you use []
indexing. If you use the Add
method, it will instead throw an ArgumentException
.
- Attempting to get a non-existent key
- Java's
HashMap
will return null.
- .NET's
Dictionary
will throw a KeyNotFoundException
. You can use the TryGetValue
method instead of the []
indexing to avoid this:
MyObject value = null;
if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }
Dictionary
's has a ContainsKey
method that can help deal with the previous two problems.
String formatting: % vs. .format vs. string literal
Yet another advantage of .format
(which I don't see in the answers): it can take object properties.
In [12]: class A(object):
....: def __init__(self, x, y):
....: self.x = x
....: self.y = y
....:
In [13]: a = A(2,3)
In [14]: 'x is {0.x}, y is {0.y}'.format(a)
Out[14]: 'x is 2, y is 3'
Or, as a keyword argument:
In [15]: 'x is {a.x}, y is {a.y}'.format(a=a)
Out[15]: 'x is 2, y is 3'
This is not possible with %
as far as I can tell.
Android Drawing Separator/Divider Line in Layout?
if you use actionBarSherlock, you can use the com.actionbarsherlock.internal.widget.IcsLinearLayout class in order to support dividers and show them between the views .
example of usage:
<com.actionbarsherlock.internal.widget.IcsLinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:divider="@drawable/divider"
android:dividerPadding="10dp"
android:orientation="vertical"
android:showDividers="beginning|middle|end" >
... children...
res/drawable/divider.xml :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<size android:height="2dip" />
<solid android:color="#FFff0000" />
</shape>
do note that for some reason, the preview in the graphical designer says "android.graphics.bitmap_delegate.nativeRecycle(I)Z" . not sure what it means, but it can be ignored as it works fine on both new versions of android and old ones (tested on android 4.2 and 2.3) .
seems the error is only shown when using API17 for the graphical designer.
Set a DateTime database field to "Now"
Use GETDATE()
Returns the current database system
timestamp as a datetime value without
the database time zone offset. This
value is derived from the operating
system of the computer on which the
instance of SQL Server is running.
UPDATE table SET date = GETDATE()
Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)
For Swift 3 and Xcode 8:
var dataTask: URLSessionDataTask?
if let url = URL(string: urlString) {
self.dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let error = error {
print(error.localizedDescription)
} else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
// You can use data received.
self.process(data: data as Data?)
}
})
}
}
//Note: You can always use debugger to check error
How to undo the last commit in git
I think you haven't messed up yet. Try:
git reset HEAD^
This will bring the dir to state before you've made the commit, HEAD^
means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).
How to write subquery inside the OUTER JOIN Statement
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
Get current time in milliseconds using C++ and Boost
If you mean milliseconds since epoch you could do
ptime time_t_epoch(date(1970,1,1));
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();
However, it's not particularly clear what you're after.
Have a look at the example in the documentation for DateTime at Boost Date Time
How to deal with http status codes other than 200 in Angular 2
Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs
for the same like this way
import {Observable} from 'rxjs/Rx';
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 400) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 409) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 406) {
return Observable.throw(new Error(error.status));
}
});
}
also you can handel error (with err block) that is throw by catch block while .map
function,
like this -
...
.subscribe(res=>{....}
err => {//handel here});
Update
as required for any status without checking particluar one you can try this: -
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status < 400 || error.status ===500) {
return Observable.throw(new Error(error.status));
}
})
.subscribe(res => {...},
err => {console.log(err)} );
How do I get a Date without time in Java?
Do you absolutely have to use java.util.Date
? I would thoroughly recommend that you use Joda Time or the java.time
package from Java 8 instead. In particular, while Date and Calendar always represent a particular instant in time, with no such concept as "just a date", Joda Time does have a type representing this (LocalDate
). Your code will be much clearer if you're able to use types which represent what you're actually trying to do.
There are many, many other reasons to use Joda Time or java.time
instead of the built-in java.util
types - they're generally far better APIs. You can always convert to/from a java.util.Date
at the boundaries of your own code if you need to, e.g. for database interaction.
Convert Uri to String and String to Uri
Try this to convert string to uri
String mystring="Hello"
Uri myUri = Uri.parse(mystring);
Uri to String
Uri uri;
String uri_to_string;
uri_to_string= uri.toString();
Variable name as a string in Javascript
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
What is the difference between & and && in Java?
Besides && and || being short circuiting, also consider operator precedence when mixing the two forms.
I think it will not be immediately apparent to everybody that result1 and result2 contain different values.
boolean a = true;
boolean b = false;
boolean c = false;
boolean result1 = a || b && c; //is true; evaluated as a || (b && c)
boolean result2 = a | b && c; //is false; evaluated as (a | b) && c