Sometimes if you only needs the values to be enumerated, use the dictionary's value collection:
foreach(var value in dictionary.Values)
{
// do something with entry.Value only
}
Reported by this post which states it is the fastest method: http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html
When I got an error saying "archive for required library could not be read," I solved it by removing the JARS in question from the Build Path of the project, and then using "Add External Jars" to add them back in again (navigating to the same folder that they were in). Using the "Add Jars" button wouldn't work, and the error would still be there. But using "Add External Jars" worked.
If you go to C:\Windows\system32\Windowspowershell\v1.0
(and C:\Windows\syswow64\Windowspowershell\v1.0
on x64 machines) in Windows Explorer and double-click powershell.exe
you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe
can be set independently from the default properties.
To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.
Running start powershell
from cmd.exe should start a new console with your default settings.
There's another, simpler way to do this:
npm install Node@8
(saves Node 8 as dependency in package.json)This works because node
is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.
See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360
Dump all custom variables:
<h1>Variables passed to the view:</h1>
{% for key, value in _context %}
{% if key starts with '_' %}
{% else %}
<pre style="background: #eee">{{ key }}</pre>
{{ dump(value) }}
{% endif %}
{% endfor %}
You can use my plugin which will do that for you (an will nicely format the output):
Since 1.4 this is now possible with the *
operator. When given two objects, it will merge them recursively. For example,
jq -s '.[0] * .[1]' file1 file2
Important: Note the -s (--slurp)
flag, which puts files in the same array.
Would get you:
{
"value1": 200,
"timestamp": 1382461861,
"value": {
"aaa": {
"value1": "v1",
"value2": "v2",
"value3": "v3",
"value4": 4
},
"bbb": {
"value1": "v1",
"value2": "v2",
"value3": "v3"
},
"ccc": {
"value1": "v1",
"value2": "v2"
},
"ddd": {
"value3": "v3",
"value4": 4
}
},
"status": 200
}
If you also want to get rid of the other keys (like your expected result), one way to do it is this:
jq -s '.[0] * .[1] | {value: .value}' file1 file2
Or the presumably somewhat more efficient (because it doesn't merge any other values):
jq -s '.[0].value * .[1].value | {value: .}' file1 file2
I posted something similar here
From Joachim's answer, from Dianne Hackborn:
http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42
I ended up just using:
FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
But could equally have used something like:
((AppCompatActivity)getContext()).getSupportFragmentManager().popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)
Which will pop all states up to the named one. You can then just replace the fragment with what you want
One like with events
(keydown)="$event.keyCode != 32 ? $event:$event.preventDefault()"
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)To do POST you'll need to have a form.
<form action="employee.action" method="post">
<input type="submit" value="Employee1" />
</form>
There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.
Some tricks: Make a link use POST instead of GET and How do you post data with a link
Edit: to load response on a frame you can target your form to your frame:
<form action="employee.action" method="post" target="myFrame">
var data = $('<div>').html('[{"Id":1,"Name":"Name}]')[0].textContent;
that should parse all the encoded values you need.
The &
character is itself an escape character in XML so the solution is to concatenate it and a Unicode decimal equivalent for &
thus ensuring that there are no XML parsing errors. That is, replace the character &
with &
.
After reading this post, I have implemented my own horizontal ListView
. You can find it here: http://dev-smart.com/horizontal-listview/ Let me know if this helps.
If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.
Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.
This is the same question as Failed to connect to mailserver at "localhost" port 25
also check this php mail function not working
When flex is a positive number, it makes the component flexible and it will be sized proportional to its flex value. So a component with flex set to 2 will take twice the space as a component with flex set to 1.
<View style={{flex: 1}>_x000D_
_x000D_
<ScrollView>_x000D_
//your scroll able content will be placed above your fixed footer content. _x000D_
//when your content will grow bigger and bigger it will hide behind _x000D_
//footer content. _x000D_
</ScrollView>_x000D_
_x000D_
<View style={styles.footerContainer}>_x000D_
//your fixed footer content will sit fixed below your screen _x000D_
</View>_x000D_
_x000D_
</View>
_x000D_
Just set the property directly: .
eleman.disabled = false;
Asymptotic notation is something you can understand as: how do functions compare when zooming out? (A good way to test this is simply to use a tool like Desmos and play with your mouse wheel). In particular:
f(n) ? o(n)
means: at some point, the more you zoom out, the more f(n)
will be dominated by n
(it will progressively diverge from it).g(n) ? T(n)
means: at some point, zooming out will not change how g(n)
compare to n
(if we remove ticks from the axis you couldn't tell the zoom level).Finally h(n) ? O(n)
means that function h
can be in either of these two categories. It can either look a lot like n
or it could be smaller and smaller than n
when n
increases. Basically, both f(n)
and g(n)
are also in O(n)
.
In computer science, people will usually prove that a given algorithm admits both an upper O
and a lower bound . When both bounds meet that means that we found an asymptotically optimal algorithm to solve that particular problem.
For example, if we prove that the complexity of an algorithm is both in O(n)
and (n)
it implies that its complexity is in T(n)
. That's the definition of T
and it more or less translates to "asymptotically equal". Which also means that no algorithm can solve the given problem in o(n)
. Again, roughly saying "this problem can't be solved in less than n
steps".
An upper bound of O(n)
simply means that even in the worse case, the algorithm will terminate in at most n
steps (ignoring all constant factors, both multiplicative and additive). A lower bound of (n)
means on the opposite that we built some examples where the problem solved by this algorithm couldn't be solved in less than n
steps (again ignoring multiplicative and additive constants). The number of steps is at most n
and at least n
so this problem complexity is "exactly n
". Instead of saying "ignoring constant multiplicative/additive factor" every time we just write T(n)
for short.
onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:
<input
type = "text"
onchange = "myHandler();"
onkeypress = "this.onchange();"
onpaste = "this.onchange();"
oninput = "this.onchange();"
/>
Form the Inheritance concept, If some perticular method is not available in the current class it will search for that method in super classes. If available it executes.
It executes
AbstractList<E>
classadd()
method which throwsUnsupportedOperationException
.
When you are converting from an Array to a Collection Obejct. i.e., array-based to collection-based API then it is going to provide you fixed-size collection object, because Array's behaviour is of Fixed size.
java.util.Arrays.asList( T... a )
Souce samples for conformation.
public class Arrays {
public static <T> List<T> asList(T... a) {
return new java.util.Arrays.ArrayList.ArrayList<>(a); // Arrays Inner Class ArrayList
}
//...
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable {
//...
}
}
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
//...
}
public ListIterator<E> listIterator() {
return listIterator(0);
}
private class ListItr extends Itr implements ListIterator<E> {
//...
}
}
Form the above Source you may observe that java.util.Arrays.ArrayList
class doesn't @Override add(index, element), set(index, element), remove(index)
. So, From inheritance it executes super AbstractList<E>
class add()
function which throws UnsupportedOperationException
.
As AbstractList<E>
is an abstract class it provides the implementation to iterator() and listIterator()
. So, that we can iterate over the list object.
List<String> list_of_Arrays = Arrays.asList(new String[] { "a", "b" ,"c"});
try {
list_of_Arrays.add("Yashwanth.M");
} catch(java.lang.UnsupportedOperationException e) {
System.out.println("List Interface executes AbstractList add() fucntion which throws UnsupportedOperationException.");
}
System.out.println("Arrays ? List : " + list_of_Arrays);
Iterator<String> iterator = list_of_Arrays.iterator();
while (iterator.hasNext()) System.out.println("Iteration : " + iterator.next() );
ListIterator<String> listIterator = list_of_Arrays.listIterator();
while (listIterator.hasNext()) System.out.println("Forward iteration : " + listIterator.next() );
while(listIterator.hasPrevious()) System.out.println("Backward iteration : " + listIterator.previous());
You can even create Fixed-Size array form Collections class Collections.unmodifiableList(list);
Sample Source:
public class Collections {
public static <T> List<T> unmodifiableList(List<? extends T> list) {
return (list instanceof RandomAccess ?
new UnmodifiableRandomAccessList<>(list) :
new UnmodifiableList<>(list));
}
}
A Collection
— sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
@see also
Since you're using PHP, you will probably need to use the CURLOPT_PORT
option, like so:
curl_setopt($ch, CURLOPT_PORT, 11740);
Bear in mind, you may face problems with SELinux:
There are 2 differences:
2 methods creating a user and granting some privileges to him
create user userName identified by password;
grant connect to userName;
and
grant connect to userName identified by password;
do exactly the same. It creates a user and grants him the connect role.
different outcome
resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.
To grant a user all privileges run you first snippet or
grant all privileges to userName identified by password;
This works for me:
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
update: function (event, ui) {
var start_pos = ui.item.data('start_pos');
var end_pos = ui.item.index();
//$('#sortable li').removeClass('highlights');
}
Late to party but come with solution. You can use "&" to defines styles for hover nth Child etc:
day: {
display: "flex",
flex: "1",
justifyContent: "center",
alignItems: "center",
width: "50px",
height: "50px",
transition: "all 0.2s",
borderLeft: "solid 1px #cccccc",
"&:hover": {
background: "#efefef"
},
"&:last-child": {
borderRight: "solid 1px #cccccc"
}
},
Alternatively
with Pool() as pool:
pool.map(fits.open, [name + '.fits' for name in datainput])
- file:
path: /etc/some_directory
state: directory
mode: 0755
owner: someone
group: somegroup
That's the way you can actually also set the permissions, the owner and the group. The last three parameters are not obligatory.
When converting an excel file to CSV the date/time cell looks like this:
foo, 3/16/2016 10:38, bar,
To convert the datetime text value to datetime python object do this:
from datetime import datetime
date_object = datetime.strptime('3/16/2016 10:38', '%m/%d/%Y %H:%M') # excel format (CSV file)
print date_object will return 2005-06-01 13:33:00
I have written down the steps:
? Add gem 'newrelic_rpm' to your Gemfile under staging & production
? bundle install
? Login to heroku control panel and add newrelic addon
? Once added, setup automatic pinging to your website so that it does not idle
? Browse to Menu > Availability Monitoring (under Settings)
? Click “Turn on Availability Monitoring”
? Enter the url to ping (eg: http://spokenvote.org)
? Select 1 minute for the interval
I feel your pain and I wasted all night/morning trying to figure this out. With sheer brute force I figured out a solution. Call it a workaround - but it's simple.
Add the CssClass property to your Menu Control's declaration like so:
<asp:Menu ID="NavigationMenu" DataSourceID="NavigationSiteMapDataSource"
CssClass="SomeMenuClass"
StaticMenuStyle-CssClass="StaticMenuStyle"
StaticMenuItemStyle-CssClass="StaticMenuItemStyle"
Orientation="Horizontal"
MaximumDynamicDisplayLevels="0"
runat="server">
</asp:Menu>
Just rip out the StaticSelectedStyle-CssClass and StaticHoverStyle-CssClass attributes as they simply don't do jack.
Now create the "SomeMenuClass", doesn't matter what you put in it. It should look something like this:
.SomeMenuClass
{
color:Green;
}
Next add the following two CSS Classes:
For "Hover" Styling add:
.SomeMenuClass a.static.highlighted
{
color:Red !important;
}
For "Selected" Styling add:
.SomeMenuClass a.static.selected
{
color:Blue !important;
}
There, that's it. You're done. Hope this saves some of you the frustration I went through. BTW: You mentioned:
I seem to be the first one to ever report on what seems to be a bug.
You also seemed to think it was a new .NET 4.0 bug. I found this: http://www.velocityreviews.com/forums/t649530-problem-with-staticselectedstyle-and-statichoverstyle.html posted back in 2008 regarding Asp.Net 2.0 . How are we the only 3 people on the planet complaining about this?
How I found the workaround (study the HTML output):
Here is the HTML output when I set StaticHoverStyle-BackColor="Red":
#NavigationMenu a.static.highlighted
{
background-color:Red;
}
This is the HTML output when setting StaticSelectedStyle-BackColor="Blue":
#NavigationMenu a.static.selected
{
background-color:Blue;
text-decoration:none;
}
Therefore, the logical way to override this markup was to create classes for SomeMenuClass a.static.highlighted and SomeMenuClass a.static.selected
Special Notes:
You MUST also use "!important" on ALL the settings in these classes because the HTML output uses "#NavigationMenu", and that means any styles Asp.Net decides to throw in there for you will have inheritance priority over any other styles for the Menu Control with the ID "NavigationMenu". One thing I struggled with was padding, till I figured out Asp.Net was using "#NavigationMenu" to set the left and right padding to 15em. I tacked on "!important" to my SomeMenuClass styles and it worked.
If you have PHP set up on the server, you can use mysql2csv to export an (actually valid) CSV file for an abitrary mysql query. See my answer at MySQL - SELECT * INTO OUTFILE LOCAL ? for a little more context/info.
I tried to maintain the option names from mysql
so it should be sufficient to provide the --file
and --query
options:
./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"
"Install" mysql2csv
via
wget https://gist.githubusercontent.com/paslandau/37bf787eab1b84fc7ae679d1823cf401/raw/29a48bb0a43f6750858e1ddec054d3552f3cbc45/mysql2csv -O mysql2csv -q && (sha256sum mysql2csv | cmp <(echo "b109535b29733bd596ecc8608e008732e617e97906f119c66dd7cf6ab2865a65 mysql2csv") || (echo "ERROR comparing hash, Found:" ;sha256sum mysql2csv) ) && chmod +x mysql2csv
(download content of the gist, check checksum and make it executable).
Try this
$("#abc").html('<span class = "xyz"> SAMPLE TEXT</span>');
Handle all the css relevant to that span within xyz
Your code is correct. Kindly mark small correction.
#rightcolumn {
width: 750px;
background-color: #777;
display: block;
**float: left;(wrong)**
**float: right; (corrected)**
border: 1px solid white;
}
My controller
public function delete_category() //Created a controller class //
{
$this->load->model('Managecat'); //Load model Managecat here
$id=$this->input->get('id'); // get the requested in a variable
$sql_del=$this->Managecat->deleteRecord($id); //send the parameter $id in Managecat there I have created a function name deleteRecord
if($sql_del){
$data['success'] = "Category Have been deleted Successfully!!"; //success message goes here
}
}
My Model
public function deleteRecord($id) {
$this->db->where('cat_id', $id);
$del=$this->db->delete('category');
return $del;
}
if you have enum like this
public enum PcapLinkType {
DLT_NULL(0)
DLT_EN10MB(1)
DLT_EN3MB(2),
DLT_AX25(3),
DLT_UNKNOWN(-1);
private final int value;
PcapLinkType(int value) {
this.value= value;
}
}
then you can use it like
PcapLinkType type = PcapLinkType.values()[1]; /*convert val to a PcapLinkType */
foreach (var data in dynObj.quizlist)
{
foreach (var data1 in data.QUIZ.QPROP)
{
Response.Write("Name" + ":" + data1.name + "<br>");
Response.Write("Intro" + ":" + data1.intro + "<br>");
Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");
Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");
Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");
Response.Write("Noofques" + ":" + data1.noofques + "<br>");
foreach (var queprop in data1.QUESTION.QUEPROP)
{
Response.Write("Questiontext" + ":" + queprop.questiontext + "<br>");
Response.Write("Mark" + ":" + queprop.mark + "<br>");
}
}
}
document.getElementsByClassName('drill_cursor')[0]
.addEventListener('click', function (event) {
// do something
});
$(".drill_cursor").click(function(){
//do something
});
You can use the available()
method to ask the stream whether there is any data available at the moment you call it. However, that function isn't guaranteed to work on all types of input streams. That means that you can't use available()
to determine whether a call to read()
will actually block or not.
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
In a case
statement, a ,
is the equivalent of ||
in an if
statement.
case car
when 'toyota', 'lexus'
# code
end
Having html collection of selects you can check if every select has option with specific value and filter those which don't match condition:
//get select collection:
let selects = $('select')
//reduce if select hasn't at least one option with value 1
.filter(function () { return [...this.children].some(el => el.value == 1) });
As of API version 3.26.10, you can set the marker label with more than one characters. The restriction is lifted.
Try it, it works!
Moreover, using a MarkerLabel object instead of just a string, you can set a number of properties for the appearance, and if using a custom Icon you can set the labelOrigin property to reposition the label.
Source: https://code.google.com/p/gmaps-api-issues/issues/detail?id=8578#c30 (also, you can report any issues regarding this at the above linked thread)
Your confusion stems from the fact that declared properties are not (necessarily named the same as) (instance) variables.
The expresion
indexPath.row
is equivalent to
[indexPath row]
and the assignment
delegate.myData = [myData objectAtIndex:indexPath.row];
is equivalent to
[delegate setMyData:[myData objectAtIndex:[indexPath row]]];
assuming standard naming for synthesised properties.
Furthermore, delegate
is probably declared as being of type id<SomeProtocol>
, i.e., the compiler hasn’t been able to provide actual type information for delegate
at that point, and the debugger is relying on information provided at compile-time. Since id
is a generic type, there’s no compile-time information about the instance variables in delegate
.
Those are the reasons why you don’t see myData
or row
as variables.
If you want to inspect the result of sending -row
or -myData
, you can use commands p
or po
:
p (NSInteger)[indexPath row]
po [delegate myData]
or use the expressions window (for instance, if you know your delegate
is of actual type MyClass *
, you can add an expression (MyClass *)delegate
, or right-click delegate
, choose View Value as…
and type the actual type of delegate
(e.g. MyClass *
).
That being said, I agree that the debugger could be more helpful:
There could be an option to tell the debugger window to use run-time type information instead of compile-time information. It'd slow down the debugger, granted, but would provide useful information;
Declared properties could be shown up in a group called properties and allow for (optional) inspection directly in the debugger window. This would also slow down the debugger because of the need to send a message/execute a method in order to get information, but would provide useful information, too.
If this doesn't work it may be overridden by your current settings. You can right-click in the bar to the left of the code where line numbers would normally appear and turn them on with the context menu.
Here's a simple script:
#!/bin/bash
args=("$@")
echo Number of arguments: $#
echo 1st argument: ${args[0]}
echo 2nd argument: ${args[1]}
$#
is the number of arguments received by the script. I find easier to access them using an array: the args=("$@")
line puts all the arguments in the args
array. To access them use ${args[index]}
.
In my case, it turned out to be a simple case of spacing.
Turns out, i had a space inserted after the last ; and before ""C:\Program Files\MySQL\MySQL Server 5.7" For this very simple reason, no matter what i did, MySql was still not being recognized.
Once i eliminated the spaces before and after path, it worked perfectly.
In retrospect, seems like a very obvious answer, but nobody's mentioned it anywhere.
Also, i'm new to this whole windows thing, so please excuse me if it sounds very simple.
do it like this:
"abc%s" % 9
#or
"abc" + str(9)
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
You might want to check the GC.GetTotalMemory method.
It retrieves the number of bytes currently thought to be allocated by the garbage collector.
Like this:
border: 1px solid black;
Why it didn't work? because:
Always declare the border-style (solid in my example) property before the border-width property. An element must have borders before you can change the color.
you have to do it in that way:
$('#datepicker').datepicker('clearDates');
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
git push -u origin master
… is the same as:
git push origin master ; git branch --set-upstream master origin/master
Do the last statement, if you forget the -u
!
Or you could force it:
git config branch.master.remote origin
git config branch.master.merge refs/heads/master
If you let the command do it for you, it will pick your mistakes like if you typed a non-existent branch or you didn't git remote add
; though that might be what you want. :)
If you're using python 3.4.1 then you get a different answer to your question.
list = [1,2,3]
id(list[0])
id(list[1])
id(list[2])
returns:
1705950792
1705950808 # increased by 16
1705950824 # increased by 16
The integers -5
to 256
have a constant id, and on finding it multiple times its id does not change, unlike all other numbers before or after it that have different id's every time you find it.
The numbers from -5
to 256
have id's in increasing order and differ by 16
.
The number returned by id()
function is a unique id given to each item stored in memory and it is analogy wise the same as the memory location in C.
If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s///
should be all you need:
#!/usr/bin/perl -w
use strict;
main();
sub main{
my $foo = "blahblahblah";
print '$foo: ' , replace("lah","ar",$foo) , "\n"; #$foo: barbarbar
}
sub replace {
my ($from,$to,$string) = @_;
$string =~s/$from/$to/ig; #case-insensitive/global (all occurrences)
return $string;
}
<label onclick="chkBulk();">
<div class="icheckbox_flat-green" style="position: relative;">
<asp:CheckBox ID="chkBulkAssign" runat="server" class="flat"
Style="position:
absolute; opacity: 0;" />
</div>
Bulk Assign
</label>
function chkBulk() {
if ($('[id$=chkBulkAssign]')[0].checked) {
$('div .icheckbox_flat-green').addClass('checked');
$("[id$=btneNoteBulkExcelUpload]").show();
}
else {
$('div .icheckbox_flat-green').removeClass('checked');
$("[id$=btneNoteBulkExcelUpload]").hide();
}
Try this piece of code to create circular progress bar(pie chart). pass it integer value to draw how many percent of filling area. :)
private void circularImageBar(ImageView iv2, int i) {
Bitmap b = Bitmap.createBitmap(300, 300,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
Paint paint = new Paint();
paint.setColor(Color.parseColor("#c4c4c4"));
paint.setStrokeWidth(10);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(150, 150, 140, paint);
paint.setColor(Color.parseColor("#FFDB4C"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.FILL);
final RectF oval = new RectF();
paint.setStyle(Paint.Style.STROKE);
oval.set(10,10,290,290);
canvas.drawArc(oval, 270, ((i*360)/100), false, paint);
paint.setStrokeWidth(0);
paint.setTextAlign(Align.CENTER);
paint.setColor(Color.parseColor("#8E8E93"));
paint.setTextSize(140);
canvas.drawText(""+i, 150, 150+(paint.getTextSize()/3), paint);
iv2.setImageBitmap(b);
}
Your syntax appears completely correct in:
mongoimport --db dbName --collection collectionName --file fileName.json
Make sure you are in the correct folder or provide the full path.
I'd fought with this a long time $('#myelement').val(x)
just wasn't working ... until I realized the #
construction requires an ID, not a NAME. So if ".val(x)
doesn't work!" is your problem, check your element and be sure it has an ID!
It's an embarrassing gotcha, but I felt I had to share to save others much hair-tearing.
Canadian locale happens to follow the same format, too:
new Date().toLocaleDateString('en-CA')
The dll
is missing in the published (deployed environment). That is the reason why it is working in the local i.e. Visual Studio but not in the Azure Website Environment.
Just do Copy Local = true
in the properties for the assembly(System.Web.Http.WebHost) and then do a redeploy, it should work fine.
If you get the similar error i.e. some other assembly missing, then make that assembly to copylocal=true and redeploy, repeat this iteratively - if you are unsure of its dependencies.
I came across this issue myself today and it happened to be only in Chrome. What made me realise it might be a rendering issue. Moving the specific modal to it's own rendering layer solved it.
#myModal {
-webkit-transform: translate3d(0, 0, 0);
}
Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here
However, the text is very confusion and contradicts itself.
This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.
But underneath it states that these are the supported platforms.
Supported Platforms:
.NET Framework 4
Windows 8
Windows Phone 8.1
Windows Phone Silverlight 7.5
Silverlight 4
Portable Class Libraries
Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.
There are several ways to do this:
$collection = Mage::getModel('...')
->getCollection()
->setPageSize(20)
->setCurPage(1);
Will get first 20 records.
Here is the alternative and maybe more readable way:
$collection = Mage::getModel('...')->getCollection();
$collection->getSelect()->limit(20);
This will call Zend Db limit. You can set offset as second parameter.
You may also use this
divID = "question-" + (i*1+1);
to be sure that i
is converted to integer.
Try the following steps:
1) Open project.json
file and Remove all Microsoft.EntityFrameworkCore.Tools references from dependencies and tools sections.
2) Close Package Manager Console (PMC) and restart Visual Studio
3) Add under dependencies section:
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
}
4) Add under tools section
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
5) Restart again Visual Studio 2015
6) Open the PMC and type
Add-Migration $Your_First_Migration_Name$
This happen because the PMC recognize the tools when Visual Studio is starting.
If you want to implement that yourself, the OAuth 2.0 flow for Web Server Applications is documented at https://developers.google.com/accounts/docs/OAuth2WebServer, in particular you should check the section about using a refresh token:
https://developers.google.com/accounts/docs/OAuth2WebServer#refresh
open jquery-ui-*.js
find $.widget( "ui.accordion", {
find _eventHandler: function( event ) {
inside
change
var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = {
oldHeader: active,
oldPanel: toHide,
newHeader: collapsing ? $() : clicked,
newPanel: toShow };
to
var options = this.options,
clicked = $( event.currentTarget),
clickedIsActive = clicked.next().attr('aria-expanded') == 'true',
collapsing = clickedIsActive && options.collapsible;
if (clickedIsActive == true) {
var toShow = $();
var toHide = clicked.next();
} else {
var toShow = clicked.next();
var toHide = $();
}
eventData = {
oldHeader: $(),
oldPanel: toHide,
newHeader: clicked,
newPanel: toShow
};
before active.removeClass( "ui-accordion-header-active ui-state-active" );
add if (typeof(active) !== 'undefined') {
and closing }
enjoy
mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)
mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM tin3;
+----+------------+
| id | val |
+----+------------+
| 1 | 0000000012 |
| 2 | 0000000007 |
| 4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)
mysql>
mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
| 10 |
+-------------+
1 row in set (0.01 sec)
mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
| 8 |
+-------+
1 row in set (0.00 sec)
In one line:
if someBoolValue: num1 = 20
But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.
if someBoolValue:
num1 = 20
(Equally, camel caps should be avoided. So rather use some_bool_value
.)
Note that an in-line expression some_value if predicate
without an else
part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.
Import in Java does not work at all, as it is evaluated at compile time only. (Treat it as shortcuts so you do not have to write fully qualified class names). At runtime there is no import at all, just FQCNs.
At runtime it is necessary that all classes you have referenced can be found by classloaders. (classloader infrastructure is sometimes dark magic and highly dependent on environment.) In case of an applet you will have to rig up your HTML tag properly and also provide necessary JAR archives on your server.
PS: Matching at runtime is done via qualified class names - class found under this name is not necessarily the same or compatible with class you have compiled against.
I had the problem and was tinkering with different solutions mentioned here. Since I was running my project from Visual Studio, apparently, I needed to set the environment path inside Visual Studio and not the system path.
Adding a simple PYTHONHOME=PATH\TO\PYTHON\DIR in the project solution\properties\environment solved the problem.
The 00947 message indicates that the record which you are trying to send to Oracle lacks one or more of the columns which was included at the time the table was created. The 00913 message indicates that the record which you are trying to send to Oracle includes more columns than were included at the time the table was created. You just need to check the number of columns and its type in both the tables ie the tables that are involved in the sql.
If you have only files there (no subdirectories) a quick solution is to select all the files (click
on the first, Shift+click
on the last) and hit Enter
or right click
and select Open
. For most of the data files this will download them straight to your computer.
Year 2020. Now we have element.scrollIntoView()
method to scroll to specific element.
HTML
<div id="my_element">
</div>
JS
var my_element = document.getElementById("my_element");
my_element.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});
Good thing is we can initiate this from any onclick/event and need not be limited to tag.
sometimes you need to select some fields by FirstOrDefault()
or singleOrDefault()
you can use the below query:
List<ResultLine> result = Lines
.GroupBy(l => l.ProductCode)
.Select(cl => new Models.ResultLine
{
ProductName = cl.select(x=>x.Name).FirstOrDefault(),
Quantity = cl.Count().ToString(),
Price = cl.Sum(c => c.Price).ToString(),
}).ToList();
@sedit was on the right path, but it's a bit awkward to define a variable.
The way to do this in bash is to put a dollar sign in front of your single quoted string.
$ echo -e '1\n2\n3'
1
2
3
$ echo -e '1\n2\n3' | sed 's/.*/\t&/g'
t1
t2
t3
$ echo -e '1\n2\n3' | sed $'s/.*/\t&/g'
1
2
3
If your string needs to include variable expansion, you can put quoted strings together like so:
$ timestamp=$(date +%s)
$ echo -e '1\n2\n3' | sed "s/.*/$timestamp"$'\t&/g'
1491237958 1
1491237958 2
1491237958 3
In bash $'string'
causes "ANSI-C expansion". And that is what most of us expect when we use things like \t
, \r
, \n
, etc. From: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html#ANSI_002dC-Quoting
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded...
The expanded result is single-quoted, as if the dollar sign had not been present.
I personally think most efforts to avoid bash are silly because avoiding bashisms does NOT* make your code portable. (Your code will be less brittle if you shebang it to bash -eu
than if you try to avoid bash and use sh
[unless you are an absolute POSIX ninja].) But rather than have a religious argument about that, I'll just give you the BEST* answer.
$ echo -e '1\n2\n3' | sed "s/.*/$(printf '\t')&/g"
1
2
3
* BEST answer? Yes, because one example of what most anti-bash shell scripters would do wrong in their code is use echo '\t'
as in @robrecord's answer. That will work for GNU echo, but not BSD echo. That is explained by The Open Group at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html#tag_20_37_16 And this is an example of why trying to avoid bashisms usually fail.
Only works in IE
$(function(){
var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>';
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xml);
alert(xmlDoc.xml);
});
Then push xmlDoc.xml to your java code.
The way I solved this, which is another option (if you have jQuery available), was to Define the fields in an old-school object and then extend the class with that object. I also didn't want to pepper the constructor with assignments, this appeared to be a neat solution.
function MyClassFields(){
this.createdAt = new Date();
}
MyClassFields.prototype = {
id : '',
type : '',
title : '',
createdAt : null,
};
class MyClass {
constructor() {
$.extend(this,new MyClassFields());
}
};
-- Update Following Bergi's comment.
No JQuery Version:
class SavedSearch {
constructor() {
Object.assign(this,{
id : '',
type : '',
title : '',
createdAt: new Date(),
});
}
}
You still do end up with 'fat' constructor, but at least its all in one class and assigned in one hit.
EDIT #2: I've now gone full circle and am now assigning values in the constructor, e.g.
class SavedSearch {
constructor() {
this.id = '';
this.type = '';
this.title = '';
this.createdAt = new Date();
}
}
Why? Simple really, using the above plus some JSdoc comments, PHPStorm was able to perform code completion on the properties. Assigning all the vars in one hit was nice, but the inability to code complete the properties, imo, isn't worth the (almost certainly minuscule) performance benefit.
The simplest way to create signed/unsigned APKs using Eclipse and ADT is as follows:
Select the location for the new APK file and click "Save".
Hope this helps.
Shamelessly copied from Generic deserialization of an xml string
public static T DeserializeFromXmlString<T>(string xmlString)
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlString))
{
return (T) serializer.Deserialize(reader);
}
}
I was able to get rid of this issue by installing nvm
, then setting node to latest version.
nvm
using curl
(for latest version go to nvm.sh)curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
nvm ls
v10.12.0
default -> v10.12 (-> v10.12.0)
node -> stable (-> v10.12.0) (default)
stable -> 10.12 (-> v10.12.0)
…
nvm use v10.12
nvm is not compatible with the npm config "prefix" option: currently set to ""
nvm use --delete-prefix v10.12.0
After following the commands above, you will be able to install react/angular in Ubuntu.
In iOS 9.2 they renamed the 'Profiles' to 'Device Management'
This is how you should do it now:
try this one
<asp:DropDownList ID="ddList" runat="server">
<asp:ListItem Value="">--Select Month--</asp:ListItem>
<asp:ListItem Value="1">January</asp:ListItem>
<asp:ListItem Value="2">Feburary</asp:ListItem>
...
<asp:ListItem Value="12">December</asp:ListItem>
</asp:DropDownList>
Value should be empty for the default selected listitem, then it works fine
I would also highly recommend Adminer - http://www.adminer.org/
It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.
Assuming you want the format "(123) 456-7890
":
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3]
}
return null
}
Here's a version that allows the optional +1
international code:
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/)
if (match) {
var intlCode = (match[1] ? '+1 ' : '')
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
}
return null
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900') // => "(234) 567-8900"
For me the problem was solved by changing the import sequence :
One with I got the error :
imports: [
BrowserModule, HttpClientModule, AppRoutingModule,
CommonModule
],
Changed this to :
imports: [
BrowserModule, CommonModule, HttpClientModule,
AppRoutingModule
],
You mean something like this?
<?php
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo "{$trend->name}\n";
}
We've always used an
if(iserror(vlookup,"n/a",vlookup))
Excel 2007 introduced IfError which allows you to do the vlookup and add output in case of error, but that doesn't help you with 2003...
Use window.confirm()
instead of window.alert()
.
HTML:
<input type="submit" onclick="return clicked();" value="Button" />
JavaScript:
function clicked() {
return confirm('clicked');
}
Following are the ways
From the code (the way you have mentioned) ->
displayBox.Text += sent + "\r\n";
or
displayBox.Text += sent + Environment.NewLine;
From the UI
a) WPF
Set TextWrapping="Wrap" and AcceptsReturn="True"
Press Enter key to the textbox and new line will be created
b) Winform text box
Set TextBox.MultiLine and TextBox.AcceptsReturn to true
setLoanItem()
isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.
Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.
You probably want to pass in a media object on which to call the method:
public void loanItem(Media m) {
m.setLoanItem("Yes");
}
You can get the output of that command and put it in a variable. then use heredoc
. for example:
nc -l -p 80 <<< "tested like a charm";
can be written like:
nc -l -p 80 <<EOF
tested like a charm
EOF
and like this (this is what you want):
text="tested like a charm"
nc -l -p 80 <<EOF
$text
EOF
Practical example in busybox
under docker
container:
kasra@ubuntu:~$ docker run --rm -it busybox
/ # nc -l -p 80 <<< "tested like a charm";
sh: syntax error: unexpected redirection
/ # nc -l -p 80 <<EOL
> tested like a charm
> EOL
^Cpunt! => socket listening, no errors. ^Cpunt! is result of CTRL+C signal.
/ # text="tested like a charm"
/ # nc -l -p 80 <<EOF
> $text
> EOF
^Cpunt!
Reference link: http://www.programering.com/a/MTNyUDMwATA.html
Steps I followed
1) Execute the command adb nodaemon server
in command prompt
Output at command prompt will be: The following error occurred cannot bind 'tcp:5037'
The original ADB server port binding failed
2) Enter the following command query which using port 5037
netstat -ano | findstr "5037"
The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288
3) View the task manager, close all adb.exe
4) Restart eclipse or other IDE
The above steps worked for me.
Since the question mentioned third-party libraries and not all packages then you probably want to fall back to using wildcards.
A use case being: I just want to update all my packages that are obtained from the Github VCS, then you would just say:
go get -u github.com/... // ('...' being the wildcard).
This would go ahead and only update your github packages in the current $GOPATH
Same applies for within a VCS too, say you want to only upgrade all the packages from ogranizaiton A's repo's since as they have released a hotfix you depend on:
go get -u github.com/orgA/...
I was also having some of the Cannot execute command
. Everything looked correct, but in fact I was having a non-breakable space
right before my command which was ofcourse impossible to spot with the naked eye:
if [[ "true" ]]; then
highlight --syntax js "var i = 0;"
fi
Which, in Vim, looked like:
if [[ "true" ]]; then
highlight --syntax js "var i = 0;"
fi
Only after running the Bash script checker shellcheck
did I find the problem.
additionally, you need to dissmis dialog before calling activity.super.onBackPressed()
, otherwise you'll get "Activity has leaked.." error.
Example in my case with sweetalerdialog library:
@Override
public void onBackPressed() {
//super.onBackPressed();
SweetAlertDialog progressDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
progressDialog.setCancelable(false);
progressDialog.setTitleText("Are you sure you want to exit?");
progressDialog.setCancelText("No");
progressDialog.setConfirmText("Yes");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismiss();
MainActivity.super.onBackPressed();
}
});
progressDialog.show();
}
Go to the directory where you have the MySQL executable. -u
for username and -p
to prompt for the password:
C:\xampp\mysql\bin>mysql -u username -ppassword databasename < C:\file.sql
ou can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
You can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
String a="myWord";
if(a.compareTo(another_string) <0){
//a is strictly < to another_string
}
else if (a.compareTo(another_string) == 0){
//a equals to another_string
}
else{
// a is strictly > than another_string
}
Here is the working solution for ie, firefox and chrome:
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
var confirmationMessage = 'Are you sure to leave the page?'; // a space
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
Generic function that is validated at compilation!
public static bool IsBetween<T>(this T item, T start, T end) where T : IComparable
{
return item.CompareTo(start) >= 0 && item.CompareTo(end) <= 0;
}
empty()
function:Returns FALSE
if var
has a non-empty and non-zero value.
That’s a good thing to know. In other words, everything from NULL
, to 0
to “” will return TRUE
when using the empty()
function.
isset()
function returns:Returns TRUE
if var
exists; FALSE
otherwise.
In other words, only variables that don’t exist (or, variables with strictly NULL
values) will return FALSE
on the isset()
function. All variables that have any type of value, whether it is 0
, a blank text string, etc. will return TRUE
.
you can install it dirctly via
$ npm install --save react react-dom
$ npm install --save react-bootstrap
then import what you really need from the bootstrap like :
import Button from 'react-bootstrap/lib/Button';
// or
import Button from 'react-bootstrap';
and also you can install :
npm install --save reactstrap@next react react-dom
check this out click here .
and for the CSS you can read this link also carfuly
For using dictionary object in typescript you can use interface as below:
interface Dictionary<T> {
[Key: string]: T;
}
and, use this for your class property type.
export class SearchParameters {
SearchFor: Dictionary<string> = {};
}
to use and initialize this class,
getUsers(): Observable<any> {
var searchParams = new SearchParameters();
searchParams.SearchFor['userId'] = '1';
searchParams.SearchFor['userName'] = 'xyz';
return this.http.post(searchParams, 'users/search')
.map(res => {
return res;
})
.catch(this.handleError.bind(this));
}
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();
Refer to the documentation.
Eva M from above, almost had the answer as posted above (Thanks Eva M!):
var validator = $( "#myform" ).validate();
validator.form();
This is almost the answer, but it causes problems, in even the most up to date jquery validation plugin as of 13 DEC 2018. The problem is that if one directly copies that sample, and EVER calls ".validate()" more than once, the focus/key processing of the validation can get broken, and the validation may not show errors properly.
Here is how to use Eva M's answer, and ensure those focus/key/error-hiding issues do not occur:
1) Save your validator to a variable/global.
var oValidator = $("#myform").validate();
2) DO NOT call $("#myform").validate() EVER again.
If you call $("#myform").validate() more than once, it may cause focus/key/error-hiding issues.
3) Use the variable/global and call form.
var bIsValid = oValidator.form();
$res = explode("\n",wordwrap('12345678910', 8, "...\n",true))[0];
// $res will be : "12345678..."
If you are using Swift 3x and UITextView, maybe the NSForegroundColorAttributeName won't work (it didn't work for me no matter what approach I tried).
So, after some digging around I found a solution.
//Get the textView somehow
let textView = UITextView()
//Set the attributed string with links to it
textView.attributedString = attributedString
//Set the tint color. It will apply to the link only
textView.tintColor = UIColor.red
The problem is the blank line you are typing before the else
or elif
. Pay attention to the prompt you're given. If it is >>>
, then Python is expecting the start of a new statement. If it is ...
, then it's expecting you to continue a previous statement.
FORMAT()
is slower than CONVERT()
. This answer is slightly better than @jpx's answer because it only does a replace on the time part of the date.
112 = yyyymmdd - no format change needed
108 = hh:mm:ss - remove :
SELECT CONVERT(VARCHAR, GETDATE(), 112) +
REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '')
Ah, that would be because RegExp is not jQuery. :)
Try this page. jQuery.attr
doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text()
to return the String representation.
Something like:
$("li").val("title").search(/sometext/i));
Suggest you not to use Count
because count always makes extra loads for db use SELECT 1
and it returns 1 if your record right there otherwise it returns null and you can handle it.
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
SELECT so.name,so.modify_date
FROM sys.objects as so
INNER JOIN INFORMATION_SCHEMA.TABLES as ist
ON ist.TABLE_NAME=so.name where ist.TABLE_TYPE='BASE TABLE' AND
TABLE_CATALOG='DbName' order by so.modify_date desc;
this is help to get table modify with table name
ToInt32 rounds. Casting to int just throws away the non-integer component.
What do you mean by impacts? Content will flow around a float. That's how they work.
If you want it to appear above your design, try setting:
z-index: 10;
position: absolute;
right: 0;
top: 0;
Try using Git Bash to push your code/make changes instead of uploading files directly on GitHub (it is less prone to errors and is quite comfortable at times - takes less time as well!), for doing so, you may follow the below-given steps:
The resources you put in src/main/resources will be copied during the build process to target/classes which can be accessed using:
...this.getClass().getResourceAsStream("/config.txt");
Git 1.7.0 has “sparse checkouts”. See “core.sparseCheckout” in the git config manpage, “Sparse checkout” in the git read-tree manpage, and “Skip-worktree bit” in the git update-index manpage.
The interface is not as convenient as SVN’s (e.g. there is no way to make a sparse checkout at the time of an initial clone), but the base functionality upon which simpler interfaces could be built is now available.
One case where you can be unable to debug an application in Android Studio is when you have the "release" build variant selected. Happened to me - Gradle builds a release version of the app (which is not debuggable) and then Android Studio fails at trying to connect the debugger.
I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; //Tell the user how the process went
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}
//Start Process
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
//Check if background worker is doing anything and send a cancellation if it is
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
//Check if there is a request to cancel the process
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
//If the process exits the loop, ensure that progress is set to 100%
//Remember in the loop we set i < 100 so in theory the process will complete at 99%
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Process was cancelled";
}
else if (e.Error != null)
{
lblStatus.Text = "There was an error running the process. The thread aborted";
}
else
{
lblStatus.Text = "Process was completed";
}
}
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
I use Xcode 4.3.2, and my problem was that in there where a folder inside another folder with the same name, e.g myFolder/myFolder/.
The solution was to change the second folder's name e.g myFolder/_myFolder and the problem was solved.
I hope this can help some one.
Use a RotateAnimation
, setting the pivot point to the centre of your image.
RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
// Start animating the image
final ImageView splash = (ImageView) findViewById(R.id.splash);
splash.startAnimation(anim);
// Later.. stop the animation
splash.setAnimation(null);
Some facts:
Google offers a public search webservice API which returns JSON: http://ajax.googleapis.com/ajax/services/search/web. Documentation here
Java offers java.net.URL
and java.net.URLConnection
to fire and handle HTTP requests.
JSON can in Java be converted to a fullworthy Javabean object using an arbitrary Java JSON API. One of the best is Google Gson.
Now do the math:
public static void main(String[] args) throws Exception {
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search = "stackoverflow";
String charset = "UTF-8";
URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
// Show title and URL of 1st result.
System.out.println(results.getResponseData().getResults().get(0).getTitle());
System.out.println(results.getResponseData().getResults().get(0).getUrl());
}
With this Javabean class representing the most important JSON data as returned by Google (it actually returns more data, but it's left up to you as an exercise to expand this Javabean code accordingly):
public class GoogleResults {
private ResponseData responseData;
public ResponseData getResponseData() { return responseData; }
public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
public String toString() { return "ResponseData[" + responseData + "]"; }
static class ResponseData {
private List<Result> results;
public List<Result> getResults() { return results; }
public void setResults(List<Result> results) { this.results = results; }
public String toString() { return "Results[" + results + "]"; }
}
static class Result {
private String url;
private String title;
public String getUrl() { return url; }
public String getTitle() { return title; }
public void setUrl(String url) { this.url = url; }
public void setTitle(String title) { this.title = title; }
public String toString() { return "Result[url:" + url +",title:" + title + "]"; }
}
}
###See also:
Update since November 2010 (2 months after the above answer), the public search webservice has become deprecated (and the last day on which the service was offered was September 29, 2014). Your best bet is now querying http://www.google.com/search directly along with a honest user agent and then parse the result using a HTML parser. If you omit the user agent, then you get a 403 back. If you're lying in the user agent and simulate a web browser (e.g. Chrome or Firefox), then you get a way much larger HTML response back which is a waste of bandwidth and performance.
Here's a kickoff example using Jsoup as HTML parser:
String google = "http://www.google.com/search?q=";
String search = "stackoverflow";
String charset = "UTF-8";
String userAgent = "ExampleBot 1.0 (+http://example.com/bot)"; // Change this to your company's name and bot homepage!
Elements links = Jsoup.connect(google + URLEncoder.encode(search, charset)).userAgent(userAgent).get().select(".g>.r>a");
for (Element link : links) {
String title = link.text();
String url = link.absUrl("href"); // Google returns URLs in format "http://www.google.com/url?q=<url>&sa=U&ei=<someKey>".
url = URLDecoder.decode(url.substring(url.indexOf('=') + 1, url.indexOf('&')), "UTF-8");
if (!url.startsWith("http")) {
continue; // Ads/news/etc.
}
System.out.println("Title: " + title);
System.out.println("URL: " + url);
}
Here's a simpler explanation:
You're correct that whether you use notify() or notifyAll(), the immediate result is that exactly one other thread will acquire the monitor and begin executing. (Assuming some threads were in fact blocked on wait() for this object, other unrelated threads aren't soaking up all available cores, etc.) The impact comes later.
Suppose thread A, B, and C were waiting on this object, and thread A gets the monitor. The difference lies in what happens once A releases the monitor. If you used notify(), then B and C are still blocked in wait(): they are not waiting on the monitor, they are waiting to be notified. When A releases the monitor, B and C will still be sitting there, waiting for a notify().
If you used notifyAll(), then B and C have both advanced past the "wait for notification" state and are both waiting to acquire the monitor. When A releases the monitor, either B or C will acquire it (assuming no other threads are competing for that monitor) and begin executing.
There is a section on Practical Closures at the Mozilla Developer Network.
Motivated by @Malvineaus answer I tried it myself and noticed that it didn't work for me.
You can specify subnet masks with '192.168.1.%' or '192.168.1.0/255.255.255.0' but the subnet must always be on complete octets. see https://mariadb.com/kb/en/create-user/#host-name-component. As result the functionality between one way of specification and the other is the same.
For example '192.168.1.0/255.255.255.128' will not work as it is not on a complete octet boundary.
Just build your code in x86 mode not in AnyCpu.
You've used text-decoration none in the wrong selector. You need to check which tag do you need for decoration none.
You may use this code
.boxhead h2 a{text-decoration: none;}
OR
.boxhead a{text-decoration: none !important;}
OR
a{text-decoration: none !important;}
Without converting to a string you could try:
Math.Ceiling(Math.Log10(n));
Correction following ysap's comment:
Math.Floor(Math.Log10(n) + 1);
There are two distinct but closely related problems in establishing a secure communication
Both of these problems can be elegantly solved using public key cryptography.
I. Encryption and decryption of data
Alice wants to send a message to Bob which no one should be able to read.
Note that if A wants to send a message to B, A needs to use the Public key of B (which is publicly available to anyone) and neither public nor private key of A comes into picture here.
So if you want to send a message to me you should know and use my public key which I provide to you and only I will be able to decrypt the message since I am the only one who has access to the corresponding private key.
II. Verify the identity of sender (Authentication)
Alice wants to send a message to Bob again. The problem of encrypting the data is solved using the above method.
But what if I am sitting between Alice and Bob, introducing myself as 'Alice' to Bob and sending my own message to Bob instead of forwarding the one sent by Alice. Even though I can not decrypt and read the original message sent by Alice(that requires access to Bob's private key) I am hijacking the entire conversation between them.
Is there a way Bob can confirm that the messages he is receiving are actually sent by Alice?
While that isn't exactly possible you could do something similar to what Google does and set your cookie to expire Jan 17, 2038 or something equally far off.
In all practicality you might be better off setting your cookie for 10 years or 60*60*24*365*10, which should outlive most of the machines your cookie will live on.
As indicated in other answers, System.getProperty provides the raw data. However, the Apache Commons Lang component provides a wrapper for java.lang.System with handy properties like SystemUtils.IS_OS_WINDOWS
, much like the aforementioned Swingx OS util.
The environment variables displayed in Jenkins (Manage Jenkins -> System information) are inherited from the system (i.e. inherited environment variables)
If you run env
command in a shell you should see the same environment variables as Jenkins shows.
These variables are either set by the shell/system or by you in ~/.bashrc
, ~/.bash_profile
.
There are also environment variables set by Jenkins when a job executes, but these are not displayed in the System Information.
SELECT CompanyName,
CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
WHEN Country = 'Brazil' THEN 'South America'
ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;
you could also grep the line out and then cut it like for instance:
grep 'text' filename | cut -c 1-5
internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value)
{
// get registry key with Microsoft.Win32.Registrys
RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
if ((rk) == null) // if the RegistryKey is null which means it does not exist
{
// the key does not exist
return false; // return false because it does not exist
}
// the registry key does exist
return true; // return true because it does exist
};
usage:
// usage:
/* Create Key - while (loading)
{
RegistryKey k;
k = Registry.CurrentUser.CreateSubKey("stuff");
k.SetValue("value", "value");
Thread.Sleep(int.MaxValue);
}; // no need to k.close because exiting control */
if (regKey(@"HKEY_CURRENT_USER\stuff ... ", "value"))
{
// key exists
return;
}
// key does not exist
FILE *fp;
char* str = "string";
int x = 10;
fp=fopen("test.txt", "w");
if(fp == NULL)
exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);
Mocking is generating pseudo-objects that simulate real objects behaviour for tests
Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill
in conjunction with fliplr
.
Example:
x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.
Tried in Python version 3.6.3 Shell
>>> x = 12
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x,int)
True
Couldn't figure out anything to work for.
<?php
list($width, $height) = getimagesize("http://site.com/image.png");
$arr = array('h' => $height, 'w' => $width );
?>
http://www.codeproject.com/Articles/237501/Windows-Phone-NTP-Client is going to work well for Windows Phone .
Adding the relevant code
/// <summary>
/// Class for acquiring time via Ntp. Useful for applications in which correct world time must be used and the
/// clock on the device isn't "trusted."
/// </summary>
public class NtpClient
{
/// <summary>
/// Contains the time returned from the Ntp request
/// </summary>
public class TimeReceivedEventArgs : EventArgs
{
public DateTime CurrentTime { get; internal set; }
}
/// <summary>
/// Subscribe to this event to receive the time acquired by the NTP requests
/// </summary>
public event EventHandler<TimeReceivedEventArgs> TimeReceived;
protected void OnTimeReceived(DateTime time)
{
if (TimeReceived != null)
{
TimeReceived(this, new TimeReceivedEventArgs() { CurrentTime = time });
}
}
/// <summary>
/// Not reallu used. I put this here so that I had a list of other NTP servers that could be used. I'll integrate this
/// information later and will provide method to allow some one to choose an NTP server.
/// </summary>
public string[] NtpServerList = new string[]
{
"pool.ntp.org ",
"asia.pool.ntp.org",
"europe.pool.ntp.org",
"north-america.pool.ntp.org",
"oceania.pool.ntp.org",
"south-america.pool.ntp.org",
"time-a.nist.gov"
};
string _serverName;
private Socket _socket;
/// <summary>
/// Constructor allowing an NTP server to be specified
/// </summary>
/// <param name="serverName">the name of the NTP server to be used</param>
public NtpClient(string serverName)
{
_serverName = serverName;
}
/// <summary>
///
/// </summary>
public NtpClient()
: this("time-a.nist.gov")
{ }
/// <summary>
/// Begins the network communication required to retrieve the time from the NTP server
/// </summary>
public void RequestTime()
{
byte[] buffer = new byte[48];
buffer[0] = 0x1B;
for (var i = 1; i < buffer.Length; ++i)
buffer[i] = 0;
DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
sArgsConnect.Completed += (o, e) =>
{
if (e.SocketError == SocketError.Success)
{
SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
sArgs.Completed +=
new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
sArgs.SetBuffer(buffer, 0, buffer.Length);
sArgs.UserToken = buffer;
_socket.SendAsync(sArgs);
}
};
_socket.ConnectAsync(sArgsConnect);
}
void sArgs_Completed(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
byte[] buffer = (byte[])e.Buffer;
SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs();
sArgs.RemoteEndPoint = e.RemoteEndPoint;
sArgs.SetBuffer(buffer, 0, buffer.Length);
sArgs.Completed += (o, a) =>
{
if (a.SocketError == SocketError.Success)
{
byte[] timeData = a.Buffer;
ulong hTime = 0;
ulong lTime = 0;
for (var i = 40; i <= 43; ++i)
hTime = hTime << 8 | buffer[i];
for (var i = 44; i <= 47; ++i)
lTime = lTime << 8 | buffer[i];
ulong milliseconds = (hTime * 1000 + (lTime * 1000) / 0x100000000L);
TimeSpan timeSpan =
TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
var currentTime = new DateTime(1900, 1, 1) + timeSpan;
OnTimeReceived(currentTime);
}
};
_socket.ReceiveAsync(sArgs);
}
}
}
Usage :
public partial class MainPage : PhoneApplicationPage
{
private NtpClient _ntpClient;
public MainPage()
{
InitializeComponent();
_ntpClient = new NtpClient();
_ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);
}
void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
txtCurrentTime.Text = e.CurrentTime.ToLongTimeString();
txtSystemTime.Text = DateTime.Now.ToUniversalTime().ToLongTimeString();
});
}
private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
{
_ntpClient.RequestTime();
}
}
For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin
to the PATH
. Use whatever directory you have this installed in.
Then you can run from any directory in command line:
httpd -k restart
The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?
I provide this answer here to the old question since no answers tell the fact that the overriding method can throw nothing here's again what the overriding method can throw:
1) throw the same exception
public static class A
{
public void m1()
throws IOException
{
System.out.println("A m1");
}
}
public static class B
extends A
{
@Override
public void m1()
throws IOException
{
System.out.println("B m1");
}
}
2) throw subclass of the overriden method's thrown exception
public static class A
{
public void m2()
throws Exception
{
System.out.println("A m2");
}
}
public static class B
extends A
{
@Override
public void m2()
throws IOException
{
System.out.println("B m2");
}
}
3) throw nothing.
public static class A
{
public void m3()
throws IOException
{
System.out.println("A m3");
}
}
public static class B
extends A
{
@Override
public void m3()
//throws NOTHING
{
System.out.println("B m3");
}
}
4) Having RuntimeExceptions in throws is not required.
There can be RuntimeExceptions in throws or not, compiler won't complain about it. RuntimeExceptions are not checked exceptions. Only checked exceptions are required to appear in throws if not catched.
Just use the time stamp as date:
SELECT * FROM Cases WHERE date(created_at)='2013-05-01'
Use RETURN QUERY
:
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (txt text -- also visible as OUT parameter inside function
, cnt bigint
, ratio bigint) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt
, count(*) AS cnt -- column alias only visible inside
, (count(*) * 100) / _max_tokens -- I added brackets
FROM (
SELECT t.txt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
LIMIT _max_tokens
) t
GROUP BY t.txt
ORDER BY cnt DESC; -- potential ambiguity
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM word_frequency(123);
Explanation:
It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE
is one way to do that. There are others. Data types of OUT
parameters have to match exactly what is returned by the query.
Choose names for OUT
parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.
But note the potential naming conflict between the OUT
parameter cnt
and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...
) Postgres uses the column alias over the OUT
parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:
ORDER BY 2 DESC
. Example:
ORDER BY count(*)
.plpgsql.variable_conflict
or use the special command #variable_conflict error | use_variable | use_column
in the function. See:
Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt
and cnt
in my examples.
Added a missing ;
and corrected a syntax error in the header. (_max_tokens int)
, not (int maxTokens)
- type after name.
While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric
(or a floating point type). See below.
This is what I think your query should actually look like (calculating a relative share per token):
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (txt text
, abs_cnt bigint
, relative_share numeric) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt, t.cnt
, round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2) -- AS relative_share
FROM (
SELECT t.txt, count(*) AS cnt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
GROUP BY t.txt
ORDER BY cnt DESC
LIMIT _max_tokens
) t
ORDER BY t.cnt DESC;
END
$func$ LANGUAGE plpgsql;
The expression sum(t.cnt) OVER ()
is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.
A final explicit RETURN
statement is not required (but allowed) when working with OUT
parameters or RETURNS TABLE
(which makes implicit use of OUT
parameters).
round()
with two parameters only works for numeric
types. count()
in the subquery produces a bigint
result and a sum()
over this bigint
produces a numeric
result, thus we deal with a numeric
number automatically and everything just falls into place.
This is a version of Ben James's answer, above:
>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>>
>>>
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>>
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>
When I ran this, it helped me see the usefulness of %r.
Generally when people are trying to animate display: none
what they really want is:
Most popular answers use visibility
, which can only achieve the first goal, but luckily it's just as easy to achieve both by using position
.
Since position: absolute
removes the element from typing document flow spacing, you can toggle between position: absolute
and position: static
(global default), combined with opacity
. See the below example.
.content-page {_x000D_
position:absolute;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
.content-page.active {_x000D_
position: static;_x000D_
opacity: 1;_x000D_
transition: opacity 1s linear;_x000D_
}
_x000D_
Here is your exact answer...
const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
LineFeed
).Replace(mystring, string.Empty);
But this one is much better... Specially if you are trying to split the lines (you may also use it with Split)
const char CarriageReturn = '\r'; // #13
const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
string.Format("{0}?{1}", CarriageReturn, LineFeed)
).Replace(mystring, string.Empty);
Much has changed since this question was asked. Visual Studio 2013 with update 4 and Visual Studio 2015 now have integrated tools for Apache Cordova and you can run them on a Visual Studio emulator for Android.
Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)
With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css
.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
Here is a working demo.
Note that you have to use .glyphicon
classes instead of .icon
:
Example:
<span class="glyphicon glyphicon-heart"></span>
Also note that you would still need to include bootstrap.min.js
for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.
If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.
In html:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
In css:
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");
Since the css
file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css
file is all there is to do to start using Glyphicons.
Here is a working demo of the Glyphicons without Bootstrap.
$(document).ready(function() {
window.setTimeout(function(){window.location.href = "https://www.google.co.in"},5000);
});
You can do it in following ways;
You can go to control panel/cpanel and add host % It means now the database server can be accessed from your local machine. Now you can install and use MySQL Administrator or Navicat to import and export database with out using PHP-Myadmin, I used it several times to upload 200 MB to 500 MB of data with no issues
Use gzip, bzip2 compressions for exporting and importing. I am using PEA ZIP software (free) in Windows. Try to avoid Winrar and Winzip
Use MySQL Splitter that splits up the sql file into several parts. In my personal suggestion, Not recommended
Using PHP INI setting (dynamically change the max upload and max execution time) as already mentioned by other friends is fruitful but not always.
select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual
The answers from freedompeace, Kiyarash and Sam Vloeberghs:
.rar application/x-rar-compressed, application/octet-stream
.zip application/zip, application/octet-stream, application/x-zip-compressed, multipart/x-zip
I would do a check on the file name too. Here is how you could check if the file is a RAR or ZIP file. I tested it by creating a quick command line application.
<?php
if (isRarOrZip($argv[1])) {
echo 'It is probably a RAR or ZIP file.';
} else {
echo 'It is probably not a RAR or ZIP file.';
}
function isRarOrZip($file) {
// get the first 7 bytes
$bytes = file_get_contents($file, FALSE, NULL, 0, 7);
$ext = strtolower(substr($file, - 4));
// RAR magic number: Rar!\x1A\x07\x00
// http://en.wikipedia.org/wiki/RAR
if ($ext == '.rar' and bin2hex($bytes) == '526172211a0700') {
return TRUE;
}
// ZIP magic number: none, though PK\003\004, PK\005\006 (empty archive),
// or PK\007\008 (spanned archive) are common.
// http://en.wikipedia.org/wiki/ZIP_(file_format)
if ($ext == '.zip' and substr($bytes, 0, 2) == 'PK') {
return TRUE;
}
return FALSE;
}
Notice that it still won't be 100% certain, but it is probably good enough.
$ rar.exe l somefile.zip
somefile.zip is not RAR archive
But even WinRAR detects non RAR files as SFX archives:
$ rar.exe l somefile.srr
SFX Volume somefile.srr
GetDateTimeFormats can parse DateTime to different formats. Example to "yyyy-MM-dd" format.
SomeDate.Value.GetDateTimeFormats()[5]
There are two types of table views cells provided to you through the storyboard, they are Dynamic Prototypes and Static Cells
1. Dynamic Prototypes
From the name, this type of cell is generated dynamically. They are controlled through your code, not the storyboard. With help of table view's delegate and data source, you can specify the number of cells, heights of cells, prototype of cells programmatically.
When you drag a cell to your table view, you are declaring a prototype of cells. You can then create any amount of cells base on this prototype and add them to the table view through cellForRow
method, programmatically. The advantage of this is that you only need to define 1 prototype instead of creating each and every cell with all views added to them by yourself (See static cell).
So in this case, you cannot connect UI elements on cell prototype to your view controller. You will have only one view controller object initiated, but you may have many cell objects initiated and added to your table view. It doesn't make sense to connect cell prototype to view controller because you cannot control multiple cells with one view controller connection. And you will get an error if you do so.
To fix this problem, you need to connect your prototype label to a UITableViewCell
object. A UITableViewCell
is also a prototype of cells and you can initiate as many cell objects as you want, each of them is then connected to a view that is generated from your storyboard table cell prototype.
Finally, in your cellForRow
method, create the custom cell from the UITableViewCell
class, and do fun stuff with the label
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier") as! YourCell
cell.label.text = "it works!"
return cell
}
2. Static Cells
On the other hand, static cells are indeed configured though storyboard. You have to drag UI elements to each and every cell to create them. You will be controlling cell numbers, heights, etc from the storyboard. In this case, you will see a table view that is exactly the same from your phone compared with what you created from the storyboard. Static cells are more often used for setting page, which the cells do not change a lot.
To control UI elements for a static cell, you will indeed need to connect them directly to your view controller, and set them up.
Not sure if you have resolved it (and if I understand correctly), but here's my idea:
If parent receives myProp, and you want it to pass to child and watch it in child, then parent has to have copy of myProp (not reference).
Try this:
new Vue({
el: '#app',
data: {
text: 'Hello'
},
components: {
'parent': {
props: ['myProp'],
computed: {
myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
}
},
'child': {
props: ['myProp'],
watch: {
myProp(val, oldval) { now val will differ from oldval }
}
}
}
}
and in html:
<child :my-prop="myInnerProp"></child>
actually you have to be very careful when working on complex collections in such situations (passing down few times)
In python, this is called "unpacking", and you can find a bit about it in the tutorial. The documentation of it sucks, I agree, especially because of how fantasically useful it is.
How about adding a space in the pattern attribute like pattern="[a-zA-Z0-9 ]+"
.
If you want to support any kind of space try pattern="[a-zA-Z0-9\s]+"
Papa Parse handles commas in values and other edge cases.
(Baby Parse for Node has been deprecated - you can now use Papa Parse in the Browser and in Node.)
Eg. (node)
const csvParser = require('papaparse'); // previously you might have used babyparse
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;
1,,"a,b"
Simply copy the file, add and commit it:
cp dir1/A.txt dir2/A.txt
git add dir2/A.txt
git commit -m "Duplicated file from dir1/ to dir2/"
Then the following commands will show the full pre-copy history:
git log --follow dir2/A.txt
To see inherited line-by-line annotations from the original file use this:
git blame -C -C -C dir2/A.txt
Git does not track copies at commit-time, instead it detects them when inspecting history with e.g. git blame
and git log
.
Most of this information comes from the answers here: Record file copy operation with Git
Note that the jQuery solutions that normalize height on here may break with IE.
After some testing (with Bootstrap 3) it looks like IE doesn't bother resizing images unless they're actually being rendered. If you make the window smaller, the image of the active item gets resized but the background images preserve their height, so the "tallest" height stays the same.
In my case we were only rendering images on these items, and the images were only ever a few pixels off. So I opted to style all of the images with the height of the active image. Everything else gets resized to fit the height, so keep that in mind if your aspect ratios vary a lot.
function carouselNormalization() {
var items = $('.carousel .item');
if (items.length) {
function normalizeHeights() {
let activeImageHeight = items.filter('.active').find('img').height();
items.each(function() {
$(this).find('img').css('height', activeImageHeight + 'px');
});
};
normalizeHeights();
$(window).on('resize orientationchange', function() {
items.each(function() {
$(this).find('img').removeAttr('style');
});
normalizeHeights();
});
}
}
$(window).on('load', carouselNormalization);
Use this
openssl ciphers -v | awk '{print $2}' | sort | uniq
Eclipse itself will add the @Override
annotation when you tell it to "generate unimplemented methods" during creation of a class that implements an interface.
You can use .map().
Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.
As the return value is a jQuery object, which contains an array, it's very common to call .get()
on the result to work with a basic array.
Use
var arr = $('input[name="pname[]"]').map(function () {
return this.value; // $(this).val()
}).get();
I haven't heard about progress with Copy-Item
. If you don't want to use any external tool, you can experiment with streams. The size of buffer varies, you may try different values (from 2kb to 64kb).
function Copy-File {
param( [string]$from, [string]$to)
$ffile = [io.file]::OpenRead($from)
$tofile = [io.file]::OpenWrite($to)
Write-Progress -Activity "Copying file" -status "$from -> $to" -PercentComplete 0
try {
[byte[]]$buff = new-object byte[] 4096
[long]$total = [int]$count = 0
do {
$count = $ffile.Read($buff, 0, $buff.Length)
$tofile.Write($buff, 0, $count)
$total += $count
if ($total % 1mb -eq 0) {
Write-Progress -Activity "Copying file" -status "$from -> $to" `
-PercentComplete ([long]($total * 100 / $ffile.Length))
}
} while ($count -gt 0)
}
finally {
$ffile.Dispose()
$tofile.Dispose()
Write-Progress -Activity "Copying file" -Status "Ready" -Completed
}
}
You could declare a variable as a temporary table like this:
declare @myList table (Id int)
Which means you can use the insert
statement to populate it with values:
insert into @myList values (1), (2), (5), (7), (10)
Then your select
statement can use either the in
statement:
select * from DBTable
where id in (select Id from @myList)
Or you could join to the temporary table like this:
select *
from DBTable d
join @myList t on t.Id = d.Id
And if you do something like this a lot then you could consider defining a user-defined table type so you could then declare your variable like this:
declare @myList dbo.MyTableType
You can multiply numpy arrays by scalars and it just works.
>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2, 4, 6],
[ 8, 10, 12]])
This is also a very fast and efficient operation. With your example:
>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
[6., 8.]])
A fast shortcut for restarting service on Windows:
1) Press Windows Key + R
2) Type "services.msc"
3) Order by name
4) Find "PostgreSQL" service and restart it.
Give a try to .bringToFront()
:
http://developer.android.com/reference/android/view/View.html#bringToFront%28%29
Bringing this question up to date by providing this answer.
appdmg
is a simple, easy-to-use, open-source command line program that creates dmg-files from a simple json specification. Take a look at the readme at the official website:
https://github.com/LinusU/node-appdmg
Quick example:
Install appdmg
npm install -g appdmg
Write a json file (spec.json
)
{
"title": "Test Title",
"background": "background.png",
"icon-size": 80,
"contents": [
{ "x": 192, "y": 344, "type": "file", "path": "TestApp.app" },
{ "x": 448, "y": 344, "type": "link", "path": "/Applications" }
]
}
Run program
appdmg spec.json test.dmg
(disclaimer. I'm the creator of appdmg)
I had this problem, and turns out the problem was that I had used
new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("foo")
instead of
new SimpleJdbcCall(jdbcTemplate)
.withFunctionName("foo")
<textarea rows="4" cols="50"></textarea>
It is equivalent to:
textarea {
height: 4em;
width: 50em;
}
where 1em is equivalent to the current font size, thus make the text area 50 chars wide. see here.
You can also use an oracle defined collection
DECLARE
arrayvalues sys.odcivarchar2list;
BEGIN
arrayvalues := sys.odcivarchar2list('Matt','Joanne','Robert');
FOR x IN ( SELECT m.column_value m_value
FROM table(arrayvalues) m )
LOOP
dbms_output.put_line (x.m_value||' is a good pal');
END LOOP;
END;
I would use in-memory array. But with the .COUNT
improvement suggested by uziberia:
DECLARE
TYPE t_people IS TABLE OF varchar2(10) INDEX BY PLS_INTEGER;
arrayvalues t_people;
BEGIN
SELECT *
BULK COLLECT INTO arrayvalues
FROM (select 'Matt' m_value from dual union all
select 'Joanne' from dual union all
select 'Robert' from dual
)
;
--
FOR i IN 1 .. arrayvalues.COUNT
LOOP
dbms_output.put_line(arrayvalues(i)||' is my friend');
END LOOP;
END;
Another solution would be to use a Hashmap like @Jchomel did here.
NB:
With Oracle 12c you can even query arrays directly now!
IMO the nicest way is to use the next()
function:
router.get('/', function(req, res, next) {
var err = new Error('Not found');
err.status = 404;
return next(err);
}
Then the error is handled by your error handler and you can style the error nicely using HTML.
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
"Both" has been stated above, and is the obvious answer...but IMO, white box testing goes far beyond developer unit testing (althoughI suppose it could depend on where you draw the line between white and black). For example, code coverage analysis is a common white box approach - i.e. run some scenarios or tests, and examine the results looking for holes in testing. Even if unit tests have 100% cc, measuring cc on common user scenarios can reveal code that may potentially need even more testing.
Another place where white box testing helps is examining data types, constants and other information to look for boundaries, special values, etc. For example, if an application has an input that takes a numeric input, a bb only approach could require the tester to "guess" at what values would be good for testing, whereas a wb approach may reveal that all values between 1-256 are treated one way, while larger values are treated another way...and perhaps the number 42 has yet another code path.
So, to answer the original question - both bb and wb are essential for good testing.
Extracting text from PDF is a hard problem because PDF has such a layout-oriented structure. You can see the docs and source code of my barely-successful attempt on CPAN (my implementation is in Perl). The PDF data structure is very cool and well designed, but it's easier to write than read.
there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD')
and heredoc(<<<EOD)
strings
you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.
nowdoc strings will not expand variables just like single quotes.
ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
The same can be achieved from ssms client itself. Just open the ssms, insert the server name and then from options under heading connection properties make sure Trust server certificate is checked.
You were able to use the PHP Horde_Text_Diff package.
However this package is no longer available.
On unix and linux there is the file
command to guess file types. There's even a windows port.
From the man page:
File tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic number tests, and language tests. The first test that succeeds causes the file type to be printed.
You would need to run the file
command with the subprocess
module and then parse the results to figure out an extension.
edit: Ignore my answer. Use Chris Johnson's answer instead.
It failed because you used ajax="false"
. This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete
to be never fired (note that all other ajax-related attributes like process
, onstart
, onsuccess
, onerror
and update
are also never fired).
That it worked when you removed actionListener
is also impossible. It should have failed the same way. Perhaps you also removed ajax="false"
along it without actually understanding what you were doing. Removing ajax="false"
should indeed achieve the desired requirement.
Also is it possible to execute actionlistener and oncomplete simultaneously?
No. The script can only be fired before or after the action listener. You can use onclick
to fire the script at the moment of the click. You can use onstart
to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:
onclick
JavaScript code is executedprocess
and current HTML DOM treeonstart
JavaScript code is executedprocess
actionListener
JSF backing bean method is executedaction
JSF backing bean method is executedupdate
and current JSF component treeonsuccess
JavaScript code is executedonerror
JavaScript code is executedupdate
based on ajax response and current HTML DOM treeoncomplete
JavaScript code is executedNote that the update
is performed after actionListener
, so if you were using onclick
or onstart
to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete
instead to show the dialog. Also note that you'd better use action
instead of actionListener
when you intend to execute a business action.
FYI, you can substitute the /*csv*/
for other formats as well including /*xml*/
and /*html*/
.
select /*xml*/ * from emp
would return an xml document with the query results for example.
I came across this article while looking for an easy way to return xml from a query.
This should work for you. Tested all the way back to SQL 2000.
create table #user (username varchar(25))
insert into #user (username) values ('Paul')
insert into #user (username) values ('John')
insert into #user (username) values ('Mary')
declare @tmp varchar(250)
SET @tmp = ''
select @tmp = @tmp + username + ', ' from #user
select SUBSTRING(@tmp, 0, LEN(@tmp))
Initially, I was using the following html/css:
img {
max-width: 100%;
height: auto;
width: auto\9; /* ie8 */
}
<div>
<img src="..." />
</div>
Then I added class="img"
to the <div>
like this:
<div class="img">
<img src="..." />
</div>
And everything started to work fine.
Another reason why people might struggle to get Syntax Highlighting working is because they don't have the appropriate syntax package installed. While some default syntax packages come pre-installed (like Swift, C, JS, CSS), others may not be available.
To solve this you can Cmd + Shift + P ? "install Extensions" and look for the language you want to add, say "Scala".
Find the suitable Syntax package, install it and reload. This will pick up the correct syntax for your files with the predefined extension, i.e. .scala
in this case.
On top of that you might want VS Code to treat all files with certain custom extensions as your preferred language of choice. Let's say you want to highlight all *.es
files as JavaScript, then just open "User Settings" (Cmd + Shift + P ? "User Settings") and configure your custom files association like so:
"files.associations": {
"*.es": "javascript"
},
This works for non-associative arrays:
while(($item = array_shift($array2)) !== null && array_push($array1, $item));
This answer doesn't add any answers that aren't already discussed, but here are some speed results. I think this should resolve questions that came up in the comments. All of these look like they are O(n), based on these three values.
TL;DR: tuples = list(df.itertuples(index=False, name=None))
and tuples = list(zip(*[df[c].values.tolist() for c in df]))
are tied for the fastest.
I did a quick speed test on results for three suggestions here:
tuples = list(zip(*[df[c].values.tolist() for c in df]))
tuples = [tuple(x) for x in df.values]
name=None
suggestion from @Axel: tuples = list(df.itertuples(index=False, name=None))
from numpy import random
import pandas as pd
def create_random_df(n):
return pd.DataFrame({"A": random.randint(n, size=n), "B": random.randint(n, size=n)})
Small size:
df = create_random_df(10000)
%timeit tuples = list(zip(*[df[c].values.tolist() for c in df]))
%timeit tuples = [tuple(x) for x in df.values]
%timeit tuples = list(df.itertuples(index=False, name=None))
Gives:
1.66 ms ± 200 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
15.5 ms ± 1.52 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
1.74 ms ± 75.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Larger:
df = create_random_df(1000000)
%timeit tuples = list(zip(*[df[c].values.tolist() for c in df]))
%timeit tuples = [tuple(x) for x in df.values]
%timeit tuples = list(df.itertuples(index=False, name=None))
Gives:
202 ms ± 5.91 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
1.52 s ± 98.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
209 ms ± 11.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
As much patience as I have:
df = create_random_df(10000000)
%timeit tuples = list(zip(*[df[c].values.tolist() for c in df]))
%timeit tuples = [tuple(x) for x in df.values]
%timeit tuples = list(df.itertuples(index=False, name=None))
Gives:
1.78 s ± 118 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
15.4 s ± 222 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
1.68 s ± 96.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
The zip version and the itertuples version are within the confidence intervals each other. I suspect that they are doing the same thing under the hood.
These speed tests are probably irrelevant though. Pushing the limits of my computer's memory doesn't take a huge amount of time, and you really shouldn't be doing this on a large data set. Working with those tuples after doing this will end up being really inefficient. It's unlikely to be a major bottleneck in your code, so just stick with the version you think is most readable.
Since $http.get
returns a 'promise' with the extra convenience methods success
and error
(which just wrap the result of then
) you should be able to use (regardless of your Angular version):
$http.get('/someUrl')
.then(function success(response) {
console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
}, function error(response) {
console.log('failed', response); // supposed to have: data, status, headers, config, statusText
})
Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments
, even if you don't know the appropriate method signature:
$http.get('/someUrl')
.success(function(data, foo, bar) {
console.log(arguments); // includes data, status, etc including unlisted ones if present
})
.error(function(baz, foo, bar, idontknow) {
console.log(arguments); // includes data, status, etc including unlisted ones if present
});
Then, based on whatever you find, you can 'fix' the function arguments to match.
With the user.language
, user.country
and user.variant
properties.
Example:
java -Duser.language=th -Duser.country=TH -Duser.variant=TH SomeClass
In my case a WAMP server was installed before on my pc, so when installing the new one some files not overwritten, all you have to do in that case is to go to the C:\ and delete the whole WAMP folder then install it again.
I always use object, it is more easily extendable, JSON array is not. For example you originally had some data as a json array, then you needed to add a status header on it you'd be a bit stuck, unless you'd nested the data in an object. The only disadvantage is a slight increase in complexity of creation / parsing.
So instead of
[datum0, datum1, datumN]
You'd have
{data: [datum0, datum1, datumN]}
then later you can add more...
{status: "foo", data: [datum0, datum1, datumN]}
Yes, you can do this quite easily. Click on your project in the project explorer or Navigator, go to the Search menu at the top, click File..., input your search string, and make sure that 'Selected Resources' or 'Enclosing Projects' is selected, then hit search. The alternative way to open the window is with Ctrl-H. This may depend on your keyboard accelerator configuration.
More details: http://www.ehow.com/how_4742705_file-eclipse.html and http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html
(source: avajava.com)
Regarding the original question asked in the title ...
sudo apt-get install libtcnative-1
or if you are on RHEL Linux yum install tomcat-native
The documentation states you need http://tomcat.apache.org/native-doc/
sudo apt-get install libapr1.0-dev libssl-dev
yum install apr-devel openssl-devel
You should remember when to use everyone and that is it
the href is used with links
<a href="#"></a>
<link rel="stylesheet" href="style.css" />
the src is used with scripts and images
<img src="the_image_link" />
<script type="text/javascript" src="" />
the url is used generally in CSS to include something, for exemple to add a background image
selector { background-image: url('the_image_link'); }
Marge array that are different data types :
var arrayInt = [Int]()
arrayInt.append(6)
var testArray = ["a",true,3,"b"] as [Any]
testArray.append(someInt)
Output :
["a", true, 3, "b", "hi", 3, [6]]