Just setting json
option to true
, the body will contain the parsed json:
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});
As mentioned, @JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:
public void serialize(Item value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeNumber(id);
}
Yet another possibility is to implement JsonSerializable
, in which case no registration is needed.
As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend org.codehaus.jackson.map.ser.SerializerBase
as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).
Assuming that the remote repository has a copy of the develop branch (your initial description describes it in a local repository, but it sounds like it also exists in the remote), you should be able to achieve what I think you want, but the approach is a bit different from what you have envisioned.
Git’s history is based on a DAG of commits. Branches (and “refs” in general) are just transient labels that point to specific commits in the continually growing commit DAG. As such, the relationship between branches can vary over time, but the relationship between commits does not.
---o---1 foo
\
2---3---o bar
\
4
\
5---6 baz
It looks like baz
is based on (an old version of) bar
? But what if we delete bar
?
---o---1 foo
\
2---3
\
4
\
5---6 baz
Now it looks like baz
is based on foo
. But the ancestry of baz
did not change, we just removed a label (and the resulting dangling commit). And what if we add a new label at 4
?
---o---1 foo
\
2---3
\
4 quux
\
5---6 baz
Now it looks like baz
is based on quux
. Still, the ancestry did not change, only the labels changed.
If, however, we were asking “is commit 6
a descendent of commit 3
?” (assuming 3
and 6
are full SHA-1 commit names), then the answer would be “yes”, whether the bar
and quux
labels are present or not.
So, you could ask questions like “is the pushed commit a descendent of the current tip of the develop branch?”, but you can not reliably ask “what is the parent branch of the pushed commit?”.
A mostly reliable question that seems to get close to what you want is:
For all the pushed commit’s ancestors (excluding the current tip of develop and its ancestors), that have the current tip of develop as a parent:
- does at least one such commit exist?
- are all such commits single-parent commits?
Which could be implemented as:
pushedrev=...
basename=develop
if ! baserev="$(git rev-parse --verify refs/heads/"$basename" 2>/dev/null)"; then
echo "'$basename' is missing, call for help!"
exit 1
fi
parents_of_children_of_base="$(
git rev-list --pretty=tformat:%P "$pushedrev" --not "$baserev" |
grep -F "$baserev"
)"
case ",$parents_of_children_of_base" in
,) echo "must descend from tip of '$basename'"
exit 1 ;;
,*\ *) echo "must not merge tip of '$basename' (rebase instead)"
exit 1 ;;
,*) exit 0 ;;
esac
This will cover some of what you want restricted, but maybe not everything.
For reference, here is an extended example history:
A master
\
\ o-----J
\ / \
\ | o---K---L
\ |/
C--------------D develop
\ |\
F---G---H | F'--G'--H'
| |\
| | o---o---o---N
\ \ \ \
\ \ o---o---P
\ \
R---S
The above code could be used to reject H
and S
while accepting H'
, J
, K
, or N
, but it would also accept L
and P
(they involve merges, but they do not merge the tip of develop).
To also reject L
and P
, you can change the question and ask
For all the pushed commit’s ancestors (excluding the current tip of develop and its ancestors):
- are there any commits with two parents?
- if not, does at least one such commit have the current tip of develop its (only) parent?
pushedrev=...
basename=develop
if ! baserev="$(git rev-parse --verify refs/heads/"$basename" 2>/dev/null)"; then
echo "'$basename' is missing, call for help!"
exit 1
fi
parents_of_commits_beyond_base="$(
git rev-list --pretty=tformat:%P "$pushedrev" --not "$baserev" |
grep -v '^commit '
)"
case "$parents_of_commits_beyond_base" in
*\ *) echo "must not push merge commits (rebase instead)"
exit 1 ;;
*"$baserev"*) exit 0 ;;
*) echo "must descend from tip of '$basename'"
exit 1 ;;
esac
A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('enter,esc', function(event,handler){
switch(handler.key){
case "enter":$('.save').click();break;
case "esc":$('.cancel').click();break;
}
});
hotkeys understands the following modifiers: ?,shiftoption?altctrlcontrolcommand, and ?.
The following special keys can be used for shortcuts:backspacetab,clear,enter,return,esc,escape,space,up,down,left,right,home,end,pageup,pagedown,del,delete andf1 throughf19.
I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit javax.swing.AbstractButton
and create your own. Should be pretty simple to wire something together with their existing framework.
Use handy request.build_absolute_uri() method on request, pass it the relative url and it'll give you full one.
By default, the absolute URL for request.get_full_path()
is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.
The proper Swift operator is is
:
if touch.view is UIPickerView {
// touch.view is of type UIPickerView
}
Of course, if you also need to assign the view to a new constant, then the if let ... as? ...
syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you should use the is
operator.
For those looking for an inline example, here is one:
<audio controls style="width: 200px;">
<source src="http://somewhere.mp3" type="audio/mpeg">
</audio>
It doesn't seem to respect a "height" setting, at least not awesomely. But you can always "customize" the controls but creating your own controls (instead of using the built-in ones) or using somebody's widget that similarly creates its own :)
This is a one-liner but uses four atomic commands:
head -1000 file.txt > newfile.txt; tail +1000 file.txt > file.txt.tmp; cp file.txt.tmp file.txt; rm file.txt.tmp
The browser is connected to the proxy so the data that the proxy gets from the web server is just sent via the same connection that the browser initiated to the proxy.
If you've copied this directly, then:
->setCellValue('B2', Ackermann')
should be
->setCellValue('B2', 'Ackermann')
In answer to your question:
Get the data that you want from limesurvey, and use setCellValue() to store those data values in the cells where you want to store it.
The Quadratic.php example file in /Tests might help as a starting point: it takes data from an input form and sets it to cells in an Excel workbook.
EDIT
An extremely simplistic example:
// Create your database query
$query = "SELECT * FROM myDataTable";
// Execute the database query
$result = mysql_query($query) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){
// Set cell An to the "name" column from the database (assuming you have a column called name)
// where n is the Excel row number (ie cell A1 in the first row)
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']);
// Set cell Bn to the "age" column from the database (assuming you have a column called age)
// where n is the Excel row number (ie cell A1 in the first row)
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']);
// Increment the Excel row counter
$rowCount++;
}
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx');
EDIT #2
Using your existing code as the basis
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
//start of printing column names as names of MySQL fields
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)
{
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
$column++;
}
//end of adding column names
//start while loop to get data
$rowCount = 2;
while($row = mysql_fetch_row($result))
{
$column = 'A';
for($j=1; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
$column++;
}
$rowCount++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
In addition to keeping the variables local, one very handy use is when writing a library using a global variable, you can give it a shorter variable name to use within the library. It's often used in writing jQuery plugins, since jQuery allows you to disable the $ variable pointing to jQuery, using jQuery.noConflict(). In case it is disabled, your code can still use $ and not break if you just do:
(function($) { ...code...})(jQuery);
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
The path to the nginx.conf
file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf
.
You may access and edit this file by typing this at the terminal
cd /etc/nginx
/etc/nginx$ sudo nano nginx.conf
Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.
I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf
file which is the primary Configuration file for Nginx.
Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d
. Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-
http{
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
Further to this you may comment out from the PRIMARY Config file , the line
http{
#include /etc/nginx/sites-available/some_file.conf; # Comment Out
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
and need not keep any Config Files in /etc/nginx/sites-available/
and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/
, kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .
EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/
, this was the older practice and is DEPRECIATED now .
Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf;
.
Quote from Nginx CookBook page - 5 .
"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."
It seems that Luiggi Mendoza
and joey rohan
both already answered this, but I think it can be clarified a little.
You can write it as a single if
statement:
if (inventory.contains("bread") && !inventory.contains("water")) {
// do something
}
Well, does sleep
even exist on your Windows XP box? According to this post: http://malektips.com/xp_dos_0002.html sleep
isn't available on Windows XP, and you have to download the Windows 2003 Resource Kit in order to get it.
Chakrit's answer gives you another way to pause, too.
Try running sleep 10
from a command prompt.
"Bad style" is very subjective. If a certain conventions works for you and your team, I think that will qualify a bad/good style.
To answer your question: I use a leading underscore to mark private variables. I find it clear and I can scan through code fast and find out what's going on.
(I almost never use "this" though, except to prevent a name clash.)
I think you are putting one too many curly brackets. Try this
@if($user->status=='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
@else
<td>{!! $user->status !!}</td>
@endif
If you want all the units, not just the biggest one, use one of these 2 methods (based on @Ankish's answer):
Example output: 28 D | 23 H | 59 M | 59 S
+ (NSString *) remaningTime:(NSDate *)startDate endDate:(NSDate *)endDate
{
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate: startDate toDate: endDate options: 0];
return [NSString stringWithFormat:@"%ti D | %ti H | %ti M | %ti S", [components day], [components hour], [components minute], [components second]];
}
+ (NSString *) timeFromNowUntil:(NSDate *)endDate
{
return [self remaningTime:[NSDate date] endDate:endDate];
}
You don't need any webpack configuration for this..
In your component just give image path. By default react will know its in public directory.
<img src="/image.jpg" alt="image" />
I would echo the Json.NET library, which can transform the JSON response into a XML document. With the XML document, you can easily query with XPath and extract the data you need. I find this pretty useful.
you can use the sbstr() function
$amount = 1; //where $amount the amount of string you want to delete starting from index 0
$str = substr($str, $amount);
This will drop the outermost level from the hierarchical column index:
df = data.groupby(...).agg(...)
df.columns = df.columns.droplevel(0)
If you'd like to keep the outermost level, you can use the ravel() function on the multi-level column to form new labels:
df.columns = ["_".join(x) for x in df.columns.ravel()]
For example:
import pandas as pd
import pandas.rpy.common as com
import numpy as np
data = com.load_data('Loblolly')
print(data.head())
# height age Seed
# 1 4.51 3 301
# 15 10.89 5 301
# 29 28.72 10 301
# 43 41.74 15 301
# 57 52.70 20 301
df = data.groupby('Seed').agg(
{'age':['sum'],
'height':['mean', 'std']})
print(df.head())
# age height
# sum std mean
# Seed
# 301 78 22.638417 33.246667
# 303 78 23.499706 34.106667
# 305 78 23.927090 35.115000
# 307 78 22.222266 31.328333
# 309 78 23.132574 33.781667
df.columns = df.columns.droplevel(0)
print(df.head())
yields
sum std mean
Seed
301 78 22.638417 33.246667
303 78 23.499706 34.106667
305 78 23.927090 35.115000
307 78 22.222266 31.328333
309 78 23.132574 33.781667
Alternatively, to keep the first level of the index:
df = data.groupby('Seed').agg(
{'age':['sum'],
'height':['mean', 'std']})
df.columns = ["_".join(x) for x in df.columns.ravel()]
yields
age_sum height_std height_mean
Seed
301 78 22.638417 33.246667
303 78 23.499706 34.106667
305 78 23.927090 35.115000
307 78 22.222266 31.328333
309 78 23.132574 33.781667
This is not possible if you can't change your code. But I like dependency injection and Mockito supports it:
public class First {
@Resource
Second second;
public First() {
second = new Second();
}
public String doSecond() {
return second.doSecond();
}
}
Your test:
@RunWith(MockitoJUnitRunner.class)
public class YourTest {
@Mock
Second second;
@InjectMocks
First first = new First();
public void testFirst(){
when(second.doSecond()).thenReturn("Stubbed Second");
assertEquals("Stubbed Second", first.doSecond());
}
}
This is very nice and easy.
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
TRIM(BOTH chr(13)||chr(10)||' ' FROM str)
You try to set the height
property of an inline
element, which is not possible. You can try to make it a block
element, or perhaps you meant to alter the line-height
property?
If your goal is to remove all elements from the list, you can iterate over each item, and then call:
list.clear()
According to my practice, I use the 40 x 40 for standard iPad tab bar item icon, 80 X 80 for retina.
From the Apple reference. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1
If you want to create a bar icon that looks like it's related to the iOS 7 icon family, use a very thin stroke to draw it. Specifically, a 2-pixel stroke (high resolution) works well for detailed icons and a 3-pixel stroke works well for less detailed icons.
Regardless of the icon’s visual style, create a toolbar or navigation bar icon in the following sizes:
About 44 x 44 pixels About 22 x 22 pixels (standard resolution) Regardless of the icon’s visual style, create a tab bar icon in the following sizes:
About 50 x 50 pixels (96 x 64 pixels maximum) About 25 x 25 pixels (48 x 32 pixels maximum) for standard resolution
num1
and num2
are Long objects. You should be using equals()
to compare them. ==
comparison might work sometimes because of the way JVM boxes primitives, but don't depend on it.
if (num1.equals(num1))
{
//code
}
ALWAYS use scope_identity(), there's NEVER a need for anything else.
On providing this as input ,
li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s = ";".join(li)
print(s)
Python returns this as output :
'server=mpilgrim;uid=sa;database=master;pwd=secret'
Override all methods
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onStopTrackingTouch(SeekBar arg0) {
}
Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:
rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>'
+ '<img src="local_img.png"/>', canvas);
Source code and a more extensive example is here.
This should get you started:
R> qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))
See also this question: How can I manipulate the strip text of facet plots in ggplot2?
When you want to watch on state level, it can be done this way:
let App = new Vue({
//...
store,
watch: {
'$store.state.myState': function (newVal) {
console.log(newVal);
store.dispatch('handleMyStateChange');
}
},
//...
});
Use shortcut: Ctrl+Q. You can customize in Settings
The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities
$idsToFilter = array(1,2,3,4);
$member->getComments()->filter(
function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
}
);
Check your server config file /etc/mysql/my.cnf
- verify bind_address
is not set to 127.0.0.1
. Set it to 0.0.0.0
or comment it out then restart server with:
sudo service mysql restart
I think you should do
for index, row in result:
If you wanna access by name.
Use this if you want to reset the select to the option which has the "selected" attribute. Works similar to the form.reset() inbuilt javascript function to the select.
$("#name").val($("#name option[selected]").val());
I had the same problem. Whole form (including gif) stopping to redraw itself because of long operation working in the background. Here is how i solved this.
private void MyThreadRoutine()
{
this.Invoke(this.ShowProgressGifDelegate);
//your long running process
System.Threading.Thread.Sleep(5000);
this.Invoke(this.HideProgressGifDelegate);
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart myThreadStart = new ThreadStart(MyThreadRoutine);
Thread myThread = new Thread(myThreadStart);
myThread.Start();
}
I simply created another thread to be responsible for this operation. Thanks to this initial form continues redrawing without problems (including my gif working). ShowProgressGifDelegate and HideProgressGifDelegate are delegates in form that set visible property of pictureBox with gif to true/false.
Please visit the website and you will get Facebook, google+ and Twitter share links http://www.sharelinkgenerator.com/
Definitely a view is better than a nested query for SQL Server. Without knowing exactly why it is better (until I read Mark Brittingham's post), I had run some tests and experienced almost shocking performance improvements when using a view versus a nested query. After running each version of the query several hundred times in a row, the view version of the query completed in half the time. I'd say that's proof enough for me.
Just so you know isDirectory() is quite a slow method. I'm finding it quite slow in my file browser. I'll be looking into a library to replace it with native code.
I had the same problem. Mine was due to a third jar, but the logcat did not catch the exception, i solved by update the third jar, hope these will help.
I propose a simple TLDR:; example for the un-initiated.
Create a bash script called helloworld.sh
#!/bin/bash
while getopts "n:" arg; do
case $arg in
n) Name=$OPTARG;;
esac
done
echo "Hello $Name!"
You can then pass an optional parameter -n
when executing the script.
Execute the script as such:
$ bash helloworld.sh -n 'World'
Output
$ Hello World!
Notes
If you'd like to use multiple parameters:
while getops "n:" arg: do
with more paramaters such as
while getops "n:o:p:" arg: do
o) Option=$OPTARG
and p) Parameter=$OPTARG
We can use relative path instead of absolute path:
$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
background-image: url(#{$logo-img});
}
.logo {
max-width: 65px;
@include logo;
}
Something along the lines of (using JSTL):
<p>Selected Values:
<ul>
<c:forEach items="${paramValues['select2']}" var="selectedValue">
<li><c:out value="${selectedValue}" /></li>
</c:forEach>
</ul>
</p>
Multiple Linear Regression can be handled using the sklearn library as referenced above. I'm using the Anaconda install of Python 3.6.
Create your model as follows:
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X, y)
# display coefficients
print(regressor.coef_)
This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this.( with or without an external library).
Type collectionType = new TypeToken<List<Class>>() {
} // end new
.getType();
String gsonString =
new Gson().toJson(objList, collectionType);
Change column position:
ALTER TABLE Employees
CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;
If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:
ALTER TABLE UserOrder
CHANGE order_id order_id INT(11) NOT NULL FIRST;
You guys are very close to explaining this fully, but missing a couple things. The hashtable is just an array. The array itself will contain something in each slot. At a minimum you will store the hashvalue or the value itself in this slot. In addition to this you could also store a linked/chained list of values that have collided on this slot, or you could use the open addressing method. You can also store a pointer or pointers to other data you want to retrieve out of this slot.
It's important to note that the hashvalue itself generally does not indicate the slot into which to place the value. For example, a hashvalue might be a negative integer value. Obviously a negative number cannot point to an array location. Additionally, hash values will tend to many times be larger numbers than the slots available. Thus another calculation needs to be performed by the hashtable itself to figure out which slot the value should go into. This is done with a modulus math operation like:
uint slotIndex = hashValue % hashTableSize;
This value is the slot the value will go into. In open addressing, if the slot is already filled with another hashvalue and/or other data, the modulus operation will be run once again to find the next slot:
slotIndex = (remainder + 1) % hashTableSize;
I suppose there may be other more advanced methods for determining slot index, but this is the common one I've seen... would be interested in any others that perform better.
With the modulus method, if you have a table of say size 1000, any hashvalue that is between 1 and 1000 will go into the corresponding slot. Any Negative values, and any values greater than 1000 will be potentially colliding slot values. The chances of that happening depend both on your hashing method, as well as how many total items you add to the hash table. Generally, it's best practice to make the size of the hashtable such that the total number of values added to it is only equal to about 70% of its size. If your hash function does a good job of even distribution, you will generally encounter very few to no bucket/slot collisions and it will perform very quickly for both lookup and write operations. If the total number of values to add is not known in advance, make a good guesstimate using whatever means, and then resize your hashtable once the number of elements added to it reaches 70% of capacity.
I hope this has helped.
PS - In C# the GetHashCode()
method is pretty slow and results in actual value collisions under a lot of conditions I've tested. For some real fun, build your own hashfunction and try to get it to NEVER collide on the specific data you are hashing, run faster than GetHashCode, and have a fairly even distribution. I've done this using long instead of int size hashcode values and it's worked quite well on up to 32 million entires hashvalues in the hashtable with 0 collisions. Unfortunately I can't share the code as it belongs to my employer... but I can reveal it is possible for certain data domains. When you can achieve this, the hashtable is VERY fast. :)
Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
Hi Jack,
your function design is fine, but this function always misses the first dataset in the array. I tested that.
Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.
The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.
You can avoid that by moving the if condition above the second foreach loop like this:
function display_data($data) {
$output = "<table>";
foreach($data as $key => $var) {
//$output .= '<tr>';
if($key===0) {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= "<td>" . $col . '</td>';
}
$output .= '</tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
else {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
}
$output .= '</table>';
echo $output;
}
Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016
and another update that removes redundant code blocks that hurt maintainability of the code.
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
As an explanation to Jonathan Fingland's answer:
[position()=1 and @location='US']
) must be true as a whole[position()=1][@location='US']
) must be true one after another[position()=1][@location='US']
!= [@location='US'][position()=1]
[position()=1 and @location='US']
== [@location='US' and position()=1]
[position()=1]
can be abbreviated to [1]
You can build complex expressions in predicates with the Boolean operators "and
" and "or
", and with the Boolean XPath functions not()
, true()
and false()
. Plus you can wrap sub-expressions in parentheses.
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
date
and datetime
objects (and time
as well) support a mini-language to specify output, and there are two ways to access it:
dt.strftime('format here')
'{:format here}'.format(dt)
f'{dt:format here}'
So your example could look like:
dt.strftime('The date is %b %d, %Y')
'The date is {:%b %d, %Y}'.format(dt)
f'The date is {dt:%b %d, %Y}'
In all three cases the output is:
The date is Feb 23, 2012
For completeness' sake: you can also directly access the attributes of the object, but then you only get the numbers:
'The date is %s/%s/%s' % (dt.month, dt.day, dt.year)
# The date is 02/23/2012
The time taken to learn the mini-language is worth it.
For reference, here are the codes used in the mini-language:
%a
Weekday as locale’s abbreviated name.%A
Weekday as locale’s full name.%w
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.%d
Day of the month as a zero-padded decimal number.%b
Month as locale’s abbreviated name.%B
Month as locale’s full name.%m
Month as a zero-padded decimal number. 01, ..., 12%y
Year without century as a zero-padded decimal number. 00, ..., 99%Y
Year with century as a decimal number. 1970, 1988, 2001, 2013%H
Hour (24-hour clock) as a zero-padded decimal number. 00, ..., 23%I
Hour (12-hour clock) as a zero-padded decimal number. 01, ..., 12%p
Locale’s equivalent of either AM or PM.%M
Minute as a zero-padded decimal number. 00, ..., 59%S
Second as a zero-padded decimal number. 00, ..., 59%f
Microsecond as a decimal number, zero-padded on the left. 000000, ..., 999999%z
UTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030%Z
Time zone name (empty if naive), UTC, EST, CST%j
Day of the year as a zero-padded decimal number. 001, ..., 366%U
Week number of the year (Sunday is the first) as a zero padded decimal number.%W
Week number of the year (Monday is first) as a decimal number.%c
Locale’s appropriate date and time representation.%x
Locale’s appropriate date representation.%X
Locale’s appropriate time representation.%%
A literal '%' character.First Run;
CREATE PROCEDURE sp_First @columnname NVARCHAR(128)--128 = SQL Server Maximum Column Name Length
AS
BEGIN
DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT ' + @columnname + ' FROM Table_1'
EXEC(@query)
END
Second Run;
EXEC sp_First 'COLUMN_Name'
move.CompleteMove()
does not return a value (perhaps it just prints something). Any method that does not return a value returns None
, and you have assigned None
to self.values
.
Here is an example of this:
>>> def hello(x):
... print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>
You'll note y
doesn't print anything, because its None
(the only value that doesn't print anything on the interactive prompt).
Simply removing @RequestBody
annotation solves the problem (tested on Spring Boot 2):
@RestController
public class MyController {
@PostMapping
public void method(@Valid RequestDto dto) {
// method body ...
}
}
export VAR=value
will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'
. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR"
.
it don't needed port and brew! because you have android sdk package.
.1 edit your .bash_profile
export ANT_HOME="[your android_sdk_path/eclipse/plugins/org.apache.ant_1.8.3.v201301120609]"
// its only my org.apache.ant version, check your org.apache.ant version
export PATH=$PATH:$ANT_HOME/bin
.2 make ant command that can executed
chmod 770 [your ANT_HOME/bin/ant]
.3 test if you see below message. that's success!
command line execute: ant
Buildfile: build.xml does not exist!
Build failed
Here are some other reasons to consider:
structs get an automatic initializer that you don't have to maintain in code at all.
struct MorphProperty {
var type : MorphPropertyValueType
var key : String
var value : AnyObject
enum MorphPropertyValueType {
case String, Int, Double
}
}
var m = MorphProperty(type: .Int, key: "what", value: "blah")
To get this in a class, you would have to add the initializer, and maintain the intializer...
Basic collection types like Array
are structs. The more you use them in your own code, the more you will get used to passing by value as opposed to reference. For instance:
func removeLast(var array:[String]) {
array.removeLast()
println(array) // [one, two]
}
var someArray = ["one", "two", "three"]
removeLast(someArray)
println(someArray) // [one, two, three]
Apparently immutability vs. mutability is a huge topic, but a lot of smart folks think immutability -- structs in this case -- is preferable. Mutable vs immutable objects
Another multiple dropdown example that works https://jsfiddle.net/vgjddv6u/
$('.moderate .button').on('click', (event) => {_x000D_
$(event.target).siblings('.dropdown')_x000D_
.toggleClass('is-open');_x000D_
});_x000D_
_x000D_
$(document).click(function(e) {_x000D_
$('.moderate')_x000D_
.not($('.moderate').has($(e.target)))_x000D_
.children('.dropdown')_x000D_
.removeClass('is-open');_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" rel="stylesheet" />_x000D_
_x000D_
<script_x000D_
src="https://code.jquery.com/jquery-3.2.1.min.js"_x000D_
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="_x000D_
crossorigin="anonymous"></script>_x000D_
_x000D_
<style>_x000D_
.dropdown {_x000D_
box-shadow: 0 0 2px #777;_x000D_
display: none;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
padding: 2px;_x000D_
z-index: 10;_x000D_
}_x000D_
_x000D_
.dropdown a {_x000D_
font-size: 12px;_x000D_
padding: 4px;_x000D_
}_x000D_
_x000D_
.dropdown.is-open {_x000D_
display: block;_x000D_
}_x000D_
</style>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
<button class="button is-small" type="button">_x000D_
moderate_x000D_
</button>_x000D_
_x000D_
<div class="box dropdown">_x000D_
<ul>_x000D_
<li><a class="nav-item">edit</a></li>_x000D_
<li><a class="nav-item">delete</a></li>_x000D_
<li><a class="nav-item">block user</a> </li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
<button class="button is-small" type="button">_x000D_
moderate_x000D_
</button>_x000D_
_x000D_
<div class="box dropdown">_x000D_
<ul>_x000D_
<li><a class="nav-item">edit</a></li>_x000D_
<li><a class="nav-item">delete</a></li>_x000D_
<li><a class="nav-item">block user</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>
_x000D_
I was facing same issue with my one of my feature branch. I tried above mentioned solution nothing worked. I resolved this issue by doing following things.
You could also use the whitelist method -
var str = $('#Search').val();
var regex = /[^\w\s]/gi;
if(regex.test(str) == true) {
alert('Your search string contains illegal characters.');
}
The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.
I just created an ArrayHelper class that would make this very easy for numeric indexes.
class ArrayHelper
{
/*
Inserts a value at the given position or throws an exception if
the position is out of range.
This function will push the current values up in index. ex. if
you insert at index 1 then the previous value at index 1 will
be pushed to index 2 and so on.
$pos: The position where the inserted value should be placed.
Starts at 0.
*/
public static function insertValueAtPos(array &$array, $pos, $value) {
$maxIndex = count($array)-1;
if ($pos === 0) {
array_unshift($array, $value);
} elseif (($pos > 0) && ($pos <= $maxIndex)) {
$firstHalf = array_slice($array, 0, $pos);
$secondHalf = array_slice($array, $pos);
$array = array_merge($firstHalf, array($value), $secondHalf);
} else {
throw new IndexOutOfBoundsException();
}
}
}
Example:
$array = array('a', 'b', 'c', 'd', 'e');
$insertValue = 'insert';
\ArrayHelper::insertValueAtPos($array, 3, $insertValue);
Beginning $array:
Array (
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
Result:
Array (
[0] => a
[1] => b
[2] => c
[3] => insert
[4] => d
[5] => e
)
Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.
In your class, do something like this:
public void setSqlResource(Resource sqlResource) {
this.sqlResource = sqlResource;
}
And then in your application context file, in the bean definition, just set a property:
<bean id="someBean" class="...">
<property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>
And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.
You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.
Use an relative path to the root of your site, for example:
If clock.js is on http://domain.com/javascript/clock.js
Include :
<script language="JavaScript" src="/javascript/clock.js"></script>
If it's on your domain root directory:
<script language="JavaScript" src="/clock.js"></script>
It's simpler to use, the -a option :
cat ~/campaigns/release-status.html | mail -s "Release Status [Green]" -a "Content-Type: text/html" [email protected]
Another way to solve the issue:
If you are using the support library, you need to add the appcompat
lib to the project. This link shows how to add the support lib to your project.
Assuming you have added the support lib earlier but you are getting the mentioned issue, you can follow the steps below to fix that.
Right click on the project and navigate to Build Path > Configure Build Path.
On the left side of the window, select Android. You will see something like this:
appcompat
lib and press OK. (Note: The lib will be shown if you have added them as mentioned earlier). Now you will see the following window:How about the following?
0[xX][0-9a-fA-F]+
Matches expression starting with a 0, following by either a lower or uppercase x, followed by one or more characters in the ranges 0-9, or a-f, or A-F
URI is kind of the super class of URL's and URN's. Wikipedia has a fine article about them with links to the right set of RFCs.
I prefer using the ggfortify
library. It is a ggplot2
wrapper that recognizes the type of object inside the autoplot function and chooses the best ggplot methods to plot. At least I don't have to remember the syntax of ggplot2.
library(ggfortify)
ts1 <- 1:100
ts2 <- 1:100*0.8
autoplot(ts( cbind(ts1, ts2) , start = c(2010,5), frequency = 12 ),
facets = FALSE)
SQL Server Management Studio 2008 R2 Express commandline:
The answer by dyslexicanaboko hits the crucial point, but this one is even simpler and suited for command line (unattended scenarios):
(tried out with SQL Server 2008 R2 Express, one instance installed and having downloaded SQLManagementStudio_x64_ENU.exe)
As pointed out in this thread often enough, it is better to use the original SQL server setup (e.g. SQL Express with Tools), if possible, but there are some scenarios, where you want to add SSMS at a SQL derivative without that tools, afterwards:
I´ve already put it in a batch syntax here:
@echo off
"%~dp0SQLManagementStudio_x64_ENU.exe" /Q /ACTION="Install" /FEATURES="SSMS" /IACCEPTSQLSERVERLICENSETERMS
Remarks:
For 2008 without R2 it should be enough to omit the /IACCEPTSQLSERVERLICENSETERMS flag, i guess.
The /INDICATEPROGRESS parameter is useless here, the whole command takes a number of minutes and is 100% silent without any acknowledgement. Just look at the start menu, if the command is ready, if it has succeeded.
This should work for the "ADV_SSMS" Feature (instead of "SSMS") too, which is the management studio extended variant (profiling, reporting, tuning, etc.)
The new v8 engine which should come out today supports it (i think)
The cc and cxx is located inside /Applications/Xcode.app
. This should find the right paths
export CXX=`xcrun -find c++`
export CC=`xcrun -find cc`
Quoting API on referencedColumnName:
The name of the column referenced by this foreign key column.
Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.
Where this would be used?
When there is a composite PK in referenced table, then you need to specify column name you are referencing.
1 - You can set a timeout in your application :
var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite
It is in milliseconds.
2 - Also you can increase timeout value in httpruntime tag in web/app.config :
<configuration>
<system.web>
<httpRuntime executionTimeout="<<**seconds**>>" />
...
</system.web>
</configuration>
For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source
Here is a simple slider object for easy to use
Difference between pass and continue in a for loop:
So why pass in python?
If you want to create a empty class, method or block.
Examples:
class MyException(Exception):
pass
try:
1/0
except:
pass
without 'pass' in the above examples will throw IndentationError.
jQuery.ajax({
type: 'GET',
url: "../struktur2/load.php",
async: false,
contentType: "application/json",
dataType: 'json',
success: function(json) {
items = json;
},
error: function(e) {
console.log("jQuery error message = "+e.message);
}
});
2019's answer as this is still actively seen today
You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.
original hack from 2015 that still works in some situations
You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.
If you cannot pull it out of the div for some reason, you should change the position style with this css:
.full-width-div {
position: absolute;
width: 100%;
left: 0;
}
Instead of absolute, you could also use fixed, but then it will not move as you scroll.
With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.
# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12
# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert
To verify the contents of the JKS, you can use this command:
keytool -list -v -keystore mykeystore.jks
If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.
which means that cacerts keystore isn't password protected
That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:
In order to verify its integrity, you must provide your keystore password.
Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.
If you want to remove duplicates from ArrayList means find the below logic,
public static Object[] removeDuplicate(Object[] inputArray)
{
long startTime = System.nanoTime();
int totalSize = inputArray.length;
Object[] resultArray = new Object[totalSize];
int newSize = 0;
for(int i=0; i<totalSize; i++)
{
Object value = inputArray[i];
if(value == null)
{
continue;
}
for(int j=i+1; j<totalSize; j++)
{
if(value.equals(inputArray[j]))
{
inputArray[j] = null;
}
}
resultArray[newSize++] = value;
}
long endTime = System.nanoTime()-startTime;
System.out.println("Total Time-B:"+endTime);
return resultArray;
}
If you use MAMP, make sure it's started. :)
I just ran into this problem, and after starting MAMP the error went away. Not my finest moment.
The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).
You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.
DO NOT use this:
System.Environment.GetEnvironmentVariable("TEMP")
Environment variables can be overridden, so the TEMP
variable is not necessarily the directory.
The correct way is to use System.IO.Path.GetTempPath()
as in the accepted answer.
This does a trick for me:
bash -c 'for (( I=100000000000000000000 ; I>=0 ; I++ )) ; do echo $(( I+I*I )) & echo $(( I*I-I )) & echo $(( I-I*I*I )) & echo $(( I+I*I*I )) ; done' &>/dev/null
and it uses nothing except bash.
I tested the ByteBuffer method against plain bitwise operations but the latter is significantly faster.
public static byte[] longToBytes(long l) {
byte[] result = new byte[8];
for (int i = 7; i >= 0; i--) {
result[i] = (byte)(l & 0xFF);
l >>= 8;
}
return result;
}
public static long bytesToLong(final byte[] b) {
long result = 0;
for (int i = 0; i < 8; i++) {
result <<= 8;
result |= (b[i] & 0xFF);
}
return result;
}
For Java 8+ we can use the static variables that were added:
public static byte[] longToBytes(long l) {
byte[] result = new byte[Long.BYTES];
for (int i = Long.BYTES - 1; i >= 0; i--) {
result[i] = (byte)(l & 0xFF);
l >>= Byte.SIZE;
}
return result;
}
public static long bytesToLong(final byte[] b) {
long result = 0;
for (int i = 0; i < Long.BYTES; i++) {
result <<= Byte.SIZE;
result |= (b[i] & 0xFF);
}
return result;
}
You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:
$('div#id').click(function (e) {
// Do whatever you want
});
This solution has the distinct advantage of keeping the logic not in your markup.
There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
And when you need it you can get it with :
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.
You can take a reference on the control on the ItemCreated event, and then use it later.
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
}
you can use valign="top"
on the td tag it is working perfectly for me.
This thing worked for me:
$scriptOutput = (cmd /s /c $FilePath $ArgumentList)
FileInfo
knows its own extension, so you could just remove it
fileInfo.Name.Replace(fileInfo.Extension, "");
fileInfo.FullName.Replace(fileInfo.Extension, "");
or if you're paranoid that it might appear in the middle, or want to microoptimize:
file.Name.Substring(0, file.Name.Length - file.Extension.Length)
So yes, you should prefer the shadowPath property for performance, but also: From the header file of CALayer.shadowPath
Specifying the path explicitly using this property will usually * improve rendering performance, as will sharing the same path * reference across multiple layers
A lesser known trick is sharing the same reference across multiple layers. Of course they have to use the same shape, but this is common with table/collection view cells.
I don't know why it gets faster if you share instances, i'm guessing it caches the rendering of the shadow and can reuse it for other instances in the view. I wonder if this is even faster with
I think this valid question is already answered here. I have tried it as well. My issue was simply using picture edit (from DevExpress). and this is how I got around it:
Thank you again. Chagbert
Step 1: Select top cell of the data
Step 2 : Select Data > Sort.
Step 3 : Select Data >Subtotal
Step 4 : Change use function to "count" and click OK.
Step 5 : Collapse to 2
DropDownList1.Items.FindByValue(stringValue).Selected = true;
should work.
list.pop()
removes and returns the last element of the list.
For my condition the cause was taking int
parameter for TextView
. Let me show an example
int i = 5;
myTextView.setText(i);
gets the error info above.
This can be fixed by converting int
to String
like this
myTextView.setText(String.valueOf(i));
As you write int
, it expects a resource not the text that you are writing. So be careful on setting an int
as a String
in Android.
Bootstrap 4
It is used to create a bottom margin of 0 (margin-bottom:0
). You can see more of the new spacing utility classes here: https://getbootstrap.com/docs/4.0/utilities/spacing/
Related: How do I use the Spacing Utility Classes on Bootstrap 4
Clear is faster because it does not loop over elements to delete. This method can assume that ALL elements can be deleted.
Remove all
does not necessarily mean delete all elements in the list, only those provided as parameters SHOULD be delete. Hence, more effort is required to keep those which should not be deleted.
CLARIFICATION
By 'loop', I mean it does not have to check whether the element should be kept or not. It can set the reference to null
without searching through the provided lists of elements to delete.
Clear
IS faster than deleteall
.
replace "150x150" with 720x720 and remove /vp/ from the link.it should work.
According to http://developers.facebook.com/docs/reference/dialogs/oauth/
for me worked
https://apps.facebook.com/YOUR_APP_NAMESPACE (watch fot http:// or https:// issue)
It turns out that the SSL certificate was installed improperly. Re-installing it properly fixed the problem
Try This
<!DOCTYPE html>
<html>
<head>
<title>Sticky Header and Footer</title>
<style type="text/css">
/* Reset body padding and margins */
body {
margin:0;
padding:0;
}
/* Make Header Sticky */
#header_container {
background:#eee;
border:1px solid #666;
height:60px;
left:0;
position:fixed;
width:100%;
top:0;
}
#header {
line-height:60px;
margin:0 auto;
width:940px;
text-align:center;
}
/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/
#container {
margin:0 auto;
overflow:auto;
padding:80px 0;
width:940px;
}
#content {
}
/* Make Footer Sticky */
#footer_container {
background:#eee;
border:1px solid #666;
bottom:0;
height:60px;
left:0;
position:fixed;
width:100%;
}
#footer {
line-height:60px;
margin:0 auto;
width:940px;
text-align:center;
}
</style>
</head>
<body>
<!-- BEGIN: Sticky Header -->
<div id="header_container">
<div id="header">
Header Content
</div>
</div>
<!-- END: Sticky Header -->
<!-- BEGIN: Page Content -->
<div id="container">
<div id="content">
content
<br /><br />
blah blah blah..
...
</div>
</div>
<!-- END: Page Content -->
<!-- BEGIN: Sticky Footer -->
<div id="footer_container">
<div id="footer">
Footer Content
</div>
</div>
<!-- END: Sticky Footer -->
</body>
</html>
Quoting the spec
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
And here's a table for typeof
To add some background, there are two data types in JavaScript:
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.
An array can be considered to be an object with the following properties/keys:
Hope this helped shed more light on why typeof Array returns an object. Cheers!
In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):
-Droot.log.level=TRACE
Turns out they are normal objects and you can access them through user_id
.
RowDataPacket is actually the name of the constructor function that creates an object, it would look like this new RowDataPacket(user_id, ...)
. You can check by accessing its name [0].constructor.name
If the result is an array, you would have to use [0].user_id
.
If you are using bash shell you can use this:
time bash -c $'
FILE=/dev/shm/test.db
sqlite3 $FILE "create table if not exists tab(id int);"
sqlite3 $FILE "insert into tab values (1),(2)"
for i in 1 2 3 4; do sqlite3 $FILE "INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5"; done;
sqlite3 $FILE "select count(*) from tab;"'
Or if you are in sqlite CLI, then you need to do this:
create table if not exists tab(id int);"
insert into tab values (1),(2);
INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (a.id+b.id+c.id)*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
select count(*) from tab;
How does it work?
It makes use of that if table tab
:
id int
------
1
2
then select a.id, b.id from tab a, tab b
returns
a.id int | b.id int
------------------
1 | 1
2 | 1
1 | 2
2 | 2
and so on. After first execution we insert 2 rows, then 2^3=8. (three because we have tab a, tab b, tab c
)
After second execution we insert additional (2+8)^3=1000
rows
Aftern thrid we insert about max(1000^3, 5e5)=500000
rows and so on...
This is the fastest known for me method of populating SQLite database.
Another jsperf.com test: http://jsperf.com/while-reverse-vs-for-cached-length
The reverse while loop seems to be the fastest. Only problem is that while (--i) will stop at 0. How can I access array[0] in my loop then?
You do not need to keep the system images unless you want to use the emulator on your desktop. Along with it you can remove other unwanted stuff to clear disk space.
Adding as an answer to my own question as I've had to narrate this to people in my team more than a few times. Hence this answer as a reference to share with other curious ones.
In the last few weeks there were several colleagues who asked me how to safely get rid of the unwanted stuff to release disk space (most of them were beginners). I redirected them to this question but they came back to me for steps. So for android beginners here is a step by step guide to safely remove unwanted stuff.
Note
First, be sure you are not going to use emulators and will always do you development on a physical device. In case you are going to need emulators, note down the API Levels and type of emulators you'll need. Do not remove those. For the rest follow the below steps:
Steps to safely clear up unwanted stuff from Android SDK folder on the disk
- Open the Stand Alone Android SDK Manager. To open do one of the following:
.
- Uncheck all items ending with "System Image". Each API Level will have more than a few. In case you need some and have figured the list already leave them checked to avoid losing them and having to re-download.
.
- Optional (may help save a marginally more amount of disk space): To free up some more space, you can also entirely uncheck unrequired API levels. Be careful again to avoid re-downloading something you are actually using in other projects.
.
- In the end make sure you have at least the following (check image below) for the remaining API levels to be able to seamlessly work with your physical device.
In the end the clean android sdk installed components should look something like this in the SDK manager.
I had a similar issue, and for me the issue was due to some missing semicolons in the controller. The minification of the app was probably causing the code to execute incorrectly (most likely the resulting code was causing state mutations, which causes the view to render, and then the controller executes the code again, and so on recursively).
The easiest answer is number_format()
.
echo "$ ".number_format($value, 2);
If you want your application to be able to work with multiple currencies and locale-aware formatting (1.000,00
for some of us Europeans for example), it becomes a bit more complex.
There is money_format()
but it doesn't work on Windows and relies on setlocale()
, which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.
If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.
Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);
Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:
All non-alphanumeric characters other than
\
,-
,^
(at the start) and the terminating]
are non-special in character classes, but it does no harm if they are escaped.
For more info about Java regular expressions, see the docs.
Try using the os
module.
import os
os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'
# Open child processes via os.system(), popen() or fork() and execv()
someVariable = int(os.environ['DEBUSSY'])
See the Python docs on os.environ
. Also, for spawning child processes, see Python's subprocess docs.
It is Work for me:
language:{"infoEmpty": "No records available",}
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
You should use Linking
.
Example from the docs:
class OpenURLButton extends React.Component {
static propTypes = { url: React.PropTypes.string };
handleClick = () => {
Linking.canOpenURL(this.props.url).then(supported => {
if (supported) {
Linking.openURL(this.props.url);
} else {
console.log("Don't know how to open URI: " + this.props.url);
}
});
};
render() {
return (
<TouchableOpacity onPress={this.handleClick}>
{" "}
<View style={styles.button}>
{" "}<Text style={styles.text}>Open {this.props.url}</Text>{" "}
</View>
{" "}
</TouchableOpacity>
);
}
}
Here's an example you can try on Expo Snack:
import React, { Component } from 'react';
import { View, StyleSheet, Button, Linking } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Button title="Click me" onPress={ ()=>{ Linking.openURL('https://google.com')}} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
This worked for me
On the Zipped folder of the ADT you initially downloaded unzip and navigate to:
adt-bundle-windows-x86_64-20140702\eclipse\plugins
Copy all the executable jar files and paste them on the
C:\adt-bundle-windows-x86_64-20140702\adt-bundle-windows-x86_64-20140702\eclipse\plugins
directory (or wherever your adt is located).
Any executable jar files missing in the plugin folder will be added. You should be able to launch eclipse
"A series of data manipulation statements that must either fully complete or fully fail, leaving the database in a consistent state"
You can't initialize your testArray
field this way, because the application resources still aren't ready.
Just change the code to:
package com.xtensivearts.episode.seven;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class Episode7 extends ListActivity {
String[] mTestArray;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter that will contain all list items
ArrayAdapter<String> adapter;
mTestArray = getResources().getStringArray(R.array.testArray);
/* Assign the name array to that adapter and
also choose a simple layout for the list items */
adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
I have found the following script is very good at maintaining indexes, you can have this scheduled to run nightly or whatever other timeframe you wish.
i had a kind of similar problem. i tried to copy from a server to my desktop and always got the same message for the local path. the problem was, i already was logged in to my server per ssh, so it was searching for the local path in the server path.
solution: i had to log out and run the command again and it worked
You can also use the [Required]
data annotation attribute to solve this:
public class Foo
{
public string FooId { get; set; }
public Boo Boo { get; set; }
}
public class Boo
{
public string BooId { get; set; }
[Required]
public Foo Foo {get; set; }
}
Foo
is required for Boo
.
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.table {
background: #fff;
box-shadow: 0 0 0 10px #fff;
margin: 10px;
width: calc(100% - 20px);
}
What's dumpsys and what are its benefit
dumpsys is an android tool that runs on the device and dumps interesting information about the status of system services.
Obvious benefits:
What information can we retrieve from dumpsys shell command and how we can use it
If you run dumpsys you would see a ton of system information. But you can use only separate parts of this big dump.
to see all of the "subcommands" of dumpsys do:
dumpsys | grep "DUMP OF SERVICE"
Output:
DUMP OF SERVICE SurfaceFlinger:
DUMP OF SERVICE accessibility:
DUMP OF SERVICE account:
DUMP OF SERVICE activity:
DUMP OF SERVICE alarm:
DUMP OF SERVICE appwidget:
DUMP OF SERVICE audio:
DUMP OF SERVICE backup:
DUMP OF SERVICE battery:
DUMP OF SERVICE batteryinfo:
DUMP OF SERVICE clipboard:
DUMP OF SERVICE connectivity:
DUMP OF SERVICE content:
DUMP OF SERVICE cpuinfo:
DUMP OF SERVICE device_policy:
DUMP OF SERVICE devicestoragemonitor:
DUMP OF SERVICE diskstats:
DUMP OF SERVICE dropbox:
DUMP OF SERVICE entropy:
DUMP OF SERVICE hardware:
DUMP OF SERVICE input_method:
DUMP OF SERVICE iphonesubinfo:
DUMP OF SERVICE isms:
DUMP OF SERVICE location:
DUMP OF SERVICE media.audio_flinger:
DUMP OF SERVICE media.audio_policy:
DUMP OF SERVICE media.player:
DUMP OF SERVICE meminfo:
DUMP OF SERVICE mount:
DUMP OF SERVICE netstat:
DUMP OF SERVICE network_management:
DUMP OF SERVICE notification:
DUMP OF SERVICE package:
DUMP OF SERVICE permission:
DUMP OF SERVICE phone:
DUMP OF SERVICE power:
DUMP OF SERVICE reboot:
DUMP OF SERVICE screenshot:
DUMP OF SERVICE search:
DUMP OF SERVICE sensor:
DUMP OF SERVICE simphonebook:
DUMP OF SERVICE statusbar:
DUMP OF SERVICE telephony.registry:
DUMP OF SERVICE throttle:
DUMP OF SERVICE usagestats:
DUMP OF SERVICE vibrator:
DUMP OF SERVICE wallpaper:
DUMP OF SERVICE wifi:
DUMP OF SERVICE window:
Some Dumping examples and output
1) Getting all possible battery statistic:
$~ adb shell dumpsys battery
You will get output:
Current Battery Service state:
AC powered: false
AC capacity: 500000
USB powered: true
status: 5
health: 2
present: true
level: 100
scale: 100
voltage:4201
temperature: 271 <---------- Battery temperature! %)
technology: Li-poly <---------- Battery technology! %)
2)Getting wifi informations
~$ adb shell dumpsys wifi
Output:
Wi-Fi is enabled
Stay-awake conditions: 3
Internal state:
interface tiwlan0 runState=Running
SSID: XXXXXXX BSSID: xx:xx:xx:xx:xx:xx, MAC: xx:xx:xx:xx:xx:xx, Supplicant state: COMPLETED, RSSI: -60, Link speed: 54, Net ID: 2, security: 0, idStr: null
ipaddr 192.168.1.xxx gateway 192.168.x.x netmask 255.255.255.0 dns1 192.168.x.x dns2 8.8.8.8 DHCP server 192.168.x.x lease 604800 seconds
haveIpAddress=true, obtainingIpAddress=false, scanModeActive=false
lastSignalLevel=2, explicitlyDisabled=false
Latest scan results:
Locks acquired: 28 full, 0 scan
Locks released: 28 full, 0 scan
Locks held:
3) Getting CPU info
~$ adb shell dumpsys cpuinfo
Output:
Load: 0.08 / 0.4 / 0.64
CPU usage from 42816ms to 34683ms ago:
system_server: 1% = 1% user + 0% kernel / faults: 16 minor
kdebuglog.sh: 0% = 0% user + 0% kernel / faults: 160 minor
tiwlan_wq: 0% = 0% user + 0% kernel
usb_mass_storag: 0% = 0% user + 0% kernel
pvr_workqueue: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
TOTAL: 6% = 1% user + 3% kernel + 0% irq
4)Getting memory usage informations
~$ adb shell dumpsys meminfo 'your apps package name'
Output:
** MEMINFO in pid 5527 [com.sec.android.widgetapp.weatherclock] **
native dalvik other total
size: 2868 5767 N/A 8635
allocated: 2861 2891 N/A 5752
free: 6 2876 N/A 2882
(Pss): 532 80 2479 3091
(shared dirty): 932 2004 6060 8996
(priv dirty): 512 36 1872 2420
Objects
Views: 0 ViewRoots: 0
AppContexts: 0 Activities: 0
Assets: 3 AssetManagers: 3
Local Binders: 2 Proxy Binders: 8
Death Recipients: 0
OpenSSL Sockets: 0
SQL
heap: 0 MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
If you want see the info for all processes, use ~$ adb shell dumpsys meminfo
dumpsys is ultimately flexible and useful tool!
If you want to use this tool do not forget to add permission into your android manifest automatically android.permission.DUMP
Try to test all commands to learn more about dumpsys. Happy dumping!
DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS
SELECT * from {TableName}
Go
I want to indent a specific section of code in Visual Studio Code:
If you want to format a section (instead of indent it):
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
protected void Page_Load(object sender, EventArgs e)
{
// prevent user from making operation twice
btnSave.Attributes.Add("onclick",
"this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");
// ... etc.
}
right click on the "SRC folder", select "Mark directory as:, select "Resource Root".
Then Edit the run configuration. select Run, run, edit configuration, with the plus button add an application configuration, give it a name (could be any name), and in the main class write down the full name of the main java class for example, com.example.java.MaxValues.
you might also need to check file, project structure, project settings-project, give it a folder for the compiler output, preferably a separate folder, under the java folder,
I agree that Google's Gson
is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple
:
// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;
@Test
public void json2Object() {
// given
String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
+ "\"address\" : \"some address\","
+ "\"someobject\" : {\"field\" : \"value\"}}";
// when
JSONObject object = (JSONObject) JSONValue.parse(jsonString);
// then
@SuppressWarnings("unchecked")
Set<String> keySet = object.keySet();
for (String key : keySet) {
Object value = object.get(key);
System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
.getSimpleName());
}
assertThat(object.get("age").toString(), is("20"));
}
Pros and cons of Gson
and json-simple
is pretty much like pros and cons of user-defined Java Object and Map
. The object you define is clear for all fields (name and type), but less flexible than Map
.
Here's a very nice Gist that covers all the possible cases: https://gist.github.com/nepsilon/156387acf9e1e72d48fa35c4fabef0b4
Overview:
git rebase -i HEAD~X
# X is the number of commits to go back
# Move to the line of your commit, change pick into edit,
# then change your commit message:
git commit --amend
# Finish the rebase with:
git rebase --continue
This: "\0"
is a string, not a character. A character uses single quotes, like '\0'
.
@Url.Action("Survey", "Applications", new { applicationid = @Model.ApplicationID }, protocol: Request.Url.Scheme)
this error get if add decimal format. i just add
step="0.1"
I tried with and it works
use mysql; # use mysql table
update user set authentication_string="" where User='root';
flush privileges;
quit;
I always like to use Ansi escape characters:
echo -e "Enter your password: \x1B[8m"
echo -e "\x1B[0m"
8m
makes text invisible and 0m
resets text to "normal." The -e makes Ansi escapes possible.
The only caveat is that you can still copy and paste the text that is there, so you probably shouldn't use this if you really want security.
It just lets people not look at your passwords when you type them in. Just don't leave your computer on afterwards. :)
NOTE:
The above is platform independent as long as it supports Ansi escape sequences.
However, for another Unix solution, you could simply tell read
to not echo the characters...
printf "password: "
let pass $(read -s)
printf "\nhey everyone, the password the user just entered is $pass\n"
When the program that opened the port exits, the port will be closed automatically. If you kill the Java process running this server, that should do it.
As a side answer it's worth to note that:
aria-hidden
or aria-expanded
. But only if implemented and tested properly!I tried with this in the context field:
this.getActivity().getParent()
and it works fine for me. This was from a class which extends from "Fragment":
public class filtro extends Fragment{...
I was already using jquery. But I think its intuitive enough to just have:
var total_amount = 0;
$.each(traveler, function( i, v ) { total_amount += v.Amount ; });
This is basically just a short-hand version of @akhouri's answer.
you can also use the Readonly attribute: the input is not gonna be grayed but it won't be editable
<input type="text" name="lat" value="22.2222" readonly="readonly" />
I could be misinterpreting your question, but, yes, this is possible. The way that I would go about doing it is this:
var oElement = document.getElementById('elementId'); // get a reference to your element
oElement.onclick = clickHandler; // assign its click function a function reference
function clickHandler() {
// this function will be called whenever the element is clicked
// and can also be called from the context of other functions
}
Now, whenever this element is clicked, the code in clickHandler
will execute. Similarly, you can execute the same code by calling the function from within the context of other functions (or even assign clickHandler
to handle events triggered by other elements)>
I don't validate email address format anymore (Ok I check to make sure there is an at sign and a period after that). The reason for this is what says the correctly formatted address is even their email? You should be sending them an email and asking them to click a link or verify a code. This is the only real way to validate an email address is valid and that a person is actually able to recieve email.
Using Excel 2010 x64
. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:
Swap the data columns, to end with X_data in column A and Y_data in column B.
My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me:
an Excel XY plot literally wants {x,y}
pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away.
For me an XY plot means Y=f(X)
plotted.
This is not a direct answer to your question (which was answered pretty well already). However, having had times bite me on the fundament several times, I cannot stress enough that it would behoove you to look closely at what your time.struct_time object is providing, vs. what other time fields may have.
Assuming you have both a time.struct_time object, and some other date/time string, compare the two, and be sure you are not losing data and inadvertently creating a naive datetime object, when you can do otherwise.
For example, the excellent feedparser module will return a "published" field and may return a time.struct_time object in its "published_parsed" field:
time.struct_time(tm_year=2013, tm_mon=9, tm_mday=9, tm_hour=23, tm_min=57, tm_sec=42, tm_wday=0, tm_yday=252, tm_isdst=0)
Now note what you actually get with the "published" field.
Mon, 09 Sep 2013 19:57:42 -0400
By Stallman's Beard! Timezone information!
In this case, the lazy man might want to use the excellent dateutil module to keep the timezone information:
from dateutil import parser
dt = parser.parse(entry["published"])
print "published", entry["published"])
print "dt", dt
print "utcoffset", dt.utcoffset()
print "tzinfo", dt.tzinfo
print "dst", dt.dst()
which gives us:
published Mon, 09 Sep 2013 19:57:42 -0400
dt 2013-09-09 19:57:42-04:00
utcoffset -1 day, 20:00:00
tzinfo tzoffset(None, -14400)
dst 0:00:00
One could then use the timezone-aware datetime object to normalize all time to UTC or whatever you think is awesome.
I would personally use a complete editing package such as:
Then I would install "MikTeX" as the compiling package, which allows you to generate a PDF from your document, using the pdfLaTeX
compiler.
That's another solution (Spring Security 3):
public String getLoggedUser() throws Exception {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
return (!name.equals("anonymousUser")) ? name : null;
}
If Your Window pc, you may try this, it's also for STS:
Ctrl + win + Alt + Down :: Copy current line or selected line to below
Ctrl + win + Alt + Up :: Copy current line or selected line to above
glob.glob
or os.listdir
will do it.
After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.
Long story short, the creator of YAML are saying .yaml
, but personally I keep doing .yml
. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml
everywhere. I've been writing docker-compose.yml
files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml
...
So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
An array that contains a property that equals to
yourArray.contains(where: {$0.propertyToCheck == value })
Returns boolean.
one
has not been assigned so points to an unpredictable location. You should either place it on the stack:
Vector one;
one.a = 12;
one.b = 13;
one.c = -11
or dynamically allocate memory for it:
Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);
Note the use of free
in this case. In general, you'll need exactly one call to free
for each call made to malloc
.
One more way to check existence of an element in a List
var result = myList.Exists(users => users.Equals("Vijai"))
I tried entering a new line character using an excel Sheet. I entered my data by writing "abc" below a blank cell in Excel and then updated my db using the empty cell above the cell containing "abc" and the cell with data. I copy pasted both the cells in my SSMS. It worked for me
I had the same problem;
textStatus = 'error'
errorThrown = (empty)
xhr.status = 0
That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)
I have tried calling it this way also:
var request = $.ajax({
url: "http://crossdomain.url.net/somefile.php", dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
but without success.
This post solved it for me: jQuery AJAX cross domain
I would go with the traditional find & xargs way:
find ~/Linux/Old -maxdepth 1 -mindepth 1 -not -name Tux.png -print0 |
xargs -0 mv -t ~/Linux/New
-maxdepth 1
makes it not search recursively. If you only care about files, you can say -type f
. -mindepth 1
makes it not include the ~/Linux/Old
path itself into the result. Works with any filenames, including with those that contain embedded newlines.
One comment notes that the mv -t
option is a probably GNU extension. For systems that don't have it
find ~/Linux/Old -maxdepth 1 -mindepth 1 -not -name Tux.png \
-exec mv '{}' ~/Linux/New \;
Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.
In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0
They are certainly not equivalent!
Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
I was having problems with this, maintaining the UK dd/mm/yyyy format, I initially used the answer from adeneo https://stackoverflow.com/a/18021130/243905 but that didnt work in safari for me so changed to this, which as far as I can tell works all over - using the jquery-ui datepicker, jquery validation.
if ($('[type="date"]').prop('type') !== 'date') {
//for reloading/displaying the ISO format back into input again
var val = $('[type="date"]').each(function () {
var val = $(this).val();
if (val !== undefined && val.indexOf('-') > 0) {
var arr = val.split('-');
$(this).val(arr[2] + '/' + arr[1] + '/' + arr[0]);
}
});
//add in the datepicker
$('[type="date"]').datepicker(datapickeroptions);
//stops the invalid date when validated in safari
jQuery.validator.methods["date"] = function (value, element) {
var shortDateFormat = "dd/mm/yy";
var res = true;
try {
$.datepicker.parseDate(shortDateFormat, value);
} catch (error) {
res = false;
}
return res;
}
}
add cv2.waitKey(0)
in the end.
To disable mouse scroll wheel zoom on embedded Google Maps, you just need to set the css property pointer-events of the iframe to none:
<style>
#googlemap iframe {
pointer-events:none;
}
</style>
Thats All.. Pretty neat huh?
<div id="googlemap">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3648.6714814904954!2d90.40069809681577!3d23.865796688563787!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3755c425897f1f09%3A0x2bdfa71343f07395!2sArcadia+Green+Point%2C+Rd+No.+16%2C+Dhaka+1230%2C+Bangladesh!5e0!3m2!1sen!2sin!4v1442184916780" width="400" height="300" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
If you are doing it with your application itself... I hope this code helps.
In href -- you have to add download_file.php along with your URL:
<a class="download" href="'/download_file.php?fileSource='+http://www.google.com/logo_small.png" target="_blank" title="YourTitle">
/* Here is the Download.php file to force download stuff */
<?php
$fullPath = $_GET['fileSource'];
if($fullPath) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment; filename=\"" . $path_parts["basename"]."\""); // Use 'attachment' to force a download
header("Content-type: application/pdf"); // Add here more headers for diff. extensions
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"" . $path_parts["basename"]."\"");
}
if($fsize) { // Checking if file size exist
header("Content-length: $fsize");
}
readfile($fullPath);
exit;
}
?>
I'm not sure what you're trying to do: If you added the file via
svn add myfile
you only told svn to put this file into your repository when you do your next commit. There's no change to the repository before you type an
svn commit
If you delete the file before the commit, svn
has it in its records (because you added it) but cannot send it to the repository because the file no longer exist.
So either you want to save the file in the repository and then delete it from your working copy: In this case try to get your file back (from the trash?), do the commit and delete the file afterwards via
svn delete myfile
svn commit
If you want to undo the add
and just throw the file away, you can to an
svn revert myfile
which tells svn
(in this case) to undo the add-Operation.
EDIT
Sorry, I wasn't aware that you're using the "Versions" GUI client for Max OSX. So either try a revert on the containing directory using the GUI or jump into the cold water and fire up your hidden Mac command shell :-) (it's called "Terminal" in the german OSX, no idea how to bring it up in the english version...)
I'm sorry to disagree, but according to the rules for parsing a legacy color value posted by @Yuhong Bao, chucknorris
DOES NOT equate to #CC0000
, but rather to #C00000
, a very similar but slightly different hue of red. I used the Firefox ColorZilla add-on to verify this.
The rules state:
chucknorris0
chuc knor ris0
ch kn ri
C0 00 00
I was able to use these rules to correctly interpret the following strings:
LuckyCharms
Luck
LuckBeALady
LuckBeALadyTonight
GangnamStyle
UPDATE: The original answerers who said the color was #CC0000
have since edited their answers to include the correction.
According to the TextView docs, the programmatic version of android:password is setTransformationMethod(), not setInputType(). So something like:
mEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
should do the trick.
Here's a better way of doing things:
import java.util.ArrayList;
import java.util.Random;
public class facultyquotes
{
private ArrayList<String> quotes;
private String quote1;
private String quote2;
private String quote3;
private String quote4;
private String quote5;
private String quote6;
private String quote7;
private String quote8;
private String quote9;
private String quote10;
private String quote11;
private String quote12;
private String quote13;
private String quote14;
private String quote15;
private String quote16;
private String quote17;
private String quote18;
private String quote19;
private String quote20;
private String quote21;
private String quote22;
private String quote23;
private String quote24;
private String quote25;
private String quote26;
private String quote27;
private String quote28;
private String quote29;
private String quote30;
private int n;
Random random;
String teacher;
facultyquotes()
{
quotes=new ArrayList<>();
random=new Random();
n=random.nextInt(3) + 0;
quote1="life is hard";
quote2="trouble shall come to an end";
quote3="never give lose and never get lose";
quote4="gamble with the devil and win";
quote5="If you don’t build your dream, someone else will hire you to help them build theirs.";
quote6="The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself.";
quote7="When I dare to be powerful – to use my strength in the service of my vision, then it becomes less and less important whether I am afraid.";
quote8="Whenever you find yourself on the side of the majority, it is time to pause and reflect";
quote9="Great minds discuss ideas; average minds discuss events; small minds discuss people.";
quote10="I have not failed. I’ve just found 10,000 ways that won’t work.";
quote11="If you don’t value your time, neither will others. Stop giving away your time and talents. Value what you know & start charging for it.";
quote12="A successful man is one who can lay a firm foundation with the bricks others have thrown at him.";
quote13="No one can make you feel inferior without your consent.";
quote14="Let him who would enjoy a good future waste none of his present.";
quote15="Live as if you were to die tomorrow. Learn as if you were to live forever.";
quote16="Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do.";
quote17="The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will.";
quote18="Success is about creating benefit for all and enjoying the process. If you focus on this & adopt this definition, success is yours.";
quote19="I used to want the words ‘She tried’ on my tombstone. Now I want ‘She did it.";
quote20="It is our choices, that show what we truly are, far more than our abilities.";
quote21="You have to learn the rules of the game. And then you have to play better than anyone else.";
quote22="The successful warrior is the average man, with laser-like focus.";
quote23="Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.";
quote24="If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much.";
quote25="The question isn’t who is going to let me; it’s who is going to stop me.";
quote26="If you genuinely want something, don’t wait for it – teach yourself to be impatient.";
quote27="Don’t let the fear of losing be greater than the excitement of winning.";
quote28="But man is not made for defeat. A man can be destroyed but not defeated.";
quote29="There is nothing permanent except change.";
quote30="You cannot shake hands with a clenched fist.";
quotes.add(quote1);
quotes.add(quote2);
quotes.add(quote3);
quotes.add(quote4);
quotes.add(quote5);
quotes.add(quote6);
quotes.add(quote7);
quotes.add(quote8);
quotes.add(quote9);
quotes.add(quote10);
quotes.add(quote11);
quotes.add(quote12);
quotes.add(quote13);
quotes.add(quote14);
quotes.add(quote15);
quotes.add(quote16);
quotes.add(quote17);
quotes.add(quote18);
quotes.add(quote19);
quotes.add(quote20);
quotes.add(quote21);
quotes.add(quote22);
quotes.add(quote23);
quotes.add(quote24);
quotes.add(quote25);
quotes.add(quote26);
quotes.add(quote27);
quotes.add(quote28);
quotes.add(quote29);
quotes.add(quote30);
}
public void setTeacherandQuote(String teacher)
{
this.teacher=teacher;
}
public void printRandomQuotes()
{
System.out.println(quotes.get(n++)+" ~ "+ teacher);
}
public void printAllQuotes()
{
for (String i : quotes)
{
System.out.println(i.toString());
}
}
}
As a conceptual example for understanding when you ought to use yield
, let's say the method ConsumeLoop()
processes the items returned/yielded by ProduceList()
:
void ConsumeLoop() {
foreach (Consumable item in ProduceList()) // might have to wait here
item.Consume();
}
IEnumerable<Consumable> ProduceList() {
while (KeepProducing())
yield return ProduceExpensiveConsumable(); // expensive
}
Without yield
, the call to ProduceList()
might take a long time because you have to complete the list before returning:
//pseudo-assembly
Produce consumable[0] // expensive operation, e.g. disk I/O
Produce consumable[1] // waiting...
Produce consumable[2] // waiting...
Produce consumable[3] // completed the consumable list
Consume consumable[0] // start consuming
Consume consumable[1]
Consume consumable[2]
Consume consumable[3]
Using yield
, it becomes rearranged, sort of interleaved:
//pseudo-assembly
Produce consumable[0]
Consume consumable[0] // immediately yield & Consume
Produce consumable[1] // ConsumeLoop iterates, requesting next item
Consume consumable[1] // consume next
Produce consumable[2]
Consume consumable[2] // consume next
Produce consumable[3]
Consume consumable[3] // consume next
And lastly, as many before have already suggested, you should use Version 2 because you already have the completed list anyway.
A POJO is just a plain, old Java Bean with the restrictions removed. Java Beans must meet the following requirements:
POJO does not mandate any of these. It's just what the name says: an object that compiles under JDK can be considered a Plain Old Java Object. No app server, no base classes, no interfaces required to use.
The acronym POJO was a reaction against EJB 2.0, which required several interfaces, extended base classes, and lots of methods just to do simple things. Some people, Rod Johnson and Martin Fowler among them, rebelled against the complexity and sought a way to implement enterprise scale solutions without having to write EJBs.
Martin Fowler coined a new acronym.
Rod Johnson wrote "J2EE Without EJBs", wrote Spring, influenced EJB enough so version 3.1 looks a great deal like Spring and Hibernate, and got a sweet IPO from VMWare out of it.
Here's an example that you can wrap your head around:
public class MyFirstPojo
{
private String name;
public static void main(String [] args)
{
for (String arg : args)
{
MyFirstPojo pojo = new MyFirstPojo(arg); // Here's how you create a POJO
System.out.println(pojo);
}
}
public MyFirstPojo(String name)
{
this.name = name;
}
public String getName() { return this.name; }
public String toString() { return this.name; }
}
if (AllocConsole() == 0)
{
// Handle error here. Use ::GetLastError() to get the error.
}
// Redirect CRT standard input, output and error handles to the console window.
FILE * pNewStdout = nullptr;
FILE * pNewStderr = nullptr;
FILE * pNewStdin = nullptr;
::freopen_s(&pNewStdout, "CONOUT$", "w", stdout);
::freopen_s(&pNewStderr, "CONOUT$", "w", stderr);
::freopen_s(&pNewStdin, "CONIN$", "r", stdin);
// Clear the error state for all of the C++ standard streams. Attempting to accessing the streams before they refer
// to a valid target causes the stream to enter an error state. Clearing the error state will fix this problem,
// which seems to occur in newer version of Visual Studio even when the console has not been read from or written
// to yet.
std::cout.clear();
std::cerr.clear();
std::cin.clear();
std::wcout.clear();
std::wcerr.clear();
std::wcin.clear();
In my case it was failing as the IP of my source server was not whitelisted in the target server.
For e.g. I was trying to access https://prodcat.ref.test.co.uk from application running on my source server. On source server find IP by ifconfig
This IP should be whitelisted in the target Server's apache config file. If its not then get it whitelist.
Steps to add a IP for whitelisting (if you control the target server as well) ssh to the apache server sudo su - cd /usr/local/apache/conf/extra (actual directories can be different based on your config)
Find the config file for the target application for e.g. prodcat-443.conf
RewriteCond %{REMOTE_ADDR} <YOUR Server's IP>
for e.g.
RewriteCond %{REMOTE_ADDR} !^192\.68\.2\.98
Hope this helps someone
/// <summary>
/// Returns a string With count chars Left or Right value
/// </summary>
/// <param name="val"></param>
/// <param name="count"></param>
/// <param name="space"></param>
/// <param name="right"></param>
/// <returns></returns>
public static string Formating(object val, int count, char space = ' ', bool right = false)
{
var value = val.ToString();
for (int i = 0; i < count - value.Length; i++) value = right ? value + space : space + value;
return value;
}
In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.
For an example ->orderBy('a.fist_name ASC, a.last_name ASC')
will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.
To add multiple order by's you need to use 'add' function. And it will be like this.
->add('orderBy','first_name ASC, last_name ASC')
. This will give you the correctly formatted SQL.
More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api
Hope this helps. Cheers!
$ git help repository-layout
A Git repository comes in two different flavours:
- a .git directory at the root of the working tree;
- a .git directory that is a bare repository (i.e. without its own working tree), that is typically used for exchanging histories with others by pushing into it and fetching from it.
Give your parent div position: relative
, then give your child div position: absolute
, this will absolute position the div inside of its parent, then you can give the child bottom: 0px;
See example here:
It would be best to just have the http content on https
if any(t < 0 for t in x):
# do something
Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:
if True in (t < 0 for t in x):
Just in case someone's made the same stupid mistake I did; check that you're not overwriting the activity content somewhere (i.e. look for additional calls to setContentView)
In my case, due to careless copy and pasting, I used DataBindingUtil.setContentView in my fragment, instead of DataBindingUtil.inflate, which messed up the state of the activity.
Associative array in PHP actually considered as a dictionary.
An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.
This iterator form is 10-15% faster than using integer indexing:
# python2 only
if str is bytes:
from itertools import izip as zip
def is_sorted(l):
return all(a <= b for a, b in zip(l, l[1:]))
UPDATED FOR XCODE 9
Connect any iOS device to your Mac (yes a physical one, yes I know this is stupid)
Click your device on the left and VIEW DEVICE LOGS on the right
Wait. It might take a minute to show up. Maybe doing Command-A
then Delete
will speed this up.
Critical undocumented step: rename the crash report that you got from iTunesConnect from .txt
extension to .crash
extension
And then Xcode will symbolicate the crash report and display the results.
Source: https://developer.apple.com/library/ios/technotes/tn2151/_index.html
Recursively:
find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(@"%d", i);
}
On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.
for (NSString* currentString in myArrayOfStrings)
{
NSLog(@"%@", currentString);
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [myArrayOfStrings count]; i++)
{
NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}
The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.
Hope this helps.
As Bakkal explained, for the keyboard shortcuts, in netbeans
you can go to tools->options->editor->code templates and add or edit your own shortcuts.
In Eclipse
it's on templates.
Most of the above mentioned solution didn't worked for me. However, below given solution works just fine:
<div class="fixed-bottom">...</div>
right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.
This is the best answer to solve the problem
In python3, there is a bytes()
method that is in the same format as encode()
.
str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True
I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode
and decode
, and without having to prefex b
in front of quotes.