Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?
On a rather unrelated note: more performance hacks!
[the first «conjecture» has been finally debunked by @ShreevatsaR; removed]
When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N
(shown first):
- [even] [odd]
- [odd] [even]
- [even] [even]
To leap past these 2 elements means to compute (N >> 1) + N + 1
, ((N << 1) + N + 1) >> 1
and N >> 2
, respectively.
Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1
.
Case (1) is obvious. Case (2) implies (N & 1) == 1
, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba
from most- to least-significant, then a = 1
, and the following holds:
(N << 1) + N + 1: (N >> 1) + N + 1:
b10 b1
b1 b
+ 1 + 1
---- ---
bBb0 bBb
where B = !b
. Right-shifting the first result gives us exactly what we want.
Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1
.
As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.
The resulting algorithm looks like this:
uint64_t sequence(uint64_t size, uint64_t *path) {
uint64_t n, i, c, maxi = 0, maxc = 0;
for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
c = 2;
while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
c += 2;
if (n == 2)
c++;
if (c > maxc) {
maxi = i;
maxc = c;
}
}
*path = maxc;
return maxi;
}
int main() {
uint64_t maxi, maxc;
maxi = sequence(1000000, &maxc);
printf("%llu, %llu\n", maxi, maxc);
return 0;
}
Here we compare n > 2
because the process may stop at 2 instead of 1 if the total length of the sequence is odd.
[EDIT:]
Let`s translate this into assembly!
MOV RCX, 1000000;
DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;
@main:
XOR RSI, RSI;
LEA RDI, [RCX + 1];
@loop:
ADD RSI, 2;
LEA RDX, [RDI + RDI*2 + 2];
SHR RDX, 1;
SHRD RDI, RDI, 2; ror rdi,2 would do the same thing
CMOVL RDI, RDX; Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
CMOVS RDI, RDX;
CMP RDI, 2;
JA @loop;
LEA RDX, [RSI + 1];
CMOVE RSI, RDX;
CMP RAX, RSI;
CMOVB RAX, RSI;
CMOVB RBX, RCX;
SUB RCX, 2;
JA @main;
MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;
@itoa:
XOR RDX, RDX;
DIV RCX;
ADD RDX, '0';
PUSH RDX;
TEST RAX, RAX;
JNE @itoa;
PUSH RCX;
LEA RAX, [RBX + 1];
TEST RBX, RBX;
MOV RBX, RDI;
JNE @itoa;
POP RCX;
INC RDI;
MOV RDX, RDI;
@outp:
MOV RSI, RSP;
MOV RAX, RDI;
SYSCALL;
POP RAX;
TEST RAX, RAX;
JNE @outp;
LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;
Use these commands to compile:
nasm -f elf64 file.asm
ld -o file file.o
See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)
what does this mean ? image/png;base64?
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
There is already an open DataReader associated with this Command which must be closed first
Most likely this issue happens because of "lazy loading" feature of Entity Framework. Usually, unless explicitly required during initial fetch, all joined data (anything that stored in other database tables) is fetched only when required. In many cases that is a good thing, since it prevents from fetching unnecessary data and thus improve query performance (no joins) and saves bandwidth.
In the situation described in the question, initial fetch is performed, and during "select" phase missing lazy loading data is requested, additional queries are issued and then EF is complaining about "open DataReader".
Workaround proposed in the accepted answer will allow execution of these queries, and indeed the whole request will succeed.
However, if you will examine requests sent to the database, you will notice multiple requests - additional request for each missing (lazy loaded) data. This might be a performance killer.
A better approach is to tell to EF to preload all needed lazy loaded data during the initial query. This can be done using "Include" statement:
using System.Data.Entity;
query = query.Include(a => a.LazyLoadedProperty);
This way, all needed joins will be performed and all needed data will be returned as a single query. The issue described in the question will be solved.
System.Net.WebException: The remote name could not be resolved:
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
Apache POI Excel - how to configure columns to be expanded?
I use below simple solution:
This is your workbook and sheet:
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("YOUR Workshhet");
then add data to your sheet with columns and rows. Once done with adding data to sheet write following code to autoSizeColumn
width.
for (int columnIndex = 0; columnIndex < 15; columnIndex++) {
sheet.autoSizeColumn(columnIndex);
}
Here, instead 15, you add the number of columns in your sheet.
Hope someone helps this.
Resetting a form in Angular 2 after submit
Use NgForm
's .resetForm()
rather than .reset()
because it is the method that is officially documented in NgForm
's public api. (Ref [1])
<form (ngSubmit)="mySubmitHandler(); myNgForm.resetForm()" #myNgForm="ngForm">
The .resetForm()
method will reset the NgForm
's FormGroup
and set it's submit
flag to false
(See [2]).
Tested in @angular versions 2.4.8 and 4.0.0-rc3
How to show Snackbar when Activity starts?
You can also define a super class for all your activities and find the view once in the parent activity.
for example
AppActivity.java :
public class AppActivity extends AppCompatActivity {
protected View content;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
changeLanguage("fa");
content = findViewById(android.R.id.content);
}
}
and your snacks would look like this in every activity in your app:
Snackbar.make(content, "hello every body", Snackbar.LENGTH_SHORT).show();
It is better for performance you have to find the view once for every activity.
Multiprocessing vs Threading Python
Here are some pros/cons I came up with.
Multiprocessing
Pros
- Separate memory space
- Code is usually straightforward
- Takes advantage of multiple CPUs & cores
- Avoids GIL limitations for cPython
- Eliminates most needs for synchronization primitives unless if you use shared memory (instead, it's more of a communication model for IPC)
- Child processes are interruptible/killable
- Python
multiprocessing
module includes useful abstractions with an interface much like threading.Thread
- A must with cPython for CPU-bound processing
Cons
- IPC a little more complicated with more overhead (communication model vs. shared memory/objects)
- Larger memory footprint
Threading
Pros
- Lightweight - low memory footprint
- Shared memory - makes access to state from another context easier
- Allows you to easily make responsive UIs
- cPython C extension modules that properly release the GIL will run in parallel
- Great option for I/O-bound applications
Cons
- cPython - subject to the GIL
- Not interruptible/killable
- If not following a command queue/message pump model (using the
Queue
module), then manual use of synchronization primitives become a necessity (decisions are needed for the granularity of locking)
- Code is usually harder to understand and to get right - the potential for race conditions increases dramatically
Facebook Graph API : get larger pictures in one request
You can set the size of the picture in pixels, like this:
https://graph.facebook.com/v2.8/me?fields=id,name,picture.width(500).height(500)
In the similar manner, type
parameter can be used
{user-id}/?fields=name,picture.type(large)
From the documentation
type
enum{small, normal, album, large, square}
YouTube embedded video: set different thumbnail
Your best bet would be to use the tutorial on http://orangecountycustomwebsitedesign.com/change-the-youtube-embed-image-to-custom-image/#comment-7289.
This will ensure there is no double clicking and that YouTube's video doesn't autoplay behind your image prior to clicking it.
Do not plug in the YouTube embed code as YT(YouTube) gives it (you can try, but it will be ganky)...instead just replace the source from the embed code of your vid UP TO "&autoplay=1" (leave this on the end as it is).
eg.)
Original code YT gives:
`<object width="420" height="315"><param name="movie" value="//www.youtube.com/v/5mEymdGuEJk?hl=en_US&version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="//www.youtube.com/v/5mEymdGuEJkhl=en_US&version=3" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>`
Code used in tutorial with same YT src:
`<object width="420" height="315" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess"value="always" /><param name="src" value="http://www.youtube.com/v/5mEymdGuEJk?version=3&hl=en_US&autoplay=1" /><param name="allowfullscreen" value="true" /><embed width="420" height="315" type="application/x-shockwave-flash" src="http://www.youtube.com/v/5mEymdGuEJk?version=3&hl=en_US&autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" /></object>`
Other than that, just replace the img source and path with your own, and voilà!
How to convert answer into two decimal point
If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this
dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))
How can I provide multiple conditions for data trigger in WPF?
Use MultiDataTrigger type
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=State}" Value="WA">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Name}" Value="Portland" />
<Condition Binding="{Binding Path=State}" Value="OR" />
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Cyan" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
Change Default branch in gitlab
For GitLab 11.5.0-ee, go to
https://gitlab.com/<username>/<project name>/settings/repository
.
You should see:
Default Branch
Select the branch you want to set as the default for this project. All merge requests and commits will automatically be made against this branch unless you specify a different one.
Click Expand, select a branch, and click Save Changes.
Merging a lot of data.frames
Put them into a list
and use merge
with Reduce
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# id v1 v2 v3
# 1 1 1 NA NA
# 2 10 4 NA NA
# 3 2 3 4 NA
# 4 43 5 NA NA
# 5 73 2 NA NA
# 6 23 NA 2 1
# 7 57 NA 3 NA
# 8 62 NA 5 2
# 9 7 NA 1 NA
# 10 96 NA 6 NA
You can also use this more concise version:
Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
Convert String to Carbon
You were almost there.
Remove protected $dates = ['license_expire']
and then change your LicenseExpire
accessor to:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
This way it will return a Carbon
instance no matter what.
So for your form you would just have $employee->license_expire->format('Y-m-d')
(or whatever format is required) and diffForHumans()
should work on your home page as well.
Hope this helps!
How to copy a char array in C?
None of the above was working for me..
this works perfectly
name
here is char *name
which is passed via the function
- get length of
char *name
using strlen(name)
- storing it in a const variable is important
- create same length size
char
array
- copy
name
's content to temp
using strcpy(temp, name);
use however you want, if you want original content back. strcpy(name, temp);
copy temp back to name
and voila works perfectly
const int size = strlen(name);
char temp[size];
cout << size << endl;
strcpy(temp, name);
Formula px to dp, dp to px android
You can use [DisplayMatrics][1]
and determine the screen density. Something like this:
int pixelsValue = 5; // margin in pixels
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(pixelsValue * d);
As I remember it's better to use flooring for offsets and rounding for widths.
What is a clearfix?
A technique commonly used in CSS float-based layouts is assigning a handful of CSS properties to an element which you know will contain floating elements. The technique, which is commonly implemented using a class definition called clearfix
, (usually) implements the following CSS behaviors:
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
zoom: 1
}
The purpose of these combined behaviors is to create a container :after
the active element containing a single '.' marked as hidden which will clear all preexisting floats and effectively reset the the page for the next piece of content.
Control flow in T-SQL SP using IF..ELSE IF - are there other ways?
IF...ELSE... is pretty much what we've got in T-SQL. There is nothing like structured programming's CASE statement. If you have an extended set of ...ELSE IF...s to deal with, be sure to include BEGIN...END for each block to keep things clear, and always remember, consistent indentation is your friend!
How to use XPath contains() here?
This is a new answer to an old question about a common misconception about contains()
in XPath...
Summary: contains()
means contains a substring, not contains a node.
Detailed Explanation
This XPath is often misinterpreted:
//ul[contains(li, 'Model')]
Wrong interpretation:
Select those ul
elements that contain an li
element with Model
in it.
This is wrong because
contains(x,y)
expects x
to be a string, and
the XPath rule for converting multiple elements to a string is this:
A node-set is converted to a string by returning the string-value of
the node in the node-set that is first in document order. If the
node-set is empty, an empty string is returned.
Right interpretation: Select those ul
elements whose first li
child has a string-value that contains a Model
substring.
Examples
XML
<r>
<ul id="one">
<li>Model A</li>
<li>Foo</li>
</ul>
<ul id="two">
<li>Foo</li>
<li>Model A</li>
</ul>
</r>
XPaths
//ul[contains(li, 'Model')]
selects the one
ul
element.
Note: The two
ul
element is not selected because the string-value of the first li
child
of the two
ul
is Foo
, which does not contain the Model
substring.
//ul[li[contains(.,'Model')]]
selects the one
and two
ul
elements.
Note: Both ul
elements are selected because contains()
is applied to each li
individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul
elements do have an li
child whose string value contains the Model
substring -- position of the li
element no longer matters.
See also
Error: The 'brew link' step did not complete successfully
I had the same problem after transferring all my applications from my old Mac to my new one.
I found the solution by running brew doctor
:
Warning: Broken symlinks were found. Remove them with brew prune
After running brew prune
, Homebrew is finally back on track :)
regular expression to match exactly 5 digits
My test string for the following:
testing='12345,abc,123,54321,ab15234,123456,52341';
If I understand your question, you'd want ["12345", "54321", "15234", "52341"]
.
If JS engines supported regexp lookbehinds, you could do:
testing.match(/(?<!\d)\d{5}(?!\d)/g)
Since it doesn't currently, you could:
testing.match(/(?:^|\D)(\d{5})(?!\d)/g)
and remove the leading non-digit from appropriate results, or:
pentadigit=/(?:^|\D)(\d{5})(?!\d)/g;
result = [];
while (( match = pentadigit.exec(testing) )) {
result.push(match[1]);
}
Note that for IE, it seems you need to use a RegExp stored in a variable rather than a literal regexp in the while
loop, otherwise you'll get an infinite loop.
How do you create nested dict in Python?
A nested dict is a dictionary within a dictionary. A very simple thing.
>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d
{'dict1': {'innerkey': 'value'}}
You can also use a defaultdict
from the collections
package to facilitate creating nested dictionaries.
>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d) # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}
You can populate that however you want.
I would recommend in your code something like the following:
d = {} # can use defaultdict(dict) instead
for row in file_map:
# derive row key from something
# when using defaultdict, we can skip the next step creating a dictionary on row_key
d[row_key] = {}
for idx, col in enumerate(row):
d[row_key][idx] = col
According to your comment:
may be above code is confusing the question. My problem in nutshell: I
have 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also has
these columns. i is kind of key columns for these csvs'. j k l column
is empty in a.csv but populated in b.csv. I want to map values of j k
l columns using 'i` as key column from b.csv to a.csv file
My suggestion would be something like this (without using defaultdict):
a_file = "path/to/a.csv"
b_file = "path/to/b.csv"
# read from file a.csv
with open(a_file) as f:
# skip headers
f.next()
# get first colum as keys
keys = (line.split(',')[0] for line in f)
# create empty dictionary:
d = {}
# read from file b.csv
with open(b_file) as f:
# gather headers except first key header
headers = f.next().split(',')[1:]
# iterate lines
for line in f:
# gather the colums
cols = line.strip().split(',')
# check to make sure this key should be mapped.
if cols[0] not in keys:
continue
# add key to dict
d[cols[0]] = dict(
# inner keys are the header names, values are columns
(headers[idx], v) for idx, v in enumerate(cols[1:]))
Please note though, that for parsing csv files there is a csv module.
How do I import global modules in Node? I get "Error: Cannot find module <module>"?
Node.js uses the environmental variable NODE_PATH
to allow for specifying additional directories to include in the module search path. You can use npm
itself to tell you where global modules are stored with the npm root -g
command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)
export NODE_PATH=$(npm root --quiet -g)
How to combine two or more querysets in a Django view?
This can be achieved by two ways either.
1st way to do this
Use union operator for queryset |
to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator.
For an instance
pagelist1 = Page.objects.filter(
Q(title__icontains=cleaned_search_term) |
Q(body__icontains=cleaned_search_term))
pagelist2 = Page.objects.filter(
Q(title__icontains=cleaned_search_term) |
Q(body__icontains=cleaned_search_term))
combined_list = pagelist1 | pagelist2 # this would take union of two querysets
2nd way to do this
One other way to achieve combine operation between two queryset is to use itertools chain function.
from itertools import chain
combined_results = list(chain(pagelist1, pagelist2))
Laravel 4: how to run a raw SQL?
This is my simplified example of how to run RAW SELECT, get result and access the values.
$res = DB::select('
select count(id) as c
from prices p
where p.type in (2,3)
');
if ($res[0]->c > 10)
{
throw new Exception('WOW');
}
If you want only run sql script with no return resutl use this
DB::statement('ALTER TABLE products MODIFY COLUMN physical tinyint(1) AFTER points;');
Tested in laravel 5.1
Deserialize from string instead TextReader
static T DeserializeXml<T>(string sourceXML) where T : class
{
var serializer = new XmlSerializer(typeof(T));
T result = null;
using (TextReader reader = new StringReader(sourceXML))
{
result = (T) serializer.Deserialize(reader);
}
return result;
}
how to call url of any other website in php
use curl php library: http://php.net/manual/en/book.curl.php
direct example: CURL_EXEC:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
JPG vs. JPEG image formats
JPG and JPEG stand both for an image format proposed and supported by the Joint Photographic Experts Group. The two terms have the same meaning and are interchangeable.
To read on, check out Difference between JPG and JPEG.
The reason for the different file extensions dates back to the early versions of Windows. The original file extension for the Joint Photographic Expert Group File Format was ‘.jpeg’; however in Windows all files required a three letter file extension. So, the file extension was shortened to ‘.jpg’. However, Macintosh was not limited to three letter file extensions, so Mac users used ‘.jpeg’. Eventually, with upgrades Windows also began to accept ‘.jpeg’. However, many users were already used to ‘.jpg’, so both the three letter file extension and the four letter extension began to be commonly used, and still is.
Today, the most commonly accepted and used form is the ‘.jpg’, as many users were Windows users. Imaging applications, such as Adobe Photoshop, save all JPEG files with a ".jpg" extension on both Mac and Windows, in an attempt to avoid confusion. The Joint Photographic Expert Group File Format can also be saved with the upper-case ‘.JPEG’ and ‘.JPG’ file extensions, which are less common, but also accepted.
How to apply a CSS filter to a background image
All you actually need is "filter":
blur(«WhatEverYouWantInPixels»);"
_x000D_
_x000D_
body {_x000D_
color: #fff;_x000D_
font-family: Helvetica, Arial, sans-serif;_x000D_
}_x000D_
_x000D_
#background {_x000D_
background-image: url('https://cdn2.geckoandfly.com/wp-content/uploads/2018/03/ios-11-3840x2160-4k-5k-beach-ocean-13655.jpg');_x000D_
background-repeat: no-repeat;_x000D_
background-size: cover;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
overflow: hidden;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: -1;_x000D_
_x000D_
/* START */_x000D_
/* START */_x000D_
/* START */_x000D_
/* START */_x000D_
_x000D_
/* You can adjust the blur-radius as you'd like */_x000D_
filter: blur(3px);_x000D_
}
_x000D_
<div id="background"></div>_x000D_
_x000D_
<p id="randomContent">Lorem Ipsum</p>
_x000D_
_x000D_
_x000D_
Is CSS Turing complete?
The fundamental issue here is that any machine written in HTML+CSS cannot evaluate infinitely many steps (i.e there can be no "real" recursion) unless the code is infinitely long. And the question will this machine reach configuration H
in n
steps or less is always answerable if n
is finite.
Why does Maven have such a bad rep?
- It imposes rigid structure on you from the start.
- It's XML-based so it's as hard to read as ANT was.
- Its error reporting is obscure and leaves you stranded when things go wrong.
- The documentation is poor.
- It makes hard things easy, and simple things hard.
- It takes too much time to maintain a Maven build environment, which defeats the point of having an all-singing build system.
- It takes a long time to figure out that you've found a bug in maven and not configured something wrong. And the bugs do exist, and in surprising places.
- It promises much but betrays you like a beautiful and seductive but emotionally cold and manipulative lover.
position: fixed doesn't work on iPad and iPhone
Even though the CSS attribute {position:fixed;}
seems (mostly) working on newer iOS devices, it is possible to have the device quirk and fallback to {position:relative;}
on occasion and without cause or reason. Usually clearing the cache will help, until something happens and the quirk happens again.
Specifically, from Apple itself Preparing Your Web Content for iPad:
Safari on iPad and Safari on iPhone do not have resizable windows. In
Safari on iPhone and iPad, the window size is set to the size of the
screen (minus Safari user interface controls), and cannot be changed
by the user. To move around a webpage, the user changes the zoom level
and position of the viewport as they double tap or pinch to zoom in or
out, or by touching and dragging to pan the page. As a user changes
the zoom level and position of the viewport they are doing so within a
viewable content area of fixed size (that is, the window). This means
that webpage elements that have their position "fixed" to the viewport
can end up outside the viewable content area, offscreen.
What is ironic, Android devices do not seem to have this issue. Also it is entirely possible to use {position:absolute;}
when in reference to the body tag and not have any issues.
I found the root cause of this quirk; that it is the scroll event not playing nice when used in conjunction with the HTML or BODY tag. Sometimes it does not like to fire the event, or you will have to wait until the scroll swing event is finished to receive the event. Specifically, the viewport is re-drawn at the end of this event and fixed elements can be re-positioned somewhere else in the viewport.
So this is what I do: (avoid using the viewport, and stick with the DOM!)
<html>
<style>
.fixed{
position:fixed;
/*you can set your other static attributes here too*/
/*like height and width, margin, etc.*/
}
.scrollableDiv{
position:relative;
overflow-y:scroll;
/*all children will scroll within this like the body normally would.*/
}
.viewportSizedBody{
position:relative;
overflow:hidden;
/*this will prevent the body page itself from scrolling.*/
}
</style>
<body class="viewportSizedBody">
<div id="myFixedContainer" class="fixed">
This part is fixed.
</div>
<div id="myScrollableBody" class="scrollableDiv">
This part is scrollable.
</div>
</body>
<script type="text/javascript" src="{your path to jquery}/jquery-1.7.2.min.js"></script>
<script>
var theViewportHeight=$(window).height();
$('.viewportSizedBody').css('height',theViewportHeight);
$('#myScrollableBody').css('height',theViewportHeight);
</script>
</html>
In essence this will cause the BODY to be the size of the viewport and non-scrollable. The scrollable DIV nested inside will scroll as the BODY normally would (minus the swing effect, so the scrolling does stop on touchend.) The fixed DIV stays fixed without interference.
As a side note, a high z-index
value on the fixed DIV is important to keep the scrollable DIV appear to be behind it. I normally add in window resize and scroll events also for cross-browser and alternate screen resolution compatibility.
If all else fails, the above code will also work with both the fixed and scrollable DIVs set to {position:absolute;}
.
Submit button doesn't work
I faced this problem today, and the issue was I was preventing event default action in document onclick:
document.onclick = function(e) {
e.preventDefault();
}
Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:
document.onclick = function(e) {
if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}
Priority queue in .Net
class PriorityQueue<T>
{
IComparer<T> comparer;
T[] heap;
public int Count { get; private set; }
public PriorityQueue() : this(null) { }
public PriorityQueue(int capacity) : this(capacity, null) { }
public PriorityQueue(IComparer<T> comparer) : this(16, comparer) { }
public PriorityQueue(int capacity, IComparer<T> comparer)
{
this.comparer = (comparer == null) ? Comparer<T>.Default : comparer;
this.heap = new T[capacity];
}
public void push(T v)
{
if (Count >= heap.Length) Array.Resize(ref heap, Count * 2);
heap[Count] = v;
SiftUp(Count++);
}
public T pop()
{
var v = top();
heap[0] = heap[--Count];
if (Count > 0) SiftDown(0);
return v;
}
public T top()
{
if (Count > 0) return heap[0];
throw new InvalidOperationException("??????");
}
void SiftUp(int n)
{
var v = heap[n];
for (var n2 = n / 2; n > 0 && comparer.Compare(v, heap[n2]) > 0; n = n2, n2 /= 2) heap[n] = heap[n2];
heap[n] = v;
}
void SiftDown(int n)
{
var v = heap[n];
for (var n2 = n * 2; n2 < Count; n = n2, n2 *= 2)
{
if (n2 + 1 < Count && comparer.Compare(heap[n2 + 1], heap[n2]) > 0) n2++;
if (comparer.Compare(v, heap[n2]) >= 0) break;
heap[n] = heap[n2];
}
heap[n] = v;
}
}
easy.
Difference between `Optional.orElse()` and `Optional.orElseGet()`
I reached here for the problem Kudo mentioned.
I'm sharing my experience for others.
orElse
, or orElseGet
, that is the question:
static String B() {
System.out.println("B()...");
return "B";
}
public static void main(final String... args) {
System.out.println(Optional.of("A").orElse(B()));
System.out.println(Optional.of("A").orElseGet(() -> B()));
}
prints
B()...
A
A
orElse
evaluates the value of B() interdependently of the value of the optional. Thus, orElseGet
is lazy.
Java: Converting String to and from ByteBuffer and associated problems
Unless things have changed, you're better off with
public static ByteBuffer str_to_bb(String msg, Charset charset){
return ByteBuffer.wrap(msg.getBytes(charset));
}
public static String bb_to_str(ByteBuffer buffer, Charset charset){
byte[] bytes;
if(buffer.hasArray()) {
bytes = buffer.array();
} else {
bytes = new byte[buffer.remaining()];
buffer.get(bytes);
}
return new String(bytes, charset);
}
Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.
Laravel - Eloquent or Fluent random row
Laravel >= 5.2:
User::inRandomOrder()->get();
or to get the specific number of records
// 5 indicates the number of records
User::inRandomOrder()->limit(5)->get();
// get one random record
User::inRandomOrder()->first();
or using the random method for collections:
User::all()->random();
User::all()->random(10); // The amount of items you wish to receive
Laravel 4.2.7 - 5.1:
User::orderByRaw("RAND()")->get();
Laravel 4.0 - 4.2.6:
User::orderBy(DB::raw('RAND()'))->get();
Laravel 3:
User::order_by(DB::raw('RAND()'))->get();
Check this article on MySQL random rows. Laravel 5.2 supports this, for older version, there is no better solution then using RAW Queries.
edit 1: As mentioned by Double Gras, orderBy() doesn't allow anything else then ASC or DESC since this change. I updated my answer accordingly.
edit 2: Laravel 5.2 finally implements a wrapper function for this. It's called inRandomOrder().
how to make window.open pop up Modal?
I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.
In parent window use:
<head>
<style>
.disableWin{
pointer-events: none;
}
</style>
<script type="text/javascript">
function openPopUp(url) {
disableParentWin();
var win = window.open(url);
win.focus();
checkPopUpClosed(win);
}
/*Function to detect pop up is closed and take action to enable parent window*/
function checkPopUpClosed(win) {
var timer = setInterval(function() {
if(win.closed) {
clearInterval(timer);
enableParentWin();
}
}, 1000);
}
/*Function to enable parent window*/
function enableParentWin() {
window.document.getElementById('mainDiv').class="";
}
/*Function to enable parent window*/
function disableParentWin() {
window.document.getElementById('mainDiv').class="disableWin";
}
</script>
</head>
<body>
<div id="mainDiv class="">
</div>
</body>
Breadth First Vs Depth First
Given this binary tree:
Breadth First Traversal:
Traverse across each level from left to right.
"I'm G, my kids are D and I, my grandkids are B, E, H and K, their grandkids are A, C, F"
- Level 1: G
- Level 2: D, I
- Level 3: B, E, H, K
- Level 4: A, C, F
Order Searched: G, D, I, B, E, H, K, A, C, F
Depth First Traversal:
Traversal is not done ACROSS entire levels at a time. Instead, traversal dives into the DEPTH (from root to leaf) of the tree first. However, it's a bit more complex than simply up and down.
There are three methods:
1) PREORDER: ROOT, LEFT, RIGHT.
You need to think of this as a recursive process:
Grab the Root. (G)
Then Check the Left. (It's a tree)
Grab the Root of the Left. (D)
Then Check the Left of D. (It's a tree)
Grab the Root of the Left (B)
Then Check the Left of B. (A)
Check the Right of B. (C, and it's a leaf node. Finish B tree. Continue D tree)
Check the Right of D. (It's a tree)
Grab the Root. (E)
Check the Left of E. (Nothing)
Check the Right of E. (F, Finish D Tree. Move back to G Tree)
Check the Right of G. (It's a tree)
Grab the Root of I Tree. (I)
Check the Left. (H, it's a leaf.)
Check the Right. (K, it's a leaf. Finish G tree)
DONE: G, D, B, A, C, E, F, I, H, K
2) INORDER: LEFT, ROOT, RIGHT
Where the root is "in" or between the left and right child node.
Check the Left of the G Tree. (It's a D Tree)
Check the Left of the D Tree. (It's a B Tree)
Check the Left of the B Tree. (A)
Check the Root of the B Tree (B)
Check the Right of the B Tree (C, finished B Tree!)
Check the Right of the D Tree (It's a E Tree)
Check the Left of the E Tree. (Nothing)
Check the Right of the E Tree. (F, it's a leaf. Finish E Tree. Finish D Tree)...
Onwards until...
DONE: A, B, C, D, E, F, G, H, I, K
3) POSTORDER:
LEFT, RIGHT, ROOT
DONE: A, C, B, F, E, D, H, K, I, G
Usage (aka, why do we care):
I really enjoyed this simple Quora explanation of the Depth First Traversal methods and how they are commonly used:
"In-Order Traversal will print values [in order for the BST (binary search tree)]"
"Pre-order traversal is used to create a copy of the [binary search tree]."
"Postorder traversal is used to delete the [binary search tree]."
https://www.quora.com/What-is-the-use-of-pre-order-and-post-order-traversal-of-binary-trees-in-computing
Tracking the script execution time in PHP
Small script that print, centered in bottom of the page, the script execution that started at server call with microsecond precision.
So as not to distort the result and to be 100% compatible with content in page, I used, to write the result on the page, a browser-side native javascript snippet.
//Uncomment the line below to test with 2 seconds
//usleep(2000000);
$prec = 5; // numbers after comma
$time = number_format(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], $prec, '.', '');
echo "<script>
if(!tI) {
var tI=document.createElement('div');
tI.style.fontSize='8px';
tI.style.marginBottom='5px';
tI.style.position='absolute';
tI.style.bottom='0px';
tI.style.textAlign='center';
tI.style.width='98%';
document.body.appendChild(tI);
}
tI.innerHTML='$time';
</script>";
Another approach is to make the snippet as small as possible, and style it with a class in your stylesheet.
Replace the echo ...;
part with the following:
echo "<script>if(!tI){var tI=document.createElement('div');tI.className='ldtme';document.body.appendChild(tI);}tI.innerHTML='$time';</script>";
In your CSS create and fill the .ldtme{...}
class.
C++ sorting and keeping track of indexes
Make a std::pair
in function then sort pair :
generic version :
template< class RandomAccessIterator,class Compare >
auto sort2(RandomAccessIterator begin,RandomAccessIterator end,Compare cmp) ->
std::vector<std::pair<std::uint32_t,RandomAccessIterator>>
{
using valueType=typename std::iterator_traits<RandomAccessIterator>::value_type;
using Pair=std::pair<std::uint32_t,RandomAccessIterator>;
std::vector<Pair> index_pair;
index_pair.reserve(std::distance(begin,end));
for(uint32_t idx=0;begin!=end;++begin,++idx){
index_pair.push_back(Pair(idx,begin));
}
std::sort( index_pair.begin(),index_pair.end(),[&](const Pair& lhs,const Pair& rhs){
return cmp(*lhs.second,*rhs.second);
});
return index_pair;
}
ideone
HTML Table width in percentage, table rows separated equally
This is definitely the cleanest answer to the question: https://stackoverflow.com/a/14025331/1008519.
In combination with table-layout: fixed
I often find <colgroup>
a great tool to make columns act as you want (see codepen here):
_x000D_
_x000D_
table {_x000D_
/* When set to 'fixed', all columns that do not have a width applied will get the remaining space divided between them equally */_x000D_
table-layout: fixed;_x000D_
}_x000D_
.fixed-width {_x000D_
width: 100px;_x000D_
}_x000D_
.col-12 {_x000D_
width: 100%;_x000D_
}_x000D_
.col-11 {_x000D_
width: 91.666666667%;_x000D_
}_x000D_
.col-10 {_x000D_
width: 83.333333333%;_x000D_
}_x000D_
.col-9 {_x000D_
width: 75%;_x000D_
}_x000D_
.col-8 {_x000D_
width: 66.666666667%;_x000D_
}_x000D_
.col-7 {_x000D_
width: 58.333333333%;_x000D_
}_x000D_
.col-6 {_x000D_
width: 50%;_x000D_
}_x000D_
.col-5 {_x000D_
width: 41.666666667%;_x000D_
}_x000D_
.col-4 {_x000D_
width: 33.333333333%;_x000D_
}_x000D_
.col-3 {_x000D_
width: 25%;_x000D_
}_x000D_
.col-2 {_x000D_
width: 16.666666667%;_x000D_
}_x000D_
.col-1 {_x000D_
width: 8.3333333333%;_x000D_
}_x000D_
_x000D_
/* Stylistic improvements from here */_x000D_
_x000D_
.align-left {_x000D_
text-align: left;_x000D_
}_x000D_
.align-right {_x000D_
text-align: right;_x000D_
}_x000D_
table {_x000D_
width: 100%;_x000D_
}_x000D_
table > tbody > tr > td,_x000D_
table > thead > tr > th {_x000D_
padding: 8px;_x000D_
border: 1px solid gray;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
<colgroup>_x000D_
<col /> <!-- take up rest of the space -->_x000D_
<col class="fixed-width" /> <!-- fixed width -->_x000D_
<col class="col-3" /> <!-- percentage width -->_x000D_
<col /> <!-- take up rest of the space -->_x000D_
</colgroup>_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="align-left">Title</th>_x000D_
<th class="align-right">Count</th>_x000D_
<th class="align-left">Name</th>_x000D_
<th class="align-left">Single</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
<td class="align-right">19</td>_x000D_
<td class="align-left">Lisa McArthur</td>_x000D_
<td class="align-left">No</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="align-left">This is a shorter title</td>_x000D_
<td class="align-right">2</td>_x000D_
<td class="align-left">John Oliver Nielson McAllister</td>_x000D_
<td class="align-left">Yes</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
<!-- define everything with percentage width -->_x000D_
<colgroup>_x000D_
<col class="col-6" />_x000D_
<col class="col-1" />_x000D_
<col class="col-4" />_x000D_
<col class="col-1" />_x000D_
</colgroup>_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="align-left">Title</th>_x000D_
<th class="align-right">Count</th>_x000D_
<th class="align-left">Name</th>_x000D_
<th class="align-left">Single</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
<td class="align-right">19</td>_x000D_
<td class="align-left">Lisa McArthur</td>_x000D_
<td class="align-left">No</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="align-left">This is a shorter title</td>_x000D_
<td class="align-right">2</td>_x000D_
<td class="align-left">John Oliver Nielson McAllister</td>_x000D_
<td class="align-left">Yes</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_
How do I find the duplicates in a list and create another list with them?
I do not see a solution that is purely using iterators, so here we go
This requires the list to be sorted, which may be the drawback here.
a = [1,2,3,2,1,5,6,5,5,5]
a.sort()
set(map(lambda x: x[0], filter(lambda x: x[0] == x[1], zip(a, a[1:]))))
{1, 2, 5}
You can easily check how fast this is on your machine with a million potential duplicates with this piece of code:
First generate the data
import random
from itertools import chain
a = list(chain(*[[n] * random.randint(1, 2) for n in range(1000000)]))
And run the test:
set(map(lambda x: x[0], filter(lambda x: x[0] == x[1], zip(a, a[1:]))))
Needless to say, this solution is only good if your list is already sorted.
Node.js/Express.js App Only Works on Port 3000
The default way to change the listening port on The Express framework is to modify the file named www in the bin folder.
There, you will find a line such as the following
var port = normalizePort(process.env.PORT || '3000');
Change the value 3000 to any port you wish.
This is valid for Express version 4.13.1
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
How to check if JavaScript object is JSON
You can use Array.isArray to check for arrays. Then typeof obj == 'string', and typeof obj == 'object'.
var s = 'a string', a = [], o = {}, i = 5;
function getType(p) {
if (Array.isArray(p)) return 'array';
else if (typeof p == 'string') return 'string';
else if (p != null && typeof p == 'object') return 'object';
else return 'other';
}
console.log("'s' is " + getType(s));
console.log("'a' is " + getType(a));
console.log("'o' is " + getType(o));
console.log("'i' is " + getType(i));
's' is string
'a' is array
'o' is object
'i' is other
Put Excel-VBA code in module or sheet?
Definitely in Modules.
- Sheets can be deleted, copied and moved with surprising results.
- You can't call code in sheet "code-behind" from other modules without fully qualifying the reference. This will lead to coupling of the sheet and the code in other modules/sheets.
- Modules can be exported and imported into other workbooks, and put under version control
- Code in split logically into modules (data access, utilities, spreadsheet formatting etc.) can be reused as units, and are easier to manage if your macros get large.
Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.
This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.
There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.
How to listen for a WebView finishing loading a URL?
The renderer will not finish rendering when the OnPageFinshed method is called or the progress reaches 100% so both methods don't guarantee you that the view was completely rendered.
But you can figure out from OnLoadResource method what has been already rendered and what is still rendering. And this method gets called several times.
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
// Log and see all the urls and know exactly what is being rendered and visible. If you wanna know when the entire page is completely rendered, find the last url from log and check it with if clause and implement your logic there.
if (url.contains("assets/loginpage/img/ui/forms/")) {
// loginpage is rendered and visible now.
// your logic here.
}
}
Make index.html default, but allow index.php to be visited if typed in
By default, the DirectoryIndex is set to:
DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml
Apache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.
The order should be DirectoryIndex index.html index.php
// default is index.html
Reference: Here.
How to get the number of characters in a string
There are several ways to get a string length:
package main
import (
"bytes"
"fmt"
"strings"
"unicode/utf8"
)
func main() {
b := "?????"
len1 := len([]rune(b))
len2 := bytes.Count([]byte(b), nil) -1
len3 := strings.Count(b, "") - 1
len4 := utf8.RuneCountInString(b)
fmt.Println(len1)
fmt.Println(len2)
fmt.Println(len3)
fmt.Println(len4)
}
jQuery - Add ID instead of Class
Try this:
$('element').attr('id', 'value');
So it becomes;
$(function() {
$('span .breadcrumb').each(function(){
$('#nav').attr('id', $(this).text());
$('#container').attr('id', $(this).text());
$('.stretch_footer').attr('id', $(this).text())
$('#footer').attr('id', $(this).text());
});
});
So you are changing/overwriting the id of three elements and adding an id to one element.
You can modify as per you needs...
Creating a procedure in mySql with parameters
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively.
Note: Instead of s_name, you can also pass @s_name as global variable.
How to call procedure?
Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');
How to supply value to an annotation from a Constant java
Compile constants can only be primitives and Strings:
15.28. Constant Expressions
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
- Literals of primitive type and literals of type
String
- Casts to primitive types and casts to type
String
- [...] operators [...]
- Parenthesized expressions whose contained expression is a constant expression.
- Simple names that refer to constant variables.
- Qualified names of the form TypeName . Identifier that refer to constant variables.
Actually in java there is no way to protect items in an array. At runtime someone can always do FieldValues.FIELD1[0]="value3"
, therefore the array cannot be really constant if we look deeper.
What is a blob URL and why it is used?
I have modified working solution to handle both the case.. when video is uploaded and when image is uploaded .. hope it will help some.
HTML
<input type="file" id="fileInput">
<div> duration: <span id='sp'></span><div>
Javascript
var fileEl = document.querySelector("input");
fileEl.onchange = function(e) {
var file = e.target.files[0]; // selected file
if (!file) {
console.log("nothing here");
return;
}
console.log(file);
console.log('file.size-' + file.size);
console.log('file.type-' + file.type);
console.log('file.acutalName-' + file.name);
let start = performance.now();
var mime = file.type, // store mime for later
rd = new FileReader(); // create a FileReader
if (/video/.test(mime)) {
rd.onload = function(e) { // when file has read:
var blob = new Blob([e.target.result], {
type: mime
}), // create a blob of buffer
url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
video = document.createElement("video"); // create video element
//console.log(blob);
video.preload = "metadata"; // preload setting
video.addEventListener("loadedmetadata", function() { // when enough data loads
console.log('video.duration-' + video.duration);
console.log('video.videoHeight-' + video.videoHeight);
console.log('video.videoWidth-' + video.videoWidth);
//document.querySelector("div")
// .innerHTML = "Duration: " + video.duration + "s" + " <br>Height: " + video.videoHeight; // show duration
(URL || webkitURL).revokeObjectURL(url); // clean up
console.log(start - performance.now());
// ... continue from here ...
});
video.src = url; // start video load
};
} else if (/image/.test(mime)) {
rd.onload = function(e) {
var blob = new Blob([e.target.result], {
type: mime
}),
url = URL.createObjectURL(blob),
img = new Image();
img.onload = function() {
console.log('iamge');
console.dir('this.height-' + this.height);
console.dir('this.width-' + this.width);
URL.revokeObjectURL(this.src); // clean-up memory
console.log(start - performance.now()); // add image to DOM
}
img.src = url;
};
}
var chunk = file.slice(0, 1024 * 1024 * 10); // .5MB
rd.readAsArrayBuffer(chunk); // read file object
};
jsFiddle Url
https://jsfiddle.net/PratapDessai/0sp3b159/
Limit String Length
You can use something similar to the below:
if (strlen($str) > 10)
$str = substr($str, 0, 7) . '...';
How do I edit $PATH (.bash_profile) on OSX?
Set the path JAVA_HOME and ANDROID_HOME > You have to open terminal and enter the below cmd.
touch ~/.bash_profile; open ~/.bash_profile
After that paste below paths in base profile file and save it
export ANDROID_HOME=/Users/<username>/Library/Android/sdk
export PATH="$JAVA_HOME/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH"
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home
Is it possible to install another version of Python to Virtualenv?
Although the question specifically describes installing 2.6, I would like to add some importants points to the excellent answers above in case someone comes across this. For the record, my case was that I was trying to install 2.7 on an ubuntu 10.04 box.
First, my motivation towards the methods described in all the answers here is that installing Python from deadsnake's ppa's has been a total failure. So building a local Python is the way to go.
Having tried so, I thought relying to the default installation of pip (with sudo apt-get install pip
) would be adequate. This unfortunately is wrong. It turned out that I was getting all shorts of nasty issues and eventually not being able to create a virtualenv.
Therefore, I highly recommend to install pip locally with wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py && python get-pip.py --user
. This related question gave me this hint.
Now if this doesn't work, make sure that libssl-dev
for Ubuntu or openssl-dev
for CentOS is installed. Install them with apt-get
or yum
and then re-build Python (no need to remove anything if already installed, do so on top). get-pip
complains about that, you can check so by running import ssl
on a py shell.
Last, don't forget to declare .local/bin
and local python to path, check with which pip
and which python
.
how does Request.QueryString work?
A query string is an array of parameters sent to a web page.
This url: http://page.asp?x=1&y=hello
Request.QueryString[0] is the same as
Request.QueryString["x"] and holds a string value "1"
Request.QueryString[1] is the same as
Request.QueryString["y"] and holds a string value "hello"
Removing empty lines in Notepad++
- notepad++
- Ctrl-H
- Select Regular Expression
- Enter
^[ \t]*$\r?\n
into find what, leave replace empty. This will match all lines starting with white space and ending with carriage return (in this case a windows crlf)
- Click the Find Next button to see for yourself how it matches only empty lines.
How to install and use "make" in Windows?
Another alternative is if you already installed minGW and added the bin folder the to Path environment variable, you can use "mingw32-make" instead of "make".
You can also create a symlink from "make" to "mingw32-make", or copying and changing the name of the file. I would not recommend the options before, they will work until you do changes on the minGW.
Difference between <? super T> and <? extends T> in Java
Based on Bert F's answer I would like to explain my understanding.
Lets say we have 3 classes as
public class Fruit{}
public class Melon extends Fruit{}
public class WaterMelon extends Melon{}
Here We have
List<? extends Fruit> fruitExtendedList = …
//Says that I can be a list of any object as long as this object extends Fruit.
Ok now lets try to get some value from fruitExtendedList
Fruit fruit = fruitExtendedList.get(position)
//This is valid as it can only return Fruit or its subclass.
Again lets try
Melon melon = fruitExtendedList.get(position)
//This is not valid because fruitExtendedList can be a list of Fruit only, it may not be
//list of Melon or WaterMelon and in java we cannot assign sub class object to
//super class object reference without explicitly casting it.
Same is the case for
WaterMelon waterMelon = fruitExtendedList.get(position)
Now lets try to set some object in fruitExtendedList
Adding fruit object
fruitExtendedList.add(new Fruit())
//This in not valid because as we know fruitExtendedList can be a list of any
//object as long as this object extends Fruit. So what if it was the list of
//WaterMelon or Melon you cannot add Fruit to the list of WaterMelon or Melon.
Adding Melon object
fruitExtendedList.add(new Melon())
//This would be valid if fruitExtendedList was the list of Fruit but it may
//not be, as it can also be the list of WaterMelon object. So, we see an invalid
//condition already.
Finally let try to add WaterMelon object
fruitExtendedList.add(new WaterMelon())
//Ok, we got it now we can finally write to fruitExtendedList as WaterMelon
//can be added to the list of Fruit or Melon as any superclass reference can point
//to its subclass object.
But wait what if someone decides to make a new type of Lemon lets say for arguments sake SaltyLemon as
public class SaltyLemon extends Lemon{}
Now fruitExtendedList can be list of Fruit, Melon, WaterMelon or SaltyLemon.
So, our statement
fruitExtendedList.add(new WaterMelon())
is not valid either.
Basically we can say that we cannot write anything to a fruitExtendedList.
This sums up List<? extends Fruit>
Now lets see
List<? super Melon> melonSuperList= …
//Says that I can be a list of anything as long as its object has super class of Melon.
Now lets try to get some value from melonSuperList
Fruit fruit = melonSuperList.get(position)
//This is not valid as melonSuperList can be a list of Object as in java all
//the object extends from Object class. So, Object can be super class of Melon and
//melonSuperList can be a list of Object type
Similarly Melon, WaterMelon or any other object cannot be read.
But note that we can read Object type instances
Object myObject = melonSuperList.get(position)
//This is valid because Object cannot have any super class and above statement
//can return only Fruit, Melon, WaterMelon or Object they all can be referenced by
//Object type reference.
Now, lets try to set some value from melonSuperList.
Adding Object type object
melonSuperList.add(new Object())
//This is not valid as melonSuperList can be a list of Fruit or Melon.
//Note that Melon itself can be considered as super class of Melon.
Adding Fruit type object
melonSuperList.add(new Fruit())
//This is also not valid as melonSuperList can be list of Melon
Adding Melon type object
melonSuperList.add(new Melon())
//This is valid because melonSuperList can be list of Object, Fruit or Melon and in
//this entire list we can add Melon type object.
Adding WaterMelon type object
melonSuperList.add(new WaterMelon())
//This is also valid because of same reason as adding Melon
To sum it up we can add Melon or its subclass in melonSuperList and read only Object type object.
SQL multiple column ordering
Multiple column ordering depends on both column's corresponding values:
Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.
Now I perform Order By in these two columns by executing below command:
Now again I insert new values in these two columns, where Alphabet value in ASC order:
and the columns in Example table look like this.
Now again perform the same operation:
You can see the values in the first column are in desc order but second column is not in ASC order.
Specifying and saving a figure with exact size in pixels
Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example this link will detect that for you.
If you have an image of 3841x7195 pixels it is unlikely that you monitor will be that large, so you won't be able to show a figure of that size (matplotlib requires the figure to fit in the screen, if you ask for a size too large it will shrink to the screen size). Let's imagine you want an 800x800 pixel image just for an example. Here's how to show an 800x800 pixel image in my monitor (my_dpi=96
):
plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)
So you basically just divide the dimensions in inches by your DPI.
If you want to save a figure of a specific size, then it is a different matter. Screen DPIs are not so important anymore (unless you ask for a figure that won't fit in the screen). Using the same example of the 800x800 pixel figure, we can save it in different resolutions using the dpi
keyword of savefig
. To save it in the same resolution as the screen just use the same dpi:
plt.savefig('my_fig.png', dpi=my_dpi)
To to save it as an 8000x8000 pixel image, use a dpi 10 times larger:
plt.savefig('my_fig.png', dpi=my_dpi * 10)
Note that the setting of the DPI is not supported by all backends. Here, the PNG backend is used, but the pdf and ps backends will implement the size differently. Also, changing the DPI and sizes will also affect things like fontsize. A larger DPI will keep the same relative sizes of fonts and elements, but if you want smaller fonts for a larger figure you need to increase the physical size instead of the DPI.
Getting back to your example, if you want to save a image with 3841 x 7195 pixels, you could do the following:
plt.figure(figsize=(3.841, 7.195), dpi=100)
( your code ...)
plt.savefig('myfig.png', dpi=1000)
Note that I used the figure dpi of 100 to fit in most screens, but saved with dpi=1000
to achieve the required resolution. In my system this produces a png with 3840x7190 pixels -- it seems that the DPI saved is always 0.02 pixels/inch smaller than the selected value, which will have a (small) effect on large image sizes. Some more discussion of this here.
Is there a reason for C#'s reuse of the variable in a foreach?
The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.
Your criticism is entirely justified.
I discuss this problem in detail here:
Closing over the loop variable considered harmful
Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.
I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.
The for
loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.
How do I call a dynamically-named method in Javascript?
Here is a working and simple solution for checking existence of a function and triaging that function dynamically by another function;
Trigger function
function runDynmicFunction(functionname){
if (typeof window[functionname] == "function" ) { //check availability
window[functionname]("this is from the function it "); //run function and pass a parameter to it
}
}
and you can now generate the function dynamically maybe using php like this
function runThis_func(my_Parameter){
alert(my_Parameter +" triggerd");
}
now you can call the function using dynamically generated event
<?php
$name_frm_somware ="runThis_func";
echo "<input type='button' value='Button' onclick='runDynmicFunction(\"".$name_frm_somware."\");'>";
?>
the exact HTML code you need is
<input type="button" value="Button" onclick="runDynmicFunction('runThis_func');">
Matplotlib legends in subplot
This should work:
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")
How to convert UTF8 string to byte array?
The logic of encoding Unicode in UTF-8 is basically:
- Up to 4 bytes per character can be used. The fewest number of bytes possible is used.
- Characters up to U+007F are encoded with a single byte.
- For multibyte sequences, the number of leading 1 bits in the first byte gives the number of bytes for the character. The rest of the bits of the first byte can be used to encode bits of the character.
- The continuation bytes begin with 10, and the other 6 bits encode bits of the character.
Here's a function I wrote a while back for encoding a JavaScript UTF-16 string in UTF-8:
function toUTF8Array(str) {
var utf8 = [];
for (var i=0; i < str.length; i++) {
var charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6),
0x80 | (charcode & 0x3f));
}
else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(0xe0 | (charcode >> 12),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
// surrogate pair
else {
i++;
// UTF-16 encodes 0x10000-0x10FFFF by
// subtracting 0x10000 and splitting the
// 20 bits of 0x0-0xFFFFF into two halves
charcode = 0x10000 + (((charcode & 0x3ff)<<10)
| (str.charCodeAt(i) & 0x3ff));
utf8.push(0xf0 | (charcode >>18),
0x80 | ((charcode>>12) & 0x3f),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
}
return utf8;
}
Create auto-numbering on images/figures in MS Word
I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).
Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:
- Select all text in your document (easiest way is to press ctrl-a)
- Press F9, this command tells Word to update all fields in the selection.
Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.
Changing the current working directory in Java?
You can use
new File("relative/path").getAbsoluteFile()
after
System.setProperty("user.dir", "/some/directory")
System.setProperty("user.dir", "C:/OtherProject");
File file = new File("data/data.csv").getAbsoluteFile();
System.out.println(file.getPath());
Will print
C:\OtherProject\data\data.csv
sqlite3.OperationalError: unable to open database file
In my case the sqlite db file db.sqlite3
was stored in the DocumentRoot
of apache. So, even after setting the following permissions it didn't work:
sudo chown www-data:www-data /path/to/db-folder
sudo chown www-data:www-data /path/to/db-folder/sqlite-db.db
Finally when i moved db.sqlite3
to a newly created folder dbfolder
under DocumentRoot
and gave the above permissions, and it worked.
How to convert image to byte array
Here's what I'm currently using. Some of the other techniques I've tried have been non-optimal because they changed the bit depth of the pixels (24-bit vs. 32-bit) or ignored the image's resolution (dpi).
// ImageConverter object used to convert byte arrays containing JPEG or PNG file images into
// Bitmap objects. This is static and only gets instantiated once.
private static readonly ImageConverter _imageConverter = new ImageConverter();
Image to byte array:
/// <summary>
/// Method to "convert" an Image object into a byte array, formatted in PNG file format, which
/// provides lossless compression. This can be used together with the GetImageFromByteArray()
/// method to provide a kind of serialization / deserialization.
/// </summary>
/// <param name="theImage">Image object, must be convertable to PNG format</param>
/// <returns>byte array image of a PNG file containing the image</returns>
public static byte[] CopyImageToByteArray(Image theImage)
{
using (MemoryStream memoryStream = new MemoryStream())
{
theImage.Save(memoryStream, ImageFormat.Png);
return memoryStream.ToArray();
}
}
Byte array to Image:
/// <summary>
/// Method that uses the ImageConverter object in .Net Framework to convert a byte array,
/// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be
/// used as an Image object.
/// </summary>
/// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
/// <returns>Bitmap object if it works, else exception is thrown</returns>
public static Bitmap GetImageFromByteArray(byte[] byteArray)
{
Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);
if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
bm.VerticalResolution != (int)bm.VerticalResolution))
{
// Correct a strange glitch that has been observed in the test program when converting
// from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts"
// slightly away from the nominal integer value
bm.SetResolution((int)(bm.HorizontalResolution + 0.5f),
(int)(bm.VerticalResolution + 0.5f));
}
return bm;
}
Edit: To get the Image from a jpg or png file you should read the file into a byte array using File.ReadAllBytes():
Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
This avoids problems related to Bitmap wanting its source stream to be kept open, and some suggested workarounds to that problem that result in the source file being kept locked.
Html.EditorFor Set Default Value
Shove it in the ViewBag
:
Controller:
ViewBag.ProductId = 1;
View:
@Html.TextBoxFor(c => c.Propertyname, new {@Value = ViewBag.ProductId})
Random element from string array
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
Google Maps v3 - limit viewable area and zoom level
As of middle 2016, there is no official way to restrict viewable area. Most of ad-hoc solutions to restrict the bounds have a flaw though, because they don't restrict the bounds exactly to fit the map view, they only restrict it if the center of the map is out of the specified bounds. If you want to restrict the bounds to overlaying image like me, this can result in a behavior like illustrated below, where the underlaying map is visible under our image overlay:
To tackle this issue, I have created a library, which successfully restrict the bounds so you cannot pan out of the overlay.
However, as other existing solutions, it has a "vibrating" issue. When the user pans the map aggressively enough, after they release the left mouse button, the map still continues panning by itself, gradually slowing. I always return the map back to the bounds, but that results in kind of vibrating. This panning effect cannot be stopped with any means provided by the Js API at the moment. It seems that until google adds support for something like map.stopPanningAnimation() we won't be able to create a smooth experience.
Example using the mentioned library, the smoothest strict bounds experience I was able to get:
_x000D_
_x000D_
function initialise(){_x000D_
_x000D_
var myOptions = {_x000D_
zoom: 5,_x000D_
center: new google.maps.LatLng(0,0),_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP,_x000D_
};_x000D_
var map = new google.maps.Map(document.getElementById('map'), myOptions);_x000D_
_x000D_
addStrictBoundsImage(map);_x000D_
}_x000D_
_x000D_
function addStrictBoundsImage(map){_x000D_
var bounds = new google.maps.LatLngBounds(_x000D_
new google.maps.LatLng(62.281819, -150.287132),_x000D_
new google.maps.LatLng(62.400471, -150.005608));_x000D_
_x000D_
var image_src = 'https://developers.google.com/maps/documentation/' +_x000D_
'javascript/examples/full/images/talkeetna.png';_x000D_
_x000D_
var strict_bounds_image = new StrictBoundsImage(bounds, image_src, map);_x000D_
}
_x000D_
<script type="text/javascript" src="http://www.google.com/jsapi"></script>_x000D_
<script type="text/javascript">_x000D_
google.load("maps", "3",{other_params:"sensor=false"});_x000D_
</script>_x000D_
<body style="margin:0px; padding:0px;" onload="initialise()">_x000D_
<div id="map" style="height:400px; width:500px;"></div>_x000D_
<script type="text/javascript"src="https://raw.githubusercontent.com/matej-pavla/StrictBoundsImage/master/StrictBoundsImage.js"></script>_x000D_
</body>
_x000D_
_x000D_
_x000D_
The library is also able to calculate the minimum zoom restriction automatically. It then restricts the zoom level using minZoom
map's attribute.
Hopefully this helps someone who wants a solution which fully respect the given boundaries and doesn't want to allow panning out of them.
Is there a naming convention for MySQL?
Consistency is what everyone strongly suggest, the rest is upto you as long as it works.
For beginners its easy to get carried away and we name whatever we want at that time. This make sense at that point but a headache later.
foo
foobar
or foo_bar
is great.
We name our table straight forward as much as possible and only use underscore if they are two different words. studentregistration
to student_registration
like @Zbyszek says, having a simple id
is more than enough for the auto-increment. The simplier the better. Why do you need foo_id
? We had the same problem early on, we named all our columns with the table prefix. like foo_id
, foo_name
, foo_age
. We dropped the tablename now and kept only the col as short as possible.
Since we are using just an id for PK we will be using foo_bar_fk
(tablename is unique, folowed by the unique PK, followed by the _fk
) as foreign key. We don't add id
to the col name because it is said that the name 'id' is always the PK of the given table. So we have just the tablename and the _fk
at the end.
For constrains we remove all underscores and join with camelCase (tablename + Colname + Fk) foobarUsernameFk
(for username_fk col). It's just a way we are following. We keep a documentation for every names structures.
When keeping the col name short, we should also keep an eye on the RESTRICTED names.
+------------------------------------+
| foobar |
+------------------------------------+
| id (PK for the current table) |
| username_fk (PK of username table) |
| location (other column) |
| tel (other column) |
+------------------------------------+
Making a cURL call in C#
Well if you are new to C# with cmd-line exp. you can use online sites like "https://curl.olsh.me/" or search curl to C# converter will returns site that could do that for you.
or if you are using postman you can use Generate Code Snippet only problem with Postman code generator is the dependency on RestSharp library.
Java Array, Finding Duplicates
Don't use ==
use .equals
.
try this instead (IIRC, ZipCode needs to implement Comparable
for this to work.
boolean unique;
Set<ZipCode> s = new TreeSet<ZipCode>();
for( ZipCode zc : zipcodelist )
unique||=s.add(zc);
duplicates = !unique;
How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?
Note that I prefer the code to be short.
List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.ToList();
or with a simple foreach
:
List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
if (item.Selected) selected.Add(item);
If you just want the ListItem.Value
:
List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
C# ListView Column Width Auto
Expanding a bit on Fredrik's answer, if you want to set the column's auto-resize width on the fly
for example: setting the first column's auto-size width to 70:
myListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.None);
myListView.Columns[0].Width = 70;
myListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
What is the best way to get the minimum or maximum value from an Array of numbers?
Amazed no-one mentioned parallelism here.
If you got really a huge array, you can use parallel-for, on sub ranges.
In the end compare all sub-ranges.
But parallelism comes width some penalty too, so this would not optimize on small arrays. However if you got huge datasets it starts to make sense, and you get a time division reduction nearing the amount of threads performing the test.
Android Pop-up message
Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:
Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}
SQL Server Linked Server Example Query
The format should probably be:
<server>.<database>.<schema>.<table>
For example:
DatabaseServer1.db1.dbo.table1
Update: I know this is an old question and the answer I have is correct; however, I think any one else stumbling upon this should know a few things.
Namely, when querying against a linked server in a join situation the ENTIRE table from the linked server will likely be downloaded to the server the query is executing from in order to do the join operation. In the OP's case, both table1
from DB1
and table1
from DB2
will be transferred in their entirety to the server executing the query, presumably named DB3
.
If you have large tables, this may result in an operation that takes a long time to execute. After all it is now constrained by network traffic speeds which is orders of magnitude slower than memory or even disk transfer speeds.
If possible, perform a single query against the remote server, without joining to a local table, to pull the data you need into a temp table. Then query off of that.
If that's not possible then you need to look at the various things that would cause SQL server to have to load the entire table locally. For example using GETDATE()
or even certain joins. Others performance killers include not giving appropriate rights.
See http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/ for some more info.
PHP fwrite new line
How about you store it like this?
Maybe in username:password format, so
sebastion:password123
anotheruser:password321
Then you can use list($username,$password) = explode(':',file_get_contents('users.txt'));
to parse the data on your end.
How to install wkhtmltopdf on a linux based (shared hosting) web server
A few things have changed since the top answers were added. They used to work out for me, but not quite anymore, so I have been hacking around for a bit and came up with the following solution for Ubuntu 16.04. For Ubuntu 14.04, see the comment at the bottom of the answer. Apologies if this doesn't work for shared hosting, but it seems like this is the goto answer for wkhtmltopdf installation instructions in general.
# Install dependencies
apt-get install libfontconfig \
zlib1g \
libfreetype6 \
libxrender1 \
libxext6 \
libx11-6
# TEMPORARY FIX! SEE: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/3001
apt-get install libssl1.0.0=1.0.2g-1ubuntu4.8
apt-get install libssl-dev=1.0.2g-1ubuntu4.8
# Download, extract and move binary in place
curl -L -o wkhtmltopdf.tar.xz https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
tar -xf wkhtmltopdf.tar.xz
mv wkhtmltox/bin/wkhtmltopdf /usr/local/bin/wkhtmltopdf
chmod +x /usr/local/bin/wkhtmltopdf
Test it out:
wkhtmltopdf http://www.google.com google.pdf
You should now have a file named google.pdf
in the current working directory.
This approach downloads the binary from the website, meaning that you can use the latest version instead of relying on package managers to be updated.
Note that as of today, my solution includes a temporary fix to this bug. I realize that the solution is really not great, but hopefully it can be removed soon. Be sure to check the status of the linked GitHub issue to see if the fix is still necessary when you read this answer!
For Ubuntu 14.04, you will need to downgrade to a different version of libssl. You can find the versions here. Anyways, be sure to consider the implications of downgrading libssl before doing so on any production server.
I hope this helps someone!
How to add fonts to create-react-app based projects?
I spent the entire morning solving a similar problem after having landed on this stack question. I used Dan's first solution in the answer above as the jump off point.
Problem
I have a dev (this is on my local machine), staging, and production environment. My staging and production environments live on the same server.
The app is deployed to staging via acmeserver/~staging/note-taking-app
and the production version lives at acmeserver/note-taking-app
(blame IT).
All the media files such as fonts were loading perfectly fine on dev (i.e., react-scripts start
).
However, when I created and uploaded staging and production builds, while the .css
and .js
files were loading properly, fonts were not. The compiled .css
file looked to have a correct path but the browser http request was getting some very wrong pathing (shown below).
The compiled main.fc70b10f.chunk.css
file:
@font-face {
font-family: SairaStencilOne-Regular;
src: url(note-taking-app/static/media/SairaStencilOne-Regular.ca2c4b9f.ttf) ("truetype");
}
The browser http request is shown below. Note how it is adding in /static/css/
when the font file just lives in /static/media/
as well as duplicating the destination folder. I ruled out the server config being the culprit.
The Referer
is partly at fault too.
GET /~staging/note-taking-app/static/css/note-taking-app/static/media/SairaStencilOne-Regular.ca2c4b9f.ttf HTTP/1.1
Host: acmeserver
Origin: http://acmeserver
Referer: http://acmeserver/~staging/note-taking-app/static/css/main.fc70b10f.chunk.css
The package.json
file had the homepage
property set to ./note-taking-app
. This was causing the problem.
{
"name": "note-taking-app",
"version": "0.1.0",
"private": true,
"homepage": "./note-taking-app",
"scripts": {
"start": "env-cmd -e development react-scripts start",
"build": "react-scripts build",
"build:staging": "env-cmd -e staging npm run build",
"build:production": "env-cmd -e production npm run build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
//...
}
Solution
That was long winded — but the solution is to:
- change the
PUBLIC_URL
env variable depending on the environment
- remove the
homepage
property from the package.json
file
Below is my .env-cmdrc
file. I use .env-cmdrc
over regular .env
because it keeps everything together in one file.
{
"development": {
"PUBLIC_URL": "",
"REACT_APP_API": "http://acmeserver/~staging/note-taking-app/api"
},
"staging": {
"PUBLIC_URL": "/~staging/note-taking-app",
"REACT_APP_API": "http://acmeserver/~staging/note-taking-app/api"
},
"production": {
"PUBLIC_URL": "/note-taking-app",
"REACT_APP_API": "http://acmeserver/note-taking-app/api"
}
}
Routing via react-router-dom
works fine too — simply use the PUBLIC_URL
env variable as the basename
property.
import React from "react";
import { BrowserRouter } from "react-router-dom";
const createRouter = RootComponent => (
<BrowserRouter basename={process.env.PUBLIC_URL}>
<RootComponent />
</BrowserRouter>
);
export { createRouter };
The server config is set to route all requests to the ./index.html
file.
Finally, here is what the compiled main.fc70b10f.chunk.css
file looks like after the discussed changes were implemented.
@font-face {
font-family: SairaStencilOne-Regular;
src: url(/~staging/note-taking-app/static/media/SairaStencilOne-Regular.ca2c4b9f.ttf)
format("truetype");
}
Reading material
Adding rows to dataset
DataSet myDataset = new DataSet();
DataTable customers = myDataset.Tables.Add("Customers");
customers.Columns.Add("Name");
customers.Columns.Add("Age");
customers.Rows.Add("Chris", "25");
//Get data
DataTable myCustomers = myDataset.Tables["Customers"];
DataRow currentRow = null;
for (int i = 0; i < myCustomers.Rows.Count; i++)
{
currentRow = myCustomers.Rows[i];
listBox1.Items.Add(string.Format("{0} is {1} YEARS OLD", currentRow["Name"], currentRow["Age"]));
}
How to check if user input is not an int value
Try this one:
for (;;) {
if (!sc.hasNextInt()) {
System.out.println(" enter only integers!: ");
sc.next(); // discard
continue;
}
choose = sc.nextInt();
if (choose >= 0) {
System.out.print("no problem with input");
} else {
System.out.print("invalid inputs");
}
break;
}
Replacement for deprecated sizeWithFont: in iOS 7?
- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
if ([self respondsToSelector:@selector(sizeWithAttributes:)])
{
NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
return ([self sizeWithAttributes:attribs]);
}
return ([self sizeWithFont:fontToUse]);
}
How to remove a file from the index in git?
You want:
git rm --cached [file]
If you omit the --cached
option, it will also delete it from the working tree. git rm
is slightly safer than git reset
, because you'll be warned if the staged content doesn't match either the tip of the branch or the file on disk. (If it doesn't, you have to add --force
.)
How to set the default value of an attribute on a Laravel model
The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
How to create exe of a console application
For .net core 2.1 console application, the following approaches worked for me:
1 - from CLI (after building the application and navigating to debug or release folders based on the build type specified):
dotnet appName.dll
2 - from Visual Studio
R.C solution and click publish
'Target location' -> 'configure' ->
'Deployment Mode' = 'Self-Contained'
'Target Runtime' = 'win-x64 or win-x86 depending on the OS'
References:
For an in depth explanation of all the deployment options available for .net core applications, checkout the following articles:
JPA - Persisting a One to Many relationship
You have to set the associatedEmployee on the Vehicle before persisting the Employee.
Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);
newEmployee.setVehicles(vehicles);
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
ViewBag, ViewData and TempData
ASP.NET MVC offers us three options ViewData, ViewBag, and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets discuss or get key points on those three objects:
Similarities between ViewBag & ViewData :
- Helps to maintain data when you move from controller to view.
- Used to pass data from controller to corresponding view.
- Short life means value becomes null when redirection occurs. This is
because their goal is to provide a way to communicate between
controllers and views. It’s a communication mechanism within the
server call.
Difference between ViewBag & ViewData:
- ViewData is a dictionary of objects that is derived from
ViewDataDictionary class and accessible using strings as keys.
- ViewBag is a dynamic property that takes advantage of the new dynamic
features in C# 4.0.
- ViewData requires typecasting for complex data type and check for
null values to avoid error.
- ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Monjurul Habib";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Monjurul Habib";
return View();
}
In View:
@ViewBag.Name
@ViewData["Name"]
TempData:
TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “TempData” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally used to store only one time messages like error messages, validation messages.
public ActionResult Index()
{
var model = new Review()
{
Body = "Start",
Rating=5
};
TempData["ModelName"] = model;
return RedirectToAction("About");
}
public ActionResult About()
{
var model= TempData["ModelName"];
return View(model);
}
The last mechanism is the Session which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information. Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.
Installing PG gem on OS X - failure to build native extension
Similarly, after installing Mavericks bundle update
was throwing an error on the pg gem, which is only used on production and not locally.
I use Brew to manage my packages and postgresql was already installed, but still I was getting the 'no pg_config' error.
The fix was to just brew uninstall postgresql
, then brew install postgresql
. After which I was immediately able to successfully run bundle update
.
Get image dimensions
You can use the getimagesize
function like this:
list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " . $height;
Find all files with name containing string
Use find
:
find . -maxdepth 1 -name "*string*" -print
It will find all files in the current directory (delete maxdepth 1
if you want it recursive) containing "string" and will print it on the screen.
If you want to avoid file containing ':', you can type:
find . -maxdepth 1 -name "*string*" ! -name "*:*" -print
If you want to use grep
(but I think it's not necessary as far as you don't want to check file content) you can use:
ls | grep touch
But, I repeat, find
is a better and cleaner solution for your task.
Raise warning in Python without interrupting program
By default, unlike an exception, a warning doesn't interrupt.
After import warnings
, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning
by default.
>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.
To simply use a preexisting class instead, e.g. DeprecationWarning
:
>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.
Creating a custom warning class is similar to creating a custom exception class:
>>> class MyCustomWarning(UserWarning):
... pass
...
... warnings.warn('This is my custom warning.', MyCustomWarning)
<string>:1: MyCustomWarning: This is my custom warning.
For testing, consider assertWarns
or assertWarnsRegex
.
As an alternative, especially for standalone applications, consider the logging
module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.
Escaping ampersand character in SQL string
--SUBSTITUTION VARIABLES
-- these variables are used to store values TEMPorarily.
-- The values can be stored temporarily through
-- Single Ampersand (&)
-- Double Ampersand(&&)
-- The single ampersand substitution variable applies for each instance when the
--SQL statement is created or executed.
-- The double ampersand substitution variable is applied for all instances until
--that SQL statement is existing.
INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');
--Using double ampersand substitution variable
INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,'&gender');
Passing command line arguments in Visual Studio 2010?
Visual Studio 2015:
Project
=>
Your Application Properties
. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.
static void Main(string[] args)
{
if(args == null || args.Length == 0)
{
Console.WriteLine("Please specify arguments!");
}
else
{
Console.WriteLine(args[0]); // First
Console.WriteLine(args[1]); // Second Argument
}
}
Bootstrap 3 with remote Modal
I did this:
$('#myModal').on 'shown.bs.modal', (e) ->
$(e.target).find('.modal-body').load('http://yourserver.com/content')
When & why to use delegates?
A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that's when you'll need delegates.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateApp {
/// <summary>
/// A class to define a person
/// </summary>
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}
class Program {
//Our delegate
public delegate bool FilterDelegate(Person p);
static void Main(string[] args) {
//Create 4 Person objects
Person p1 = new Person() { Name = "John", Age = 41 };
Person p2 = new Person() { Name = "Jane", Age = 69 };
Person p3 = new Person() { Name = "Jake", Age = 12 };
Person p4 = new Person() { Name = "Jessie", Age = 25 };
//Create a list of Person objects and fill it
List<Person> people = new List<Person>() { p1, p2, p3, p4 };
//Invoke DisplayPeople using appropriate delegate
DisplayPeople("Children:", people, IsChild);
DisplayPeople("Adults:", people, IsAdult);
DisplayPeople("Seniors:", people, IsSenior);
Console.Read();
}
/// <summary>
/// A method to filter out the people you need
/// </summary>
/// <param name="people">A list of people</param>
/// <param name="filter">A filter</param>
/// <returns>A filtered list</returns>
static void DisplayPeople(string title, List<Person> people, FilterDelegate filter) {
Console.WriteLine(title);
foreach (Person p in people) {
if (filter(p)) {
Console.WriteLine("{0}, {1} years old", p.Name, p.Age);
}
}
Console.Write("\n\n");
}
//==========FILTERS===================
static bool IsChild(Person p) {
return p.Age < 18;
}
static bool IsAdult(Person p) {
return p.Age >= 18;
}
static bool IsSenior(Person p) {
return p.Age >= 65;
}
}
}
Output:
Children:
Jake, 12 years old
Adults:
John, 41 years old
Jane, 69 years old
Jessie, 25 years old
Seniors:
Jane, 69 years old
How do I trigger a macro to run after a new mail is received in Outlook?
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
overlay two images in android to set an imageview
ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya:
The logo is going to be on top of shazam background image.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget39"
android:layout_width="219px"
android:layout_height="225px"
android:src="@drawable/shazam_bkgd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageView
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shazam_logo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
</RelativeLayout>
Byte and char conversion in Java
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
Service located in another namespace
To access services in two different namespaces you can use url like this:
HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local
To list out all your namespaces you can use:
kubectl get namespace
And for service in that namespace you can simply use:
kubectl get services -n <namespace-name>
this will help you.
What to do with commit made in a detached head
Alternatively, you could cherry-pick the commit-id onto your branch.
<commit-id> made in detached head state
git checkout master
git cherry-pick <commit-id>
No temporary branches, no merging.
CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?
Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.
The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.
To prevent CodeIgniter from doing this "favor" automatically, use the set()
method with a third parameter of false
.
$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login'); // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows(); // this is expected to return the integer: 1
The generated query (depending on your database adapter) would be like this:
UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444
Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0
In this case, Last
and Current
ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.
If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().
How to enable PHP's openssl extension to install Composer?
If you compiled from source, then adding extension=php_openssl.dll
to the php.ini file may not work.
To troubleshoot this, open a command prompt and type php -i
. Scroll up to the first line, it will tell you the most recent error regarding your php.ini file.
To solve the issue, find the php_openssl.dll
file, for me it was in the very same directory of the compilation output:
C:\php-sdk\bin\phpdev\vc14\x64\php-7.0.13-src\x64\Release_TS
So just add the directory where the extension is, to the php.ini
:
extension_dir = "C:\php-sdk\bin\phpdev\vc14\x64\php-7.0.13-src\x64\Release_TS"
Hopefully the error will be gone
Understanding Apache's access log
I also don't under stand what the "-" means after the 200 140 section
of the log
That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)
Using Jquery AJAX function with datatype HTML
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
Why isn't textarea an input[type="textarea"]?
So that its value can easily contain quotes and <> characters and respect whitespace and newlines.
The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Yes I can</title>
</head>
<body>
<textarea name="test">
I can put < and > and & signs in
my textarea without any problems.
</textarea>
</body>
</html>
Python Flask, how to set content type
I like and upvoted @Simon Sapin's answer. I ended up taking a slightly different tack, however, and created my own decorator:
from flask import Response
from functools import wraps
def returns_xml(f):
@wraps(f)
def decorated_function(*args, **kwargs):
r = f(*args, **kwargs)
return Response(r, content_type='text/xml; charset=utf-8')
return decorated_function
and use it thus:
@app.route('/ajax_ddl')
@returns_xml
def ajax_ddl():
xml = 'foo'
return xml
I think this is slightly more comfortable.
Getting the size of an array in an object
Arrays have a property .length
that returns the number of elements.
var st =
{
"itema":{},
"itemb":
[
{"id":"s01","cd":"c01","dd":"d01"},
{"id":"s02","cd":"c02","dd":"d02"}
]
};
st.itemb.length // 2
How can I select rows by range?
Following your clarification you're looking for limit:
SELECT * FROM `table` LIMIT 0, 10
This will display the first 10 results from the database.
SELECT * FROM `table` LIMIT 5, 5 .
Will display 5-9 (5,6,7,8,9)
The syntax follows the pattern:
SELECT * FROM `table` LIMIT [row to start at], [how many to include] .
The SQL for selecting rows where a column is between two values is:
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
See: http://www.w3schools.com/sql/sql_between.asp
If you want to go on the row number you can use rownum:
SELECT column_name(s)
FROM table_name
WHERE rownum
BETWEEN x AND y
However we need to know which database engine you are using as rownum is different for most.
How to access the php.ini from my CPanel?
You could try to find it via the command line.
find / -type f -name "php.ini"
Or you could add the following to a .htaccess
file in the root of your site.
php_value max_input_vars 6000
php_value suhosin.get.max_vars 6000
php_value suhosin.post.max_vars 6000
php_value suhosin.request.max_vars 6000
Dynamically load a JavaScript file
I did basically the same thing that you did Adam, but with a slight modification to make sure I was appending to the head tag to get the job done. I simply created an include function (code below) to handle both script and css files.
This function also checks to make sure that the script or CSS file hasn't already been loaded dynamically. It does not check for hand coded values and there may have been a better way to do that, but it served the purpose.
function include( url, type ){
// First make sure it hasn't been loaded by something else.
if( Array.contains( includedFile, url ) )
return;
// Determine the MIME-type
var jsExpr = new RegExp( "js$", "i" );
var cssExpr = new RegExp( "css$", "i" );
if( type == null )
if( jsExpr.test( url ) )
type = 'text/javascript';
else if( cssExpr.test( url ) )
type = 'text/css';
// Create the appropriate element.
var tag = null;
switch( type ){
case 'text/javascript' :
tag = document.createElement( 'script' );
tag.type = type;
tag.src = url;
break;
case 'text/css' :
tag = document.createElement( 'link' );
tag.rel = 'stylesheet';
tag.type = type;
tag.href = url;
break;
}
// Insert it to the <head> and the array to ensure it is not
// loaded again.
document.getElementsByTagName("head")[0].appendChild( tag );
Array.add( includedFile, url );
}
How can I convert a Timestamp into either Date or DateTime object?
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
// S is the millisecond
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");
System.out.println(simpleDateFormat.format(timestamp));
System.out.println(simpleDateFormat.format(date));
}
}
No shadow by default on Toolbar?
For 5.0 + : You can use AppBarLayout with Toolbar. AppBarLayout has "elevation" attribure.
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:elevation="4dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="@layout/toolbar" />
</android.support.design.widget.AppBarLayout>
How to generate a random string of 20 characters
Here you go. Just specify the chars you want to allow on the first line.
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
If you are using this to generate something sensitive like a password
reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead.
Values produced by java.util.Random
and java.util.concurrent.ThreadLocalRandom
are mathematically predictable.
ConcurrentHashMap vs Synchronized HashMap
As per java doc's
Hashtable and Collections.synchronizedMap(new HashMap()) are
synchronized. But ConcurrentHashMap is "concurrent".
A concurrent collection is thread-safe, but not governed by a single exclusion lock.
In the particular case of ConcurrentHashMap, it safely permits
any number of concurrent reads as well as a tunable number of
concurrent writes. "Synchronized" classes can be useful when you need
to prevent all access to a collection via a single lock, at the
expense of poorer scalability.
In other cases in which multiple
threads are expected to access a common collection, "concurrent"
versions are normally preferable. And unsynchronized collections are
preferable when either collections are unshared, or are accessible
only when holding other locks.
How to check if a folder exists
You need to transform your Path into a File
and test for existence:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
How can I convert a PFX certificate file for use with Apache on a linux server?
To get it to work with Apache, we needed one extra step.
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain_encrypted.key
openssl rsa -in domain_encrypted.key -out domain.key
The final command decrypts the key for use with Apache. The domain.key file should look like this:
-----BEGIN RSA PRIVATE KEY-----
MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
-----END RSA PRIVATE KEY-----
How can I generate Javadoc comments in Eclipse?
For me the /**<NEWLINE>
or Shift-Alt-J (or ?-?-J on a Mac) approach works best.
I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.
IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details.
Oracle - How to create a materialized view with FAST REFRESH and JOINS
You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense.
Page scroll up or down in Selenium WebDriver (Selenium 2) using java
Javascript executor always does the job perfectly:
((JavascriptExecutor) driver).executeScript("scroll(0,300)");
where (0,300)
are the horizontal and vertical distances respectively. Put your distances as per your requirements.
If you a perfectionist and like to get the exact distance you like to scroll up to on the first attempt, use this tool, MeasureIt. It's a brilliant firefox add-on.
Mipmaps vs. drawable folders
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
Cannot attach the file *.mdf as database
To fix this using SQL SERVER Management Studio
Your problem: You get an error such as 'Cannot attach the file 'YourDB.mdf' as database 'YourConnStringNamedContext';
Reason: happens because you deleted the backing files .mdf, ldf without actually deleting the database within the running instance of SqlLocalDb; re-running the code in VS won't help because you cannot re-create a DB with the same name (and that's why renaming works, but leaves the old phantom db name lying around).
The Fix: I am using VS2012, adopt similarly for a different version.
Navigate to below path and enter
c:\program files\microsoft sql server\110\Tools\Binn>sqllocaldb info
Above cmd shows the instance names, including 'v11.0'
If the instance is already running, enter at the prompt
sqllocaldb info v11.0
Note the following info
Owner: YourPCName\Username ,
State: Running ,
Instance pipe name: np:\.\pipe\LOCALDB#12345678\tsql\query ,
where 123456789 is some random alphanumeric
If State is not running or stopped, start the instance with
sqllocaldb start v11.0
and extract same info as above.
In the SS Management Studio 'Connect' dialog box enter
server name: np:\.\pipe\LOCALDB#12345678\tsql\query
auth: Windows auth
user name: (same as Owner, it is grayed out for Win. auth.)
Once connected, find the phantom DB which you deleted (e.g. YourDB.mdf should have created a db named YourDB), and really delete it.
Done! Once it's gone, VS EF should have no problem re-creating it.
How to restrict UITextField to take only numbers in Swift?
Swift 2.0
For only allowing numbers and one "." decimal in uitextfield.
func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool
{
let newCharacters = NSCharacterSet(charactersInString: string)
let boolIsNumber = NSCharacterSet.decimalDigitCharacterSet().isSupersetOfSet(newCharacters)
if boolIsNumber == true {
return true
} else {
if string == "." {
let countdots = textField.text!.componentsSeparatedByString(".").count - 1
if countdots == 0 {
return true
} else {
if countdots > 0 && string == "." {
return false
} else {
return true
}
}
} else {
return false
}
}
}
Decode Base64 data in Java
In a code compiled with Java 7 but potentially running in a higher java version, it seems useful to detect presence of java.util.Base64
class and use the approach best for given JVM mentioned in other questions here.
I used this code:
private static final Method JAVA_UTIL_BASE64_GETENCODER;
static {
Method getEncoderMethod;
try {
final Class<?> base64Class = Class.forName("java.util.Base64");
getEncoderMethod = base64Class.getMethod("getEncoder");
} catch (ClassNotFoundException | NoSuchMethodException e) {
getEncoderMethod = null;
}
JAVA_UTIL_BASE64_GETENCODER = getEncoderMethod;
}
static String base64EncodeToString(String s) {
final byte[] bytes = s.getBytes(StandardCharsets.ISO_8859_1);
if (JAVA_UTIL_BASE64_GETENCODER == null) {
// Java 7 and older // TODO: remove this branch after switching to Java 8
return DatatypeConverter.printBase64Binary(bytes);
} else {
// Java 8 and newer
try {
final Object encoder = JAVA_UTIL_BASE64_GETENCODER.invoke(null);
final Class<?> encoderClass = encoder.getClass();
final Method encodeMethod = encoderClass.getMethod("encode", byte[].class);
final byte[] encodedBytes = (byte[]) encodeMethod.invoke(encoder, bytes);
return new String(encodedBytes);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
}
Unique Key constraints for multiple columns in Entity Framework
With Entity Framework 6.1, you can now do this:
[Index("IX_FirstAndSecond", 1, IsUnique = true)]
public int FirstColumn { get; set; }
[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public int SecondColumn { get; set; }
The second parameter in the attribute is where you can specify the order of the columns in the index.
More information: MSDN
How to printf long long
// acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2
double pi = 2 * acos(0.0);
int n; // upto 6 digit
scanf("%d",&n); //precision with which you want the value of pi
printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision
SQL Sum Multiple rows into one
If you don't want to group your result, use a window function.
You didn't state your DBMS, but this is ANSI SQL:
SELECT AccountNumber,
Bill,
BillDate,
SUM(Bill) over (partition by accountNumber) as account_total
FROM Table1
order by AccountNumber, BillDate;
Here is an SQLFiddle: http://sqlfiddle.com/#!15/2c35e/1
You can even add a running sum, by adding:
sum(bill) over (partition by account_number order by bill_date) as sum_to_date
which will give you the total up to the current's row date.
OrderBy descending in Lambda expression?
This only works in situations where you have a numeric field, but you can put a minus sign in front of the field name like so:
reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);
However this works a little bit different than OrderByDescending
when you have are running it on an int?
or double?
or decimal?
fields.
What will happen is on OrderByDescending
the nulls will be at the end, vs with this method the nulls will be at the beginning. Which is useful if you want to shuffle nulls around without splitting data into pieces and splicing it later.
Set LIMIT with doctrine 2?
Your setMaxResults($limit) needs to be set on the object.
e.g.
$query_ids = $this->getEntityManager()
->createQuery(
"SELECT e_.id
FROM MuzichCoreBundle:Element e_
WHERE [...]
GROUP BY e_.id")
;
$query_ids->setMaxResults($limit);
SyntaxError: "can't assign to function call"
You are assigning to a function call:
invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount
which is illegal in Python. The question is, what do you want to do? What does invest()
do? I suppose it returns a value, namely what you're trying to use as subsequent_amount
, right?
If so, then something like this should work:
amount = invest(amount,top_company(5,year,year+1),year)
How to modify existing XML file with XmlDocument and XmlNode in C#
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
How to add a footer in ListView?
I know this is a very old question, but I googled my way here and found the answer provided not 100% satisfying, because as gcl1 mentioned - this way the footer is not really a footer to the screen - it's just an "add-on" to the list.
Bottom line - for others who may google their way here - I found the following suggestion here: Fixed and always visible footer below ListFragment
Try doing as follows, where the emphasis is on the button (or any footer element) listed first in the XML - and then the list is added as "layout_above":
<RelativeLayout>
<Button android:id="@+id/footer" android:layout_alignParentBottom="true"/>
<ListView android:id="@android:id/list" **android:layout_above**="@id/footer"> <!-- the list -->
</RelativeLayout>
File path for project files?
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")
base directory + your filename
How to convert Excel values into buckets?
I use this trick for equal data bucketing. Instead of text result you get the number. Here is example for four buckets. Suppose you have data in A1:A100
range. Put this formula in B1:
=MAX(ROUNDUP(PERCENTRANK($A$1:$A$100,A1) *4,0),1)
Fill down the formula all across B column and you are done. The formula divides the range into 4 equal buckets and it returns the bucket number which the cell A1 falls into. The first bucket contains the lowest 25% of values.
Adjust the number of buckets according to thy wish:
=MAX(ROUNDUP(PERCENTRANK([Range],[OneCellOfTheRangeToTest]) *[NumberOfBuckets],0),1)
The number of observation in each bucket will be equal or almost equal. For example if you have a 100 observations and you want to split it into 3 buckets (like in your example) then the buckets will contain 33, 33, 34 observations. So almost equal. You do not have to worry about that - the formula works that out for you.
Waiting for another flutter command to release the startup lock
There are some action to do:
1- in pubspec.yaml press "packages get" or in terminal type " flutter packages get" and wait seconds.
if this doesn't work :
2-type flutter clean then do step(1)
if this doesn't work too :
3-type killtask /f /im dart.exe
if this doesn't work too :
4- close android studio and then restart your pc.
Batch script to find and replace a string in text file within a minute for files up to 12 MB
Give this a shot:
@echo off
setlocal
call :FindReplace "findstr" "replacestr" input.txt
exit /b
:FindReplace <findstr> <replstr> <file>
set tmp="%temp%\tmp.txt"
If not exist %temp%\_.vbs call :MakeReplace
for /f "tokens=*" %%a in ('dir "%3" /s /b /a-d /on') do (
for /f "usebackq" %%b in (`Findstr /mic:"%~1" "%%a"`) do (
echo(&Echo Replacing "%~1" with "%~2" in file %%~nxa
<%%a cscript //nologo %temp%\_.vbs "%~1" "%~2">%tmp%
if exist %tmp% move /Y %tmp% "%%~dpnxa">nul
)
)
del %temp%\_.vbs
exit /b
:MakeReplace
>%temp%\_.vbs echo with Wscript
>>%temp%\_.vbs echo set args=.arguments
>>%temp%\_.vbs echo .StdOut.Write _
>>%temp%\_.vbs echo Replace(.StdIn.ReadAll,args(0),args(1),1,-1,1)
>>%temp%\_.vbs echo end with
Automatically pass $event with ng-click?
Take a peek at the ng-click
directive source:
...
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
It shows how the event
object is being passed on to the ng-click
expression, using $event
as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to bleed into the target scope, which means the answer is no, you can't access the $event
object any other way but through the callback parameter.
Create multiple threads and wait all of them to complete
I've made a very simple extension method to wait for all threads of a collection:
using System.Collections.Generic;
using System.Threading;
namespace Extensions
{
public static class ThreadExtension
{
public static void WaitAll(this IEnumerable<Thread> threads)
{
if(threads!=null)
{
foreach(Thread thread in threads)
{ thread.Join(); }
}
}
}
}
Then you simply call:
List<Thread> threads=new List<Thread>();
// Add your threads to this collection
threads.WaitAll();
Listview Scroll to the end of the list after updating the list
A combination of TRANSCRIPT_MODE_ALWAYS_SCROLL and setSelection made it work for me
ChatAdapter adapter = new ChatAdapter(this);
ListView lv = (ListView) findViewById(R.id.chatList);
lv.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lv.setAdapter(adapter);
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
lv.setSelection(adapter.getCount() - 1);
}
});
Convert image from PIL to openCV format
This is the shortest version I could find,saving/hiding an extra conversion:
pil_image = PIL.Image.open('image.jpg')
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)
If reading a file from a URL:
import cStringIO
import urllib
file = cStringIO.StringIO(urllib.urlopen(r'http://stackoverflow.com/a_nice_image.jpg').read())
pil_image = PIL.Image.open(file)
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)