you can use an external package if you cant upgrade to 4.5. One such is Ionic.Zip.dll from DotNetZipLib.
using Ionic.Zip;
you can download it here, its free. http://dotnetzip.codeplex.com/
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
On Ubuntu I had to install php5 mysql
extension:
apt-get install php5-mysql
I have an idea. Why not use the ascii_lowercase
constant?
For example, running the following code:
# string module, contains constant ascii_lowercase which is all the lowercase
# letters of the English alphabet
import string
# Example value of s, a string
s = 'aaabcabccd'
# Result variable to store the resulting string
result = ''
# Goes through each letter in the alphabet and checks how many times it appears.
# If a letter appears at least oce, then it is added to the result variable
for letter in string.ascii_letters:
if s.count(letter) >= 1:
result+=letter
# Optional three lines to convert result variable to a list for sorting
# and then back to a string
result = list(result)
result.sort()
result = ''.join(result)
print(result)
Will print 'abcd'
There you go, all duplicates removed and optionally sorted
If you have password for your dB then
mysql -u <username> -p <DBName> < yourfile.sql
Flexbox spec editor here.
This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.
Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.
Since your header and footer aren't meant to flex, they should both have flex: none;
set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto
, so they start at their auto height and can shrink but not grow, but they're also overflow:visible
by default, which triggers their default min-height:auto
to prevent them from shrinking at all. If you ever set an overflow
on them, the behavior of min-height:auto
changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article>
element.)
You can simplify the <article>
flex
too - just set flex: 1;
and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.
I just follow up the answer from @John Wilkey.
My alias python
used to represent python2.7 (located in /usr/bin
).
However the default python_path is now preceded by /usr/local/bin
for python3
; hence when typing python
, I didn't get either the python version.
I tried make a link in /usr/local/bin
for python2
:
ln -s /usr/bin/python /usr/local/bin/
It works when calling python
for python2
.
Try simply to reset last commit using --soft
flag
git reset --soft HEAD~1
Note :
For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"
Just call css with one argument
$('#idDetails').css('display');
If I understand your question. Otherwise, you want cletus' answer.
The site generates a unique token when it makes the form page. This token is required to post/get data back to the server.
Since the token is generated by your site and provided only when the page with the form is generated, some other site can't mimic your forms -- they won't have the token and therefore can't post to your site.
same for Terminator
Ctrl + Shift + V
Look at your terminal key-bindings if any if that doesn't work
Have you tried innerHTML
?
I'd be inclined to use getElementsByTagName()
to find the <tr>
elements, and then on each to call it again to find the <td>
elements. To get the contents, you can either use innerHTML
or the appropriate (browser-specific) variation on innerText
.
You must press twice on tap and (_) key each time, it must look like:
__init__
I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.
Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.
If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.
ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.
Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.
To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?
Like biegleux already said:
If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml
file in your values
folder and define the text size there with the following 3 lines:
<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>
Here is an example for a TextView with large text from the dimens.xml
file:
<TextView
android:id="@+id/hello_world"
android:text="hello world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"/>
Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.
It comprises of the pthread.h
header, libwinpthread.a
, libwinpthread.dll.a
static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll
and libwinpthread_64-1.dll
(this, as of 01-06-2016).
You'll need to link to the libwinpthread.a
library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.
Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.
The above two seem to be the most well known ways for this.
Hope this helps.
I realize this is a little old, but, yes it can be done. Some javascript to get you started:
viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0');
Just change the parts you need and Mobile Safari will respect the new settings.
Update:
If you don't already have the meta viewport tag in the source, you can append it directly with something like this:
var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);
Or if you're using jQuery:
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">');
To get the origin of any url, including paths within a website (/my/path
) or schemaless (//example.com/my/path
), or full (http://example.com/my/path
) I put together a quick function.
In the snippet below, all three calls should log https://stacksnippets.net
.
function getOrigin(url)_x000D_
{_x000D_
if(/^\/\//.test(url))_x000D_
{ // no scheme, use current scheme, extract domain_x000D_
url = window.location.protocol + url;_x000D_
}_x000D_
else if(/^\//.test(url))_x000D_
{ // just path, use whole origin_x000D_
url = window.location.origin + url;_x000D_
}_x000D_
return url.match(/^([^/]+\/\/[^/]+)/)[0];_x000D_
}_x000D_
_x000D_
console.log(getOrigin('https://stacksnippets.net/my/path'));_x000D_
console.log(getOrigin('//stacksnippets.net/my/path'));_x000D_
console.log(getOrigin('/my/path'));
_x000D_
In my case it was the close() that was not executing due to unhandled exception.
void method() throws Exception {
FileInputStream fis = new FileInputStream(fileName);
parse(fis);
fis.close();
}
Assume exception is being thrown on the parse(), which is not handled in this method and therefore the file is not closed, down the road, the file is being deleted, and that delete statement fails, and do not delete.
So, instead I had the code like this, then it worked...
try {
parse(fis);
}
catch (Exception ex) {
fis.close();
throw ex;
}
so basic Java, which sometimes we overlook.
If you have a remote configured and you have / don't care about losing some unpushed code, you can do :
git fetch && git reset --hard
Your main problem is you create new figures in your loop, so each vector gets drawn on a different figure. Here's what I came up with, let me know if it's still not what you expect:
CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
for i,l in enumerate(range(0,cols)):
xs = [0,M[i,0]]
ys = [0,M[i,1]]
plt.plot(xs,ys)
plt.plot(0,0,'ok') #<-- plot a black point at the origin
plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.legend(['V'+str(i+1) for i in range(cols)]) #<-- give a legend
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
OUTPUT:
EDIT CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
colors = ['b','r','k']
for i,l in enumerate(range(0,cols)):
plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.05,head_length=0.1,color = colors[i])
plt.plot(0,0,'ok') #<-- plot a black point at the origin
plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
Math
has static method where you can call directly like Math.abs()
while Date
has static method like Date.now()
and also instance method where you need to create new instance first var time = new Date()
to call time.getHours()
.
// The instance method of Date can be found on `Date.prototype` so you can just call:
var keys = Object.getOwnPropertyNames(Date.prototype);
// And for the static method
var keys = Object.getOwnPropertyNames(Date);
// But if the instance already created you need to
// pass its constructor
var time = new Date();
var staticKeys = Object.getOwnPropertyNames(time.constructor);
var instanceKeys = Object.getOwnPropertyNames(time.constructor.prototype);
Of course you will need to filter the obtained keys for the static method to get actual method names, because you can also get length, name
that aren't a function on the list.
But how if we want to obtain all available method from class that extend another class?
Of course you will need to scan through the root of prototype like using __proto__
. For saving your time you can use script below to get static method and deep method instance.
// var keys = new Set();_x000D_
function getStaticMethods(keys, clas){_x000D_
var keys2 = Object.getOwnPropertyNames(clas);_x000D_
_x000D_
for(var i = 0; i < keys2.length; i++){_x000D_
if(clas[keys2[i]].constructor === Function)_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
}_x000D_
_x000D_
function getPrototypeMethods(keys, clas){_x000D_
if(clas.prototype === void 0)_x000D_
return;_x000D_
_x000D_
var keys2 = Object.getOwnPropertyNames(clas.prototype);_x000D_
for (var i = keys2.length - 1; i >= 0; i--) {_x000D_
if(keys2[i] !== 'constructor')_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
_x000D_
var deep = Object.getPrototypeOf(clas);_x000D_
if(deep.prototype !== void 0)_x000D_
getPrototypeMethods(keys, deep);_x000D_
}_x000D_
_x000D_
// ====== Usage example ======_x000D_
// To avoid duplicate on deeper prototype we use `Set`_x000D_
var keys = new Set();_x000D_
getStaticMethods(keys, Date);_x000D_
getPrototypeMethods(keys, Date);_x000D_
_x000D_
console.log(Array.from(keys));
_x000D_
If you want to obtain methods from created instance, don't forget to pass the constructor
of it.
This is a difficult question I came up against the other day myself. java.util.LinkedHashSet
maintains a linked list of its contents (addition-ordered by default) but does not provide any accessors. Other structure types will fail to provide O(1) on add()
, remove()
, and contains()
.
You can use a LinkedHashSet
and get its iterator()
, grab one element, and discard it. If you don't care too much about speed or memory when doing this frequently to numerous different sets, that is probably your solution... but that seemed wasteful to me. Plus I had a little extra desired functionality.
I ended up writing my own class, dubbed RandomAccessLinkedHashSet
, which concurrently maintains a hashtable, a doubly linked list, and an order-irrelevant array. I wrote it to comply with both Set
and Deque
, though the Deque implementation is a little sketchy since it will fail to push()
elements it already contains, a little bit of a stretch for the interface's contract. Maintaining the third structure, the array, is not necessary at all for what you're doing, but it also allows access to a random element in the set in whatever capacity you can actually provide a random value.
If you're interested I can provide this source. I haven't Serialized
it yet but it works great in runtime.
If you cannot guarantee the type of Set
provided in any way, then you'll have to stick with the Iterator
thing.
I know the topic is old, but I just fell on it after a google search so... here is another solution:
$array_merged = array_merge($array_going_first, $array_going_second);
This one seems pretty clean to me, it works just fine!
One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)
Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).
I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).
Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/
This will add 10 pixels to the left of the paragraph element
p {
margin-left: 10px;
}
or if you just want some padding within your paragraph element
p {
padding-left: 10px;
}
In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.
#!/bin/bash
IP=$(curl automation.whatismyip.com/n09230945.asp)
echo "$IP"
sed "s/IP/$IP/" nsupdate.txt | nsupdate
On the Uncheck "Precompile During Publishing" - I was getting the 403.14 error on a web service I had just written in VS2015 so I rewrote it in VS2013 and was getting the same error. In both cases I had "Precompile During Publishing" on. I unchecked it but was still getting the error. In my case I also had "Delete all existing files prior to publish" but was not deleting everything from the target directory on the server before copying the new published files there. If you don't do that - a "PrecompiledApp.config" file is left behind which causes the problem. Once I deleted that file I was golden on both the VS2013 and VS2015 versions of my web service.
Suppose that you have a file Called "test.txt" with:
a=1.251
b=2.65415
c=3.54
d=549.5645
e=4684.65489
And you want to find a variable (a,b,c,d or e):
ffile=open('test.txt','r').read()
variable=raw_input('Wich is the variable you are looking for?\n')
ini=ffile.find(variable)+(len(variable)+1)
rest=ffile[ini:]
search_enter=rest.find('\n')
number=float(rest[:search_enter])
print "value:",number
One solution I adopted--for use with java code, but the concept is the same with mexFunctions, just messier--is to return a FutureValue and then loop while FutureValue.finished() or whatever returns true. The actual code executes in another thread/process. Wrapping a try,catch around that and a FutureValue.cancel() in the catch block works for me.
In the case of mex functions, you will need to return somesort of pointer (as an int) that points to a struct/object that has all the data you need (native thread handler, bool for complete etc). In the case of a built in mexFunction, your mexFunction will most likely need to call that mexFunction in the separate thread. Mex functions are just DLLs/shared objects after all.
PseudoCode
FV = mexLongProcessInAnotherThread();
try
while ~mexIsDone(FV);
java.lang.Thread.sleep(100); %pause has a memory leak
drawnow; %allow stdout/err from mex to display in command window
end
catch
mexCancel(FV);
end
Apache tomcat keeps the project context path in server.xml path.
For each web project on Eclipse, there is tag from there you can change it.
Suppose, there are two or three project deployed on server.
For each one context path is stored in .
This tag is located on server.xml file within Server created on eclipse.
I have one project for there on context root path in server is:
<Context docBase="Test" path="/test" reloadable="true" source="org.eclipse.jst.jee.server:Test1"/>
This path represents context path of your web application. By changing this path, your web app context path will change.
As these answers are old, I found this alternative. It is very clean and works with just java annotations:
To fix it, create a “none static setter” to assign the injected value for the static variable. For example :
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/
You can use this
<button type="submit" class="btn btn-primary btn-block w-50 mx-auto">Search</button>
Complete Form code -
<form id="submit">
<input type="text" class="form-control mt-5" id="search-city"
placeholder="Search City">
<button type="submit" class="btn btn-primary mt-3 btn-sm btn-block w-50
mx-auto">Search</button>
</form>
In git
stash is a storage area where current changed files can be moved.
stash
area is useful when you want to pull some changes from git
repository and detected some changes in some mutual files available in git
repo.
git stash apply //apply the changes without removing stored files from stash area.
git stash pop // apply the changes as well as remove stored files from stash area.
Note :-
git apply
only apply the changes from stash area whilegit pop
apply as well as remove change fromstash
area.
@Override
public void onBackPressed() {
// Put your code here.
}
//I had to go back to the dashboard. Hence,
@Override
public void onBackPressed() {
Intent intent = new Intent(this,Dashboard.class);
startActivity(intent);
}
Just write this above or below the onCreate Method(within the class)
This should do the trick:
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');
Here's the distinction between ajax
and getJSON
(from the jQuery documentation):
[getJSON] is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, dataType: 'json', data: data, success: callback });
EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:
{
"msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}
...So that msg
property needed to be parsed manually using $.parseJSON()
.
You have to use active in the label to make it work as mentioned above. But you can use checked="checked" and it will work too. It's not necessary but it's more legible and makes more sense as it is more html format compliance.
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
I am not sure if this applies to the older version of chosen,but now in the current version(v1.4.1) they have a option $('#autoship_option').chosen({ allow_single_deselect:true });
This will add a 'x' icon next to the name selected.Use the 'x' to clear the 'select' feild.
PS:make sure you have 'chosen-sprite.png' in the right place as per the chosen.css so that the icons are visible.
I had the same problem, and none of the above solutions worked. Actually, the file include/boost/version.hpp
could not be read (by the cmake script launched by jenkins).
I had to manually change the permission of the (boost) library (even though jenkins belongs to the group, but that is another problem linked to jenkins that I could not figure out):
chmod o+wx ${BOOST_ROOT} -R # allow reading/execution on the whole library
#chmod g+wx ${BOOST_ROOT} -R # this did not suffice, strangely, but it is another story I guess
It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.
To change current working dir to the one containing your script you can use:
import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())
The __file__
variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?
You can use the adjacent sibling selector to achieve something similar, that might help.
.list-item.other-class + .list-item:not(.other-class)
Will effectively target the immediately following element after the last element with the class other-class
.
Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/
Short answer:
int
uses up 4 bytes of memory (and it CANNOT contain a decimal), double
uses 8 bytes of memory. Just different tools for different purposes.
Almost there! The escape sequence for a brace is {{
or }}
so for your example you would use:
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.
I installed Node.js on bluehost.com (a shared server) using:
wget <path to download file>
tar -xf <gzip file>
mv <gzip_file_dir> node
This will download the tar file, extract to a directory and then rename that directory to the name 'node' to make it easier to use.
then
./node/bin/npm install jt-js-sample
Returns:
npm WARN engine [email protected]: wanted: {"node":"0.10.x"} (current: {"node":"0.12.4","npm":"2.10.1"})
[email protected] node_modules/jt-js-sample
+-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
I can now use the commands:
# ~/node/bin/node -v
v0.12.4
# ~/node/bin/npm -v
2.10.1
For security reasons, I have renamed my node directory to something else.
SQL> -- original . . .
SQL> select
2 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ) dt
3 from dual;
DT
----------------------------------------
Friday the 13th of May , 2016
SQL>
SQL> -- collapse repeated spaces . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' * *', ' ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May , 2016
SQL>
SQL> -- and space before commma . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' *(,*) *', '\1 ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May, 2016
SQL>
SQL> -- space before punctuation . . .
SQL> select
2 regexp_replace(
3 to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
4 ' *([.,/:;]*) *', '\1 ') datesp
5 from dual;
DATESP
----------------------------------------
Friday the 13th of May, 2016
We may need more information. Here is what I did to reproduce on SQL Server 2008:
CREATE DATABASE [Test] ON PRIMARY
(
NAME = N'Test'
, FILENAME = N'...Test.mdf'
, SIZE = 3072KB
, FILEGROWTH = 1024KB
)
LOG ON
(
NAME = N'Test_log'
, FILENAME = N'...Test_log.ldf'
, SIZE = 1024KB
, FILEGROWTH = 10%
)
COLLATE SQL_Latin1_General_CP850_BIN2
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MyTable]
(
[SomeCol] [varchar](50) NULL
) ON [PRIMARY]
GO
Insert MyTable( SomeCol )
Select '±' Collate SQL_Latin1_General_CP1_CI_AS
GO
Select SomeCol, SomeCol Collate SQL_Latin1_General_CP1_CI_AS
From MyTable
Results show the original character. Declaring collation in the query should return the proper character from SQL Server's perspective however it may be the case that the presentation layer is then converting to something yet different like UTF-8.
Refer to RFC 6266 (Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)) http://tools.ietf.org/html/rfc6266
See this MSDN article and an example usage here on Stack Overflow.
Let's say that you have the following Linq/POCO class:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
And let's say that you have the following model:
public class PageModel
{
public int MyColorId { get; set; }
}
And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:
public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}
};
In your view, you can create a drop down list like so:
<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
As others have said you're subtracting from the numeric values returned from methods like date.getDate()
, you need to reset those values on your date variable. I've created a method below that will do this for you. It creates a date using new Date()
which will initialize with the current date, then sets the date, month, and year according to the values passed in. For example, if you want to go back 6 days then pass in -6 like so var newdate = createDate(-6,0,0)
. If you don't want to set a value pass in a zero (or you could set default values). The method will return the new date for you (tested in Chrome and Firefox).
function createDate(days, months, years) {
var date = new Date();
date.setDate(date.getDate() + days);
date.setMonth(date.getMonth() + months);
date.setFullYear(date.getFullYear() + years);
return date;
}
Why not just display it in the user's web browser?
//Calling close and then quit will kill the driver running process.
driver.close();
driver.quit();
docker export -o <nameOfContainer>.tar <nameOfContainer>
Might need to prune the existing container using docker prune ...
Import with required modifications:
cat <nameOfContainer>.tar | docker import -c "ENTRYPOINT service mysql start && /bin/bash" - <nameOfContainer>
Run the container for example with always restart option to make sure it will auto resume after host/daemon recycle:
docker run -d -t -i --restart always --name <nameOfContainer> <nameOfContainer> /bin/bash
Side note: In my opinion reasonable is to start only cron service leaving container as clean as possible then just modify crontab or cron.hourly, .daily etc... with corresponding checkup/monitoring scripts. Reason is You rely only on one daemon and in case of changes it is easier with ansible or puppet to redistribute cron scripts instead of track services that start at boot.
You could use a literal eval:
>>> ast.literal_eval('0xdeadbeef')
3735928559
Or just specify the base as argument to int
:
>>> int('deadbeef', 16)
3735928559
A trick that is not well known, if you specify the base 0
to int
, then Python will attempt to determine the base from the string prefix:
>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100
I've built a tool that does exactly that - qnm
node_modules
directory.Install it using:
npm i --global qnm
and run:
qnm [module]
for example:
> qnm lodash
lodash
+-- 4.17.5
+-- cli-table2
¦ +-- 3.10.1
+-- karma
+-- 3.10.1
Which means we have lodash
installed in the root of the node_modules
and two other copies in the node_modules
of cli-table2
and karma
.
It's really fast, and has some nice features like tab completion and match search.
I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.
CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data
SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid;
You can use a DecimalFormat, or String.format("%.2f", a);
Other alternatives to an installer and gacutil are GUI tools like Gac Manager or GACAdmin. Or if you like PowerShell you could use PowerShell GAC from which I am the author.
You can use jquery function.
<form name='add'>
<input type='text' name='stud_name' id="stud_name" value=""/>
Age: <select name='age' id="age">
<option value='1' stud_name='sre'>23</option>
<option value='2' stud_name='sam'>24</option>
<option value='5' stud_name='john'>25</option>
</select>
<input type='submit' name='submit'/>
</form>
jquery code :
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function() {
$("#age").change(function(){
var option = $('option:selected', this).attr('stud_name');
$('#stud_name').val(option);
});
});
</script>
Try jcabi-xml, with a one liner:
Node node = new XMLDocument("<node>value</node>").node();
For a group of inputs you can use an improved version based in @mikemaccana's answer
$.fn.isValid = function(){
var validate = true;
this.each(function(){
if(this.checkValidity()==false){
validate = false;
}
});
};
now you can use this to verify if the form is valid:
if(!$(".form-control").isValid){
return;
}
You could use the same technique to get all the error messages:
$.fn.getVelidationMessage = function(){
var message = "";
var name = "";
this.each(function(){
if(this.checkValidity()==false){
name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
}
})
return message;
}
If you want to use the GUI... click/double-click the table and select the Data
tab. Click in the column value you want to set to (null)
. Select the value and delete it. Hit the commit button (green check-mark button). It should now be null.
More info here:
How to use the SQL Worksheet in SQL Developer to Insert, Update and Delete Data
https://stackoverflow.com/a/37191719/75579 answer stopped working for me in Android 7 somehow. So I have to do it the manual way, so I want to share it.
Put this snippet of code in your ~/.bash_profile
or ~/.profile
file:
snap_screen() {
if [ $# -eq 0 ]
then
name="screenshot.png"
else
name="$1.png"
fi
adb shell screencap -p /sdcard/$name
adb pull /sdcard/$name
adb shell rm /sdcard/$name
curr_dir=pwd
echo "save to `pwd`/$name"
}
Run source ~/.bash_profile
or source ~/.profile
command,
Usage without specifying filename:
$ snap_screen
11272 KB/s (256237 bytes in 0.022s)
Saved to /Users/worker8/desktop/screenshot.png
Usage with a filename:
$ snap_screen mega_screen_capture
11272 KB/s (256237 bytes in 0.022s)
Saved to /Users/worker8/desktop/mega_screen_capture.png
Hope it helps!
** This will not work if multiple devices are plugged in
Using underscore unique lib following is working for me, I m making list unique on the based of _id then returning String value of _id:
var uniqueEntities = _.uniq(entities, function (item, key, a) {
return item._id.toString();
});
I've actually used your first approach with quite some success, but in a slightly different ways that I think would solve some of your problems:
Keep the entire schema and scripts for creating it in source control so that anyone can create the current database schema after a check out. In addition, keep sample data in data files that get loaded by part of the build process. As you discover data that causes errors, add it to your sample data to check that errors don't re-emerge.
Use a continuous integration server to build the database schema, load the sample data, and run tests. This is how we keep our test database in sync (rebuilding it at every test run). Though this requires that the CI server have access and ownership of its own dedicated database instance, I say that having our db schema built 3 times a day has dramatically helped find errors that probably would not have been found till just before delivery (if not later). I can't say that I rebuild the schema before every commit. Does anybody? With this approach you won't have to (well maybe we should, but its not a big deal if someone forgets).
For my group, user input is done at the application level (not db) so this is tested via standard unit tests.
Loading Production Database Copy:
This was the approach that was used at my last job. It was a huge pain cause of a couple of issues:
Mocking Database Server:
We also do this at my current job. After every commit we execute unit tests against the application code that have mock db accessors injected. Then three times a day we execute the full db build described above. I definitely recommend both approaches.
Register org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
as the message converter and return the object directly from the method.
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"/>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
and the controller:
@RequestMapping(method=RequestMethod.GET, value="foo/bar")
public @ResponseBody Object fooBar(){
return myService.getActualObject();
}
This requires the dependency org.springframework:spring-webmvc
.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
All of the following services should be running,for successful connectivity: SQL Full test filter Daemon, SQL server(SQLEXPRESS), SQL Server Agent(SQLEXPRESS), SQL Server Browser, SQL server reporting service and SQL Server VSS Writer
You can use a HTML table:
<table>
<tr>
<td>
<div id="bloc1">your content</div>
</td>
<td>
<div id="bloc2">your content</div>
</td>
</tr>
</table>
<table class="table border">
<thead>
<tr>
<ng-container *ngFor="let column of columns; let i = index">
<th>{{ column }}</th>
</ng-container>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of groups;let i = index">
<td>{{row.name}}</td>
<td>{{row.items}}</td>
<td >
<span class="status" *ngFor="let item of row.Status | slice:0:2;let j = index">
{{item.name}}
</span><span *ngIf = "i < 2" class="dots" (mouseenter) ="onHover(i)" (mouseleave) ="onHover(-1)">.....</span> <span [hidden] ="test" *ngIf = "i == hoverIndex" class="hover-details"><span *ngFor="let item of row.Status;let j = index">
{{item.name}}
</span></span>
</td>
</tr>
</tbody>
</table>
<p *ngFor="let group of usersg"><input type="checkbox" [checked]="isChecked(group.id)" value="{{group.id}}" />{{group.name}}</p>
<p><select [(ngModel)]="usersr_selected.id">
<option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option>
</select></p>
import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
getListData: any;
dataGroup: FormGroup;
selectedGroups: string[];
submitted = false;
usersg_checked:any;
usersr_selected:any;
dotsh:any;
hoverIndex:number = -1;
groups:any;
test:any;
constructor(private formBuilder: FormBuilder) {
}
onHover(i:number){
this.hoverIndex = i;
}
columns = ["name", "Items","status"];
public usersr = [{
"id": 1,
"name": "test1"
}, {
"id": 2,
"name": "test2",
}];
ngOnInit() {
this.test = false;
this.groups=[{
"id": 1,
"name": "pencils",
"items": "red pencil",
"Status": [{
"id": 1,
"name": "green"
}, {
"id": 2,
"name": "red"
}, {
"id": 3,
"name": "yellow"
}],
"loc": [{
"id": 1,
"name": "loc 1"
}, {
"id": 2,
"name": "loc 2"
}, {
"id": 3,
"name": "loc 3"
}]
},
{
"id": 2,
"name": "rubbers",
"items": "big rubber",
"Status": [{
"id": 1,
"name": "green"
}, {
"id": 2,
"name": "red"
}],
"loc": [{
"id": 1,
"name": "loc 2"
}, {
"id": 2,
"name": "loc 3"
}]
},
{
"id": 3,
"name": "rubbers1",
"items": "big rubber1",
"Status": [{
"id": 1,
"name": "green"
}],
"loc": [{
"id": 1,
"name": "loc 2"
}, {
"id": 2,
"name": "loc 3"
}]
}
];
this.dotsh = false;
console.log(this.groups.length);
this.usersg_checked = [{
"id": 1,
"name": "test1"
}, {
"id": 2,
"name": "test2",
}];
this.usersr_selected = {"id":1,"name":"test2"};;
this.selectedGroups = [];
this.dataGroup = this.formBuilder.group({
email: ['', Validators.required]
});
}
isChecked(id) {
console.log(this.usersg_checked);
return this.usersg_checked.some(item => item.id === id);
}
get f() { return this.dataGroup.controls; }
onCheckChange(event) {
if (event.target.checked) {
this.selectedGroups.push(event.target.value);
} else {
const index = this.selectedGroups.findIndex(item => item === event.target.value);
if (index !== -1) {
this.selectedGroups.splice(index, 1);
}
}
}
getFormData(value){
this.submitted = true;
// stop here if form is invalid
if (this.dataGroup.invalid) {
return;
}
value['groups'] = this.selectedGroups;
console.log(value);
}
}
.status{
border: 1px solid;
border-radius: 4px;
padding: 0px 10px;
margin-right: 10px;
}
.hover-details{
position: absolute;
border: 1px solid;
padding: 10px;
width: 164px;
text-align: left;
border-radius: 4px;
}
.dots{
position:relative;
}
You could use something like a set from Programming in Lua:
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
Then you could put your list in the Set and test for membership:
local items = Set { "apple", "orange", "pear", "banana" }
if items["orange"] then
-- do something
end
Or you could iterate over the list directly:
local items = { "apple", "orange", "pear", "banana" }
for _,v in pairs(items) do
if v == "orange" then
-- do something
break
end
end
render() {
return (
<View style={styles.container}>
(() => {
if (this.state == 'news') {
return <Text>data</Text>
}
else
return <Text></Text>
})()
</View>
)
}
What is the difference between Git and GitHub?
Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.
Is git saving every repository locally (in the user's machine) and in GitHub?
If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.
How does Git compare to a backup system such as Time Machine?
Git is specifically designed and optimized for source code.
Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?
Exactly.
If are not collaborating and you are already using a backup system why would you use Git?
See #4.
If you need just update your records in energydata
based on data in temp_energydata
, assuming that temp_enerydata
doesn't contain any new records, then try this:
UPDATE e SET e.kWh = t.kWh
FROM energydata e INNER JOIN
temp_energydata t ON e.webmeterID = t.webmeterID AND
e.DateTime = t.DateTime
Here is working sqlfiddle
But if temp_energydata
contains new records and you need to insert it to energydata
preferably with one statement then you should definitely go with the answer that Bacon Bits gave.
sharing in Es6 full read and write localStorage Example with support check
const LOCAL_STORAGE_KEY = 'tds_app_localdata';
const isSupported = () => {
try {
localStorage.setItem('supported', '1');
localStorage.removeItem('supported');
return true;
} catch (error) {
return false;
}
};
const writeToLocalStorage =
components =>
(isSupported ?
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(components))
: components);
const isEmpty = component => (!component || Object.keys(component).length === 0);
const readFromLocalStorage =
() => (isSupported ? JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || {} : null);
This will make sure your keys are set and retrieved properly on all browsers.
For 'Bad' red:
For 'Good' green:
For 'Neutral' yellow:
for people still not able to solve it, this answer helped me. stackoverflow answer: 34558264
TLDR;
one needs to set {withCredentials: true}
in both GET request as well the POST request (getting the cookie) for both axios as well as fetch.
You likely don't need to reinstall ggplot2
Solution: go back to plot that didn't work previously. Take the below console output for example. The figure margins (the window that displays your plots) were too small to display the pairs(MinusInner) plot. Then when I tried to make the next qplot, R was still hung up on previous error.
pairs(MinusInner) Error in plot.new() : figure margins too large qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot") Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) : invalid graphics state
I fixed the first error by expanding the plot window and rerunning the pairs(MinusInner) plot. Then blam, it worked.
pairs(MinusInner) qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot")
Use utf8_encode()
Man page can be found here http://php.net/manual/en/function.utf8-encode.php
Also read this article from Joel on Software. It provides an excellent explanation if what Unicode is and how it works. http://www.joelonsoftware.com/articles/Unicode.html
This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.
new_index = max(0, min(new_index, len(mylist)-1))
UPDATE t1
LEFT JOIN
t2
ON t2.id = t1.id
SET t1.col1 = newvalue
WHERE t2.id IS NULL
Note that for a SELECT
it would be more efficient to use NOT IN
/ NOT EXISTS
syntax:
SELECT t1.*
FROM t1
WHERE t1.id NOT IN
(
SELECT id
FROM t2
)
See the article in my blog for performance details:
LEFT JOIN
compared to NOT IN
Unfortunately, MySQL
does not allow using the target table in a subquery in an UPDATE
statement, that's why you'll need to stick to less efficient LEFT JOIN
syntax.
Assuming i'm in a container with 15px padding, this is what i always use for the inner part:
width:auto;
right:15px;
left:15px;
That will stretch the inner part to whatever width it should be less the 15px either side.
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
Difference between show() and css({'display':'block'})
Assuming you have this at the beginning:
<span id="thisElement" style="display: none;">Foo</span>
when you call:
$('#thisElement').show();
you will get:
<span id="thisElement" style="">Foo</span>
while:
$('#thisElement').css({'display':'block'});
does:
<span id="thisElement" style="display: block;">Foo</span>
so, yes there's a difference.
Difference between hide() and css({'display':'none'})
same as above but change these into hide() and display':'none'......
Another difference
When .hide()
is called the value of the display property is saved in jQuery's data cache, so when .show()
is called, the initial display value is restored!
This is a solution suggested by the MySQl manual:
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:
Create a table to hold the sequence counter and initialize it:
mysql> CREATE TABLE sequence (id INT NOT NULL); mysql> INSERT INTO sequence VALUES (0);
Use the table to generate sequence numbers like this:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1); mysql> SELECT LAST_INSERT_ID();
The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 23.8.7.37, “mysql_insert_id()”.
You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.
First, remove all packages from dependencies
and devDependencies
in package.json
Second, run npm install
That simple.
When mysql was installed with Homebrew, the following command did the trick for me:
brew services stop mysql
Template refs section tells how this has been unified:
ref="myEl"
; :ref=
with a v-for
const myEl = ref(null)
and expose it from setup
The reference carries the DOM element from mounting onwards.
This will unstage all files you might have staged with git add
:
git reset
This will revert all local uncommitted changes (should be executed in repo root):
git checkout .
You can also revert uncommitted changes only to particular file or directory:
git checkout [some_dir|file.txt]
Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory):
git reset --hard HEAD
This will remove all local untracked files, so only git tracked files remain:
git clean -fdx
WARNING:
-x
will also remove all ignored files, including ones specified by.gitignore
! You may want to use-n
for preview of files to be deleted.
To sum it up: executing commands below is basically equivalent to fresh git clone
from original source (but it does not re-download anything, so is much faster):
git reset
git checkout .
git clean -fdx
Typical usage for this would be in build scripts, when you must make sure that your tree is absolutely clean - does not have any modifications or locally created object files or build artefacts, and you want to make it work very fast and to not re-clone whole repository every single time.
Just tested and this works:
public class Coordinates {
byte red;
@JsonProperty("r")
public byte getR() {
return red;
}
@JsonProperty("red")
public void setRed(byte red) {
this.red = red;
}
}
The idea is that method names should be different, so jackson parses it as different fields, not as one field.
Here is test code:
Coordinates c = new Coordinates();
c.setRed((byte) 5);
ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(c));
Coordinates r = mapper.readValue("{\"red\":25}",Coordinates.class);
System.out.println("Deserialization: " + r.getR());
Result:
Serialization: {"r":5}
Deserialization: 25
In my case, I have several tasks I want to execute in parallel, but I need to do something different with the result of those tasks.
function wait(ms, data) {
console.log('Starting task:', data, ms);
return new Promise(resolve => setTimeout(resolve, ms, data));
}
var tasks = [
async () => {
var result = await wait(1000, 'moose');
// do something with result
console.log(result);
},
async () => {
var result = await wait(500, 'taco');
// do something with result
console.log(result);
},
async () => {
var result = await wait(5000, 'burp');
// do something with result
console.log(result);
}
]
await Promise.all(tasks.map(p => p()));
console.log('done');
And the output:
Starting task: moose 1000
Starting task: taco 500
Starting task: burp 5000
taco
moose
burp
done
Using jQuery!
var demoShow = function(){
$("#p2").hide();
}
But I would recommend you give an id to your button on which you want an action to happen. For example:
<input type="button" id="p1" value="edit" />
<input type="button" id="p2" value="submit" name="submit" />
<script type="text/javascript">
$("#p1").click(function(){
$("#p2").hide();
});
</script>
To show it again you can simply write: $("#p2").show();
Since you don't mention a plot package , I propose here using Lattice
version( I think there is more ggplot2 answers than lattice ones, at least since I am here in SO).
## reshaping the data( similar to the other answer)
library(reshape2)
dat.m <- melt(TestData,id.vars='Label')
library(lattice)
bwplot(value~Label |variable, ## see the powerful conditional formula
data=dat.m,
between=list(y=1),
main="Bad or Good")
System.out.printf("%.2f", number);
BUT, this will round the number to the nearest decimal point you have mentioned.(As in your case you will get 3.14 since rounding 3.14159 to 2 decimal points will be 3.14)
Since the function printf will round the numbers the answers for some other numbers may look like this,
System.out.printf("%.2f", 3.14136); -> 3.14
System.out.printf("%.2f", 3.14536); -> 3.15
System.out.printf("%.2f", 3.14836); -> 3.15
If you just need to cutoff the decimal numbers and limit it to a k
decimal numbers without rounding,
lets say k = 2.
System.out.printf("%.2f", 3.14136 - 0.005); -> 3.14
System.out.printf("%.2f", 3.14536 - 0.005); -> 3.14
System.out.printf("%.2f", 3.14836 - 0.005); -> 3.14
Another option is the use <th>
instead of <td>
. <th>
defaults to center; <td>
defaults to left.
You're so close!
Change
plot "print_1012720" using 1:2 title "Flow 1", \
plot "print_1058167" using 1:2 title "Flow 2", \
plot "print_193548" using 1:2 title "Flow 3", \
plot "print_401125" using 1:2 title "Flow 4", \
plot "print_401275" using 1:2 title "Flow 5", \
plot "print_401276" using 1:2 title "Flow 6"
to
plot "print_1012720" using 1:2 title "Flow 1", \
"print_1058167" using 1:2 title "Flow 2", \
"print_193548" using 1:2 title "Flow 3", \
"print_401125" using 1:2 title "Flow 4", \
"print_401275" using 1:2 title "Flow 5", \
"print_401276" using 1:2 title "Flow 6"
The error arises because gnuplot is trying to interpret the word "plot" as the filename to plot, but you haven't assigned any strings to a variable named "plot" (which is good – that would be super confusing).
If you want to create static files, you can use Node.js File System Library to do that. But if you are looking for a way to create dynamic files as a result of your database or similar queries then you will need a template engine like SWIG. Besides these options you can always create HTML files as you would normally do and serve them over Node.js. To do that, you can read data from HTML files with Node.js File System and write it into response. A simple example would be:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile(req.params.filepath, function (err, content) {
if(!err) {
res.end(content);
} else {
res.end('404');
}
}
}).listen(3000);
But I suggest you to look into some frameworks like Express for more useful solutions.
Looks like your depth
variable is unset. This means that the expression [ $depth -eq $zero ]
becomes [ -eq 0 ]
after bash substitutes the values of the variables into the expression. The problem here is that the -eq
operator is incorrectly used as an operator with only one argument (the zero), but it requires two arguments. That is why you get the unary operator error message.
EDIT: As Doktor J mentioned in his comment to this answer, a safe way to avoid problems with unset variables in checks is to enclose the variables in ""
. See his comment for the explanation.
if [ "$depth" -eq "0" ]; then
echo "false";
exit;
fi
An unset variable used with the [
command appears empty to bash. You can verify this using the below tests which all evaluate to true
because xyz
is either empty or unset:
if [ -z ] ; then echo "true"; else echo "false"; fi
xyz=""; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi
unset xyz; if [ -z "$xyz" ] ; then echo "true"; else echo "false"; fi
From Node 10.5 there is now multi threading support, but it is experimental. Hope this will become stable soon.
Checkout following resources :
Update:
From Node v11.7.0 onward, you do not have to use --experimental-worker
flag.
Release note: https://nodejs.org/en/blog/release/v11.7.0/
I received this same error when I made a backup copy of the node_modules
folder in the same directory. I was in the process of trying to solve a different build error when this occurred. I hope this scenario helps someone. Remove the backup folder and the build will complete.
SHOW CREATE PROCEDURE <name>
Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE
statement. Swap PROCEDURE
for FUNCTION
for a stored function.
i have solve this problem several times using the same steps :
1- Close Eclipse.
2- Restart your phone.
3- End adb.exe process in Task Manager (Windows). In Mac, force close in Activity Monitor.
4- Issue kill and start command in \platform-tools\
C:\sdk\platform-tools>adb kill-server
C:\sdk\platform-tools>adb start-server
5- If it says something like 'started successfully', you are good.
but now it's doesn't work cause i have an anti-virus called "Baidu", this program have run "Baidu ADB server", finally i turn this process off and retry above steps it's work properly.
Or use a cast with split to uniform type of str
unique, counts = numpy.unique(str(a).split(), return_counts=True)
Ideally, I would use a construct like this instead:
for (std::vector<your_type>::const_iterator i = things.begin(); i != things.end(); ++i)
{
// if you ever need the distance, you may call std::distance
// it won't cause any overhead because the compiler will likely optimize the call
size_t distance = std::distance(things.begin(), i);
}
This a has the neat advantage that your code suddenly becomes container agnostic.
And regarding your problem, if some library you use requires you to use int
where an unsigned int
would better fit, their API is messy. Anyway, if you are sure that those int
are always positive, you may just do:
int int_distance = static_cast<int>(distance);
Which will specify clearly your intent to the compiler: it won't bug you with warnings anymore.
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
Return value:
READ_COMMITTED_SNAPSHOT
option is ON. Read operations under the READ COMMITTED
isolation level are based on snapshot scans and do not acquire locks.READ_COMMITTED_SNAPSHOT
option is OFF. Read operations under the READ COMMITTED
isolation level use Shared (S) locks.I could solve the issue simply by replacing the JPA api jar file which is located jboss7/modules/javax/persistence/api/main with 'hibernate-jpa-2.1-api'. also with updating module.xml in the directory.
Maybe this will help for beginners
<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8">
<title></title>
<link rel="icon" href="favicon.ico">
<link rel="stylesheet" href="custom.css">
</head>
<body>
<div ng-include src="'view/01.html'"></div>
<div ng-include src="'view/02.html'"></div>
<script src="angular.min.js"></script>
</body>
</html>
public static void main(String[] args) {
long a = 1111;
Long b = 1113L;
if(a == b.longValue())
{
System.out.println("Equals");
}else{
System.out.println("not equals");
}
}
or:
public static void main(String[] args) {
long a = 1111;
Long b = 1113L;
if(a == b)
{
System.out.println("Equals");
}else{
System.out.println("not equals");
}
}
Sssuming you have a parent Post
entity and a child PostComment
as illustrated in the following diagram:
If you call find
when you try to set the @ManyToOne
post
association:
PostComment comment = new PostComment();
comment.setReview("Just awesome!");
Post post = entityManager.find(Post.class, 1L);
comment.setPost(post);
entityManager.persist(comment);
Hibernate will execute the following statements:
SELECT p.id AS id1_0_0_,
p.title AS title2_0_0_
FROM post p
WHERE p.id = 1
INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)
The SELECT query is useless this time because we don’t need the Post entity to be fetched. We only want to set the underlying post_id Foreign Key column.
Now, if you use getReference
instead:
PostComment comment = new PostComment();
comment.setReview("Just awesome!");
Post post = entityManager.getReference(Post.class, 1L);
comment.setPost(post);
entityManager.persist(comment);
This time, Hibernate will issue just the INSERT statement:
INSERT INTO post_comment (post_id, review, id)
VALUES (1, 'Just awesome!', 1)
Unlike find
, the getReference
only returns an entity Proxy which only has the identifier set. If you access the Proxy, the associated SQL statement will be triggered as long as the EntityManager is still open.
However, in this case, we don’t need to access the entity Proxy. We only want to propagate the Foreign Key to the underlying table record so loading a Proxy is sufficient for this use case.
When loading a Proxy, you need to be aware that a LazyInitializationException
can be thrown if you try to access the Proxy reference after the EntityManager is closed.
I used this :D
HtmlElement script = this.WebNavegador.Document.CreateElement("SCRIPT");
script.SetAttribute("TEXT", "function GetNameFromBrowser() {" +
"return 'My name is David';" +
"}");
this.WebNavegador.Document.Body.AppendChild(script);
Then you can execute and get the result with:
string myNameIs = (string)this.WebNavegador.Document.InvokeScript("GetNameFromBrowser");
I hope to be helpful
'*' works as a modifier for the previous item. So 'abc*def' searches for 'ab' followed by 0 or more 'c's follwed by 'def'.
What you probably want is 'abc.*def' which searches for 'abc' followed by any number of characters, follwed by 'def'.
%S
seems to conform to The Single Unix Specification v2 and is also part of the current (2008) POSIX specification.
Equivalent C99 conforming format specifiers would be %s
and %ls
.
Use modern java.time
classes if you use java 8 or newer.
String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
Basil Bourque's answer is pretty good. But it's too long. Many people would have no patience to read it. Top 3 answers are too old and may mislead Java new bee .So I provide this short and modern answer for new coming devs. Hope this answer can reduce usage of terrible SimpleDateFormat
.
You can stash
and stash pop
the file:
git checkout branch1
git checkout branch2 file.py
git stash
git checkout branch1
git stash pop
I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone
Save your sorting order in a ViewState.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression,string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
Why you don't want to use existing sorting functionality? You can always customize it.
Sorting Data in a GridView Web Server Control at MSDN
Here is an example with customization:
If you already committed the changes than you would have to revert changes.
If you didn't commit yet, just do a clean checkout git checkout .
Setting \itemindent
for a new itemize environment solves the problem:
\newenvironment{beameritemize}
{ \begin{itemize}
\setlength{\itemsep}{1.5ex}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
\addtolength{\itemindent}{-2em} }
{ \end{itemize} }
none of that needed.... just go to:
now and load your csv file as-is. extra columns and all. it will slice and dice and use just the log & lat columns and plot it for you on google maps.
Swift version of the accepted answer for easy copy pasting:
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
scrollView.setContentOffset(bottomOffset, animated: true)
Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.
Do you have the key backed up somewhere?
Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.
First make this class :
package com.test;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
Then use this from your Activity :
EditText et = (EditText) findViewById(R.id.myEditText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "12")});
This will allow user to enter values from 1 to 12 only.
EDIT :
Set your edittext with android:inputType="number"
.
You can find more details at https://www.techcompose.com/how-to-set-minimum-and-maximum-value-in-edittext-in-android-app-development/.
Thanks.
It will work for that code sometimes need both properties
android:layout_gravity="center"
android:layout_centerHorizontal="true"
If you have a route like
[Route("nuclearreactors/{reactorId}")]
You need to use the exact same parameter name in the method e.g.
public ReactorModel GetReactor(reactorId)
{
...
}
If you do not pass the exact same parameter you may get the error "405 method not allowed" because the route will not match the request and WebApi will hit a different controller method with different allowed HTTP method.
Use HTML Form "elements" attribute:
$.each($("form").elements, function(){
console.log($(this));
});
Now it's not necessary to provide such names as "input, textarea, select ..." etc.
The accepted answer didn't work for me, here's what I used instead:
import paramiko
import os
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh.load_system_host_keys()
ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.connect("d.d.d.d", username="user", password="pass", port=22222)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("ls -alrt")
exit_code = ssh_stdout.channel.recv_exit_status() # handles async exit error
for line in ssh_stdout:
print(line.strip())
total 44
-rw-r--r--. 1 root root 129 Dec 28 2013 .tcshrc
-rw-r--r--. 1 root root 100 Dec 28 2013 .cshrc
-rw-r--r--. 1 root root 176 Dec 28 2013 .bashrc
...
Alternatively, you can use sshpass:
import subprocess
cmd = """ sshpass -p "myPas$" ssh [email protected] -p 22222 'my command; exit' """
print( subprocess.getoutput(cmd) )
References:
Notes:
ssh root@ip
) and accept the public key, this is many times the reason from not being able connect using paramiko
or other automated ssh
scripts.On newer versions of Windows (Windows 10 and Windows Server 2016) the tasks you create are located in C:\Windows\Tasks
. They will have the extension .job
For example if you create the task "DoWork" it will create the task in
C:\Windows\Tasks\DoWork.job
There is a function in scipy named scipy.signal.find_peaks_cwt
which sounds like is suitable for your needs, however I don't have experience with it so I cannot recommend..
http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html
If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:
Markup:
<a href="#" id="link1" >click</a>
Javascript:
$(document).ready(function(){
$("#link1").click(clickWithEvent); //Bind the click event to the link
});
function clickWithEvent(evt){
myFunc('p1', 'p2', 'p3');
function myFunc(p1,p2,p3){ //Defined as local function, but has access to evt
alert(evt.type);
}
}
Since the event ob
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
Usually you would do it something like this
public class Foo implements Runnable {
private volatile int value;
@Override
public void run() {
value = 2;
}
public int getValue() {
return value;
}
}
Then you can create the thread and retrieve the value (given that the value has been set)
Foo foo = new Foo();
Thread thread = new Thread(foo);
thread.start();
thread.join();
int value = foo.getValue();
tl;dr
a thread cannot return a value (at least not without a callback mechanism). You should reference a thread like an ordinary class and ask for the value.
txt_name.value
txt_name.onkeyup = e=> alert(txt_name.value);
_x000D_
<input type="text" id="txt_name" />
_x000D_
When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p
flag to mkdir
... Please update your Dockerfile with
RUN mkdir -p ...
I tested this and it's correct.
Max Number of default simultaneous persistent connections per server/proxy:
Firefox 2: 2
Firefox 3+: 6
Opera 9.26: 4
Opera 12: 6
Safari 3: 4
Safari 5: 6
IE 7: 2
IE 8: 6
IE 10: 8
Edge: 6
Chrome: 6
The limit is per-server/proxy, so your wildcard scheme will work.
FYI: this is specifically related to HTTP 1.1; other protocols have separate concerns and limitations (i.e., SPDY, TLS, HTTP 2).
You can try the following:
from haversine import haversine
haversine((45.7597, 4.8422),(48.8567, 2.3508), unit='mi')
243.71209416020253
Everything everyone is saying is correct so,
int[] aArray = {1,2,3};
List<int> list = aArray.OfType<int> ().ToList();
would turn aArray into a list, list. However the biggest thing that is missing from a lot of comments is that you need to have these 2 using statements at the top of your class
using System.Collections.Generic;
using System.Linq;
I hope this helps!
I assume you have proper xml encoding and matching with Schema.
If you still get this error, check code that unmarshalls the xml and input type you have used. Because XML documents declare their own encoding, it is preferable to create a StreamSource object from an InputStream instead of from a Reader, so that XML processor can correctly handle the declared encoding [Ref Book: Java in A Nutshell ]
Hope this helps!
Meanwhile, all the values above will only restrict the values to integer, so i use
/^[1-9][0-9\.]{0,15}$/
to allow float values too.
Look at placing your radio buttons in a GroupBox.
You can change it by going File
=> Settings
(Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance
, Now from Right Panel choose theme.
Android Studio 2.1
Preference -> Search for Appearance -> UI options , Click on DropDown Theme
Android 2.2
Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options
EDIT :
Import External Themes
You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the
.jar
file downloaded.
As I couldn't find a cloner that meets all my requirements in different projects, I created a deep cloner that can be configured and adapted to different code structures instead of adapting my code to meet the cloners requirements. Its achieved by adding annotations to the code that shall be cloned or you just leave the code as it is to have the default behaviour. It uses reflection, type caches and is based on fasterflect. The cloning process is very fast for a huge amount of data and a high object hierarchy (compared to other reflection/serialization based algorithms).
https://github.com/kalisohn/CloneBehave
Also available as a nuget package: https://www.nuget.org/packages/Clone.Behave/1.0.0
For example: The following code will deepClone Address, but only perform a shallow copy of the _currentJob field.
public class Person
{
[DeepClone(DeepCloneBehavior.Shallow)]
private Job _currentJob;
public string Name { get; set; }
public Job CurrentJob
{
get{ return _currentJob; }
set{ _currentJob = value; }
}
public Person Manager { get; set; }
}
public class Address
{
public Person PersonLivingHere { get; set; }
}
Address adr = new Address();
adr.PersonLivingHere = new Person("John");
adr.PersonLivingHere.BestFriend = new Person("James");
adr.PersonLivingHere.CurrentJob = new Job("Programmer");
Address adrClone = adr.Clone();
//RESULT
adr.PersonLivingHere == adrClone.PersonLivingHere //false
adr.PersonLivingHere.Manager == adrClone.PersonLivingHere.Manager //false
adr.PersonLivingHere.CurrentJob == adrClone.PersonLivingHere.CurrentJob //true
adr.PersonLivingHere.CurrentJob.AnyProperty == adrClone.PersonLivingHere.CurrentJob.AnyProperty //true
This is the perfect job for the query selector...
var Set1=document.querySelectorAll('input[type=button]'); // by type
var Set2=document.querySelectorAll('input[name=goButton]'); // by name
var Set3=document.querySelectorAll('input[value=Go]'); // by value
You can then loop through these collections to operate on elements found.
You need to locate the element and use getText() method to extract the text.
WebElement element = driver.findElement(By.id("customSelect_3"));
System.out.println(element.getText());
To Remove Special character
String t2 = "!@#$%^&*()-';,./?><+abdd";
t2 = t2.replaceAll("\\W+","");
Output will be : abdd.
This works perfectly.
You can only match to constants in switch statements.
Example:
switch (variable1)
{
case 1: // A hard-coded value
// Code
break;
default:
// Code
break;
}
Successful!
switch (variable1)
{
case variable2:
// Code
break;
default:
// Code
break;
}
CS0150 A constant value is expected.
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
ticker
on itYou need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
Use String#slice
, also aliased as []
.
a = "hello there"
a[1] #=> "e"
a[1,3] #=> "ell"
a[1..3] #=> "ell"
a[6..-1] #=> "there"
a[6..] #=> "there" (requires Ruby 2.6+)
a[-3,2] #=> "er"
a[-4..-2] #=> "her"
a[12..-1] #=> nil
a[-2..-4] #=> ""
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a["lo"] #=> "lo"
a["bye"] #=> nil
this is the solution that works for me...wrote it in another question as well: How to change shape color dynamically?
//get the image button by id
ImageButton myImg = (ImageButton) findViewById(R.id.some_id);
//get drawable from image button
GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();
//set color as integer
//can use Color.parseColor(color) if color is a string
drawable.setColor(color)
They look pretty much the same on Python 3.2.
As gnibbler pointed out, the first doesn't need to lookup dict
, which should make it a tiny bit faster.
>>> def literal():
... d = {'one': 1, 'two': 2}
...
>>> def constructor():
... d = dict(one='1', two='2')
...
>>> import dis
>>> dis.dis(literal)
2 0 BUILD_MAP 2
3 LOAD_CONST 1 (1)
6 LOAD_CONST 2 ('one')
9 STORE_MAP
10 LOAD_CONST 3 (2)
13 LOAD_CONST 4 ('two')
16 STORE_MAP
17 STORE_FAST 0 (d)
20 LOAD_CONST 0 (None)
23 RETURN_VALUE
>>> dis.dis(constructor)
2 0 LOAD_GLOBAL 0 (dict)
3 LOAD_CONST 1 ('one')
6 LOAD_CONST 2 ('1')
9 LOAD_CONST 3 ('two')
12 LOAD_CONST 4 ('2')
15 CALL_FUNCTION 512
18 STORE_FAST 0 (d)
21 LOAD_CONST 0 (None)
24 RETURN_VALUE
A third option, for a pipelined one-liner is to nest the -replaces:
PS> ("ABC" -replace "B","C") -replace "C","D"
ADD
And:
PS> ("ABC" -replace "C","D") -replace "B","C"
ACD
This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?
-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.
Please see:
help about_operators
This is the fastest and easiest way that I have found;
while (tableModel.getRowCount()>0)
{
tableModel.removeRow(0);
}
This clears the table lickety split and leaves it ready for new data.
This may become useful to someone in the future as the new framework, when setup through VS, gets a default web.config
, web.Debug.config
and web.Release.config
. In the web.release.config
you will find this line:
<compilation xdt:Transform="RemoveAttributes(debug)" />
this was seeming to override any inline changes I made. I commented this line out and we were gravy (in terms of seeing non-minified code in a "release" build)
I've combined some of the above answers to come up with this to ensure that a given path entry exists exactly as given with as much brevity as possible and no junk echos on the command line.
set myPath=<pathToEnsure | %1>
echo ;%PATH%; | find /C /I ";%myPath%;" >nul
if %ERRORLEVEL% NEQ 0 set PATH=%PATH%;%myPath%
I searched now over 2h to find a nicely way how to find duplicates in a list and how to remove them. Here is the simplest answer:
//Copy the string array with the filtered data of the analytics db into an list
// a list should be easier to use
List<string> list_filtered_data = new List<string>(analytics_db_filtered_data);
// Get distinct elements and convert into a list again.
List<string> distinct = list_filtered_data.Distinct().ToList();
The Output will look like this: Duplicated Elements will be removed in the new list called distinct!
A way that has worked for me personally, is using the recyclerview's adapter methods to deal with changes in it's items.
It would go in a way similar to this, create a method in your custom recycler's view somewhat like this:
public void modifyItem(final int position, final Model model) {
mainModel.set(position, model);
notifyItemChanged(position);
}
The chunks below work at least for sending an int over UDP.
int to byte array:
public byte[] intToBytes(int my_int) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeInt(my_int);
out.close();
byte[] int_bytes = bos.toByteArray();
bos.close();
return int_bytes;
}
byte array to int:
public int bytesToInt(byte[] int_bytes) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
int my_int = ois.readInt();
ois.close();
return my_int;
}
I don't know how was the plugin the time the question was asked (2010), but I faced the same problem today and solved it this way:
Give your select tag a name attribute. For example in this case
<select name="myselect">
Instead of working with the attribute value="default" in the tag option, disable the default option or set value="" as suggested by Andrew Coats
<option disabled="disabled">Choose...</option>
or
<option value="">Choose...</option>
Set the plugin validation rule
$( "#YOUR_FORM_ID" ).validate({
rules: {
myselect: { required: true }
}
});
or
<select name="myselect" class="required">
Obs: Andrew Coats' solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.
Hope it helps! :)
I've done this several different ways but the only way I've found that keeps the labels and corresponding text/input data on the same line and always wraps perfectly to the width of the parent is to use display:inline table.
CSS
.container {
display: inline-table;
padding-right: 14px;
margin-top:5px;
margin-bottom:5px;
}
.fieldName {
display: table-cell;
vertical-align: middle;
padding-right: 4px;
}
.data {
display: table-cell;
}
HTML
<div class='container'>
<div class='fieldName'>
<label>Student</label>
</div>
<div class='data'>
<input name="Student" />
</div>
</div>
<div class='container'>
<div class='fieldName'>
<label>Email</label>
</div>
<div class='data'>
<input name="Email" />
</div>
</div>
You can use valgrind
to debug it.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *x = malloc(100);
free(x);
free(x);
return 0;
}
[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ ./t1
*** glibc detected *** ./t1: double free or corruption (top): 0x00000000058f7010 ***
======= Backtrace: =========
/lib64/libc.so.6[0x3a3127245f]
/lib64/libc.so.6(cfree+0x4b)[0x3a312728bb]
./t1[0x400500]
/lib64/libc.so.6(__libc_start_main+0xf4)[0x3a3121d994]
./t1[0x400429]
======= Memory map: ========
00400000-00401000 r-xp 00000000 68:02 30246184 /home/sand/testbox/t1
00600000-00601000 rw-p 00000000 68:02 30246184 /home/sand/testbox/t1
058f7000-05918000 rw-p 058f7000 00:00 0 [heap]
3a30e00000-3a30e1c000 r-xp 00000000 68:03 5308733 /lib64/ld-2.5.so
3a3101b000-3a3101c000 r--p 0001b000 68:03 5308733 /lib64/ld-2.5.so
3a3101c000-3a3101d000 rw-p 0001c000 68:03 5308733 /lib64/ld-2.5.so
3a31200000-3a3134e000 r-xp 00000000 68:03 5310248 /lib64/libc-2.5.so
3a3134e000-3a3154e000 ---p 0014e000 68:03 5310248 /lib64/libc-2.5.so
3a3154e000-3a31552000 r--p 0014e000 68:03 5310248 /lib64/libc-2.5.so
3a31552000-3a31553000 rw-p 00152000 68:03 5310248 /lib64/libc-2.5.so
3a31553000-3a31558000 rw-p 3a31553000 00:00 0
3a41c00000-3a41c0d000 r-xp 00000000 68:03 5310264 /lib64/libgcc_s-4.1.2-20080825.so.1
3a41c0d000-3a41e0d000 ---p 0000d000 68:03 5310264 /lib64/libgcc_s-4.1.2-20080825.so.1
3a41e0d000-3a41e0e000 rw-p 0000d000 68:03 5310264 /lib64/libgcc_s-4.1.2-20080825.so.1
2b1912300000-2b1912302000 rw-p 2b1912300000 00:00 0
2b191231c000-2b191231d000 rw-p 2b191231c000 00:00 0
7ffffe214000-7ffffe229000 rw-p 7ffffffe9000 00:00 0 [stack]
7ffffe2b0000-7ffffe2b4000 r-xp 7ffffe2b0000 00:00 0 [vdso]
ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0 [vsyscall]
Aborted
[sand@PS-CNTOS-64-S11 testbox]$
[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck ./t1
==20859== Memcheck, a memory error detector
==20859== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20859== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20859== Command: ./t1
==20859==
==20859== Invalid free() / delete / delete[]
==20859== at 0x4A05A31: free (vg_replace_malloc.c:325)
==20859== by 0x4004FF: main (t1.c:8)
==20859== Address 0x4c26040 is 0 bytes inside a block of size 100 free'd
==20859== at 0x4A05A31: free (vg_replace_malloc.c:325)
==20859== by 0x4004F6: main (t1.c:7)
==20859==
==20859==
==20859== HEAP SUMMARY:
==20859== in use at exit: 0 bytes in 0 blocks
==20859== total heap usage: 1 allocs, 2 frees, 100 bytes allocated
==20859==
==20859== All heap blocks were freed -- no leaks are possible
==20859==
==20859== For counts of detected and suppressed errors, rerun with: -v
==20859== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$
[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck --leak-check=full ./t1
==20899== Memcheck, a memory error detector
==20899== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20899== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20899== Command: ./t1
==20899==
==20899== Invalid free() / delete / delete[]
==20899== at 0x4A05A31: free (vg_replace_malloc.c:325)
==20899== by 0x4004FF: main (t1.c:8)
==20899== Address 0x4c26040 is 0 bytes inside a block of size 100 free'd
==20899== at 0x4A05A31: free (vg_replace_malloc.c:325)
==20899== by 0x4004F6: main (t1.c:7)
==20899==
==20899==
==20899== HEAP SUMMARY:
==20899== in use at exit: 0 bytes in 0 blocks
==20899== total heap usage: 1 allocs, 2 frees, 100 bytes allocated
==20899==
==20899== All heap blocks were freed -- no leaks are possible
==20899==
==20899== For counts of detected and suppressed errors, rerun with: -v
==20899== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$
One possible fix:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *x = malloc(100);
free(x);
x=NULL;
free(x);
return 0;
}
[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ ./t1
[sand@PS-CNTOS-64-S11 testbox]$
[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck --leak-check=full ./t1
==20958== Memcheck, a memory error detector
==20958== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20958== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20958== Command: ./t1
==20958==
==20958==
==20958== HEAP SUMMARY:
==20958== in use at exit: 0 bytes in 0 blocks
==20958== total heap usage: 1 allocs, 1 frees, 100 bytes allocated
==20958==
==20958== All heap blocks were freed -- no leaks are possible
==20958==
==20958== For counts of detected and suppressed errors, rerun with: -v
==20958== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$
Check out the blog on using Valgrind Link
Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as "offline", or to log when they are done their session.
Historically, you would send an AJAX request in the beforeunload
function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.
Later came navigator.sendBeacon()
. By using the sendBeacon()
method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it's sent asynchronously, and it doesn't impact the loading of the next page.
Unless you are targeting only desktop users, sendBeacon()
should not be used with unload
or beforeunload
since these do not reliably fire on mobile devices. Instead you can listen to the visibilitychange
event. This event will fire every time your page is visible and the user switches tabs, switches apps, goes to the home screen, answers a phone call, navigates away from the page, closes the tab, refreshes, etc.
Here is an example of its usage:
document.addEventListener('visibilitychange', function() {
if (document.visibilityState == 'hidden') {
navigator.sendBeacon("/log.php", analyticsData);
}
});
When the user returns to the page, document.visibilityState
will change to 'visible'
, so you can also handle that event as well.
sendBeacon()
is supported in:
It is NOT currently supported in:
Here is a polyfill for sendBeacon() in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.
Update:
It might be worth mentioning that sendBeacon()
only sends POST
requests. If you need to send a request using any other method, an alternative would be to use the fetch API
with the keepalive
flag set to true
, which causes it to behave the same way as sendBeacon()
. Browser support for the fetch API is about the same.
fetch(url, {
method: ...,
body: ...,
headers: ...,
credentials: 'include',
mode: 'no-cors',
keepalive: true,
})
You have to set a reference to the workbook you're opening. Then you can do anything you want with that workbook by using its reference.
Dim wkb As Workbook
Set wkb = Workbooks.Open("Tire.xls") ' open workbook and set reference!
wkb.Sheets("Sheet1").Activate
wkb.Sheets("Sheet1").Cells(2, 1).Value = 123
Could even set a reference to the sheet, which will make life easier later:
Dim wkb As Workbook
Dim sht As Worksheet
Set wkb = Workbooks.Open("Tire.xls")
Set sht = wkb.Sheets("Sheet2")
sht.Activate
sht.Cells(2, 1) = 123
Others have pointed out that .Activate
may be superfluous in your case. You don't strictly need to activate a sheet before editing its cells. But, if that's what you want to do, it does no harm to activate -- except for a small hit to performance which should not be noticeable as long as you do it only once or a few times. However, if you activate many times e.g. in a loop, it will slow things down significantly, so activate should be avoided.
You can use a circular buffer :
Code
// buffer all data in a circular buffer of infinite size
CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
class1.putDataOnOutputStream(cbb.getOutputStream());
class2.processDataFromInputStream(cbb.getInputStream());
Maven dependency
<dependency>
<groupId>org.ostermiller</groupId>
<artifactId>utils</artifactId>
<version>1.07.00</version>
</dependency>
Mode details
In case if someone interests to pass data to dialog:
app.controller('ModalCtrl', function($scope, $modal) {
$scope.name = 'theNameHasBeenPassed';
$scope.showModal = function() {
$scope.opts = {
backdrop: true,
backdropClick: true,
dialogFade: false,
keyboard: true,
templateUrl : 'modalContent.html',
controller : ModalInstanceCtrl,
resolve: {} // empty storage
};
$scope.opts.resolve.item = function() {
return angular.copy(
{name: $scope.name}
); // pass name to resolve storage
}
var modalInstance = $modal.open($scope.opts);
modalInstance.result.then(function(){
//on ok button press
},function(){
//on cancel button press
console.log("Modal Closed");
});
};
})
var ModalInstanceCtrl = function($scope, $modalInstance, $modal, item) {
$scope.item = item;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
Demo Plunker
I'm reading the Pragmatic Programmers book "Groovy Recipes: Greasing the wheels of Java" by Scott Davis, Copyright 2008 and printed in April of the same year.
It's a bit out of date but the book makes it clear that Groovy is literally an extension of Java. I can write Java code that functions exactly like Java and rename the file *.groovy and it works fine. According to the book, the reverse is true if I include the requisite libraries. So far, experimentation seems to bear this out.
# reopen stdout file descriptor with write mode
# and 0 as the buffer size (unbuffered)
import io, os, sys
try:
# Python 3, open as binary, then wrap in a TextIOWrapper with write-through.
sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)
# If flushing on newlines is sufficient, as of 3.7 you can instead just call:
# sys.stdout.reconfigure(line_buffering=True)
except TypeError:
# Python 2
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Credits: "Sebastian", somewhere on the Python mailing list.
You can do this
Rails.application.routes.recognize_path "/your/path"
It works for me in rails 3.1.0.rc4
Paste it into your web page, just before the closing
</head>
tag.One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the
<head>
section, and we recommend placing the snippet at the bottom of the<head>
section for best performance
char *a = "stack overflow";
char *b = "new string, it's real";
int d = strlen(a);
b = malloc(d * sizeof(char));
b = strcpy(b,a);
printf("%s %s\n", a, b);
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:
hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');
This will do exactly as manually saving the figure.
source: http://www.mathworks.com/support/solutions/en/data/1-1PT49C/index.html?product=SL&solution=1-1PT49C
I could delete most of my branches but one looked like this and I could not delete it:
Turned out someone had set Branch permissions
under Settings
and from there unchecked Allow deleting this branch
. Hope this can help someone.
Update: Where settings are located from question in comment. Enter the repository that you wan't to edit to get the menu. You might need admin privileges to change this.
With Underscore.js, you could do
_.find( {"one": [1,2,3], "two": [4,5,6]} )
It will return [1,2,3]
something like this ? :
DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"
Is it what you are searching for?
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.
import urllib
def fetch_thing(url, params, method):
params = urllib.urlencode(params)
if method=='POST':
f = urllib.urlopen(url, params)
else:
f = urllib.urlopen(url+'?'+params)
return (f.read(), f.code)
content, response_code = fetch_thing(
'http://google.com/',
{'spam': 1, 'eggs': 2, 'bacon': 0},
'GET'
)
[Update]
Some of these answers are old. Today I would use the requests
module like the answer by robaple.
Unidirectional. Just add the inversedBy:(Foreign Column Name) to make it Bidirectional.
# config/yaml/ProductStore.dcm.yml
ProductStore:
type: entity
id:
product:
associationKey: true
store:
associationKey: true
fields:
status:
type: integer(1)
createdAt:
type: datetime
updatedAt:
type: datetime
manyToOne:
product:
targetEntity: Product
joinColumn:
name: product_id
referencedColumnName: id
store:
targetEntity: Store
joinColumn:
name: store_id
referencedColumnName: id
I hope it helps. See you.
Just enable NuGet Package Restore. Right click your solution > choose 'Enable NuGet Package Restore'.
This will create the .nuget folder with NuGet.Config file and fixed my problem.
For cases where you want to time the same stretch of code every time it gets executed (e.g. for profiling code that you think might be a bottleneck), here is a wrapper around (a slight modification to) Andreas Bonini's function that I find useful:
#ifdef _WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#endif
/*
* A simple timer class to see how long a piece of code takes.
* Usage:
*
* {
* static Timer timer("name");
*
* ...
*
* timer.start()
* [ The code you want timed ]
* timer.stop()
*
* ...
* }
*
* At the end of execution, you will get output:
*
* Time for name: XXX seconds
*/
class Timer
{
public:
Timer(std::string name, bool start_running=false) :
_name(name), _accum(0), _running(false)
{
if (start_running) start();
}
~Timer() { stop(); report(); }
void start() {
if (!_running) {
_start_time = GetTimeMicroseconds();
_running = true;
}
}
void stop() {
if (_running) {
unsigned long long stop_time = GetTimeMicroseconds();
_accum += stop_time - _start_time;
_running = false;
}
}
void report() {
std::cout<<"Time for "<<_name<<": " << _accum / 1.e6 << " seconds\n";
}
private:
// cf. http://stackoverflow.com/questions/1861294/how-to-calculate-execution-time-of-a-code-snippet-in-c
unsigned long long GetTimeMicroseconds()
{
#ifdef _WIN32
/* Windows */
FILETIME ft;
LARGE_INTEGER li;
/* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
* * to a LARGE_INTEGER structure. */
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
unsigned long long ret = li.QuadPart;
ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
ret /= 10; /* From 100 nano seconds (10^-7) to 1 microsecond (10^-6) intervals */
#else
/* Linux */
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long long ret = tv.tv_usec;
/* Adds the seconds (10^0) after converting them to microseconds (10^-6) */
ret += (tv.tv_sec * 1000000);
#endif
return ret;
}
std::string _name;
long long _accum;
unsigned long long _start_time;
bool _running;
};
Edit
A better way to do this is:
Create your own less file as a main less file ( like bootstrap.less ).
Import all bootstrap less files you need. (in this case, you just need to Import all responsive less files but responsive-1200px-min.less
)
If you need to modify anything in original bootstrap less file, you just need to write your own less to overwrite bootstrap's less code. (Just remember to put your less code/file after @import { /* bootstrap's less file */ };
).
Original
I have the same problem. This is how I fixed it.
Find the media query:
@media (max-width:1200px) ...
Remove it. (I mean the whole thing , not just @media (max-width:1200px)
)
Since the default width of Bootstrap is 940px, you don't need to do anything.
If you want to have your own max-width
, just modify the css rule in the media query that matches your desired width.
For 64-bit windows
install using wheel
pip install wheel download from http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
For python 3.x:
pip install mysqlclient-xxxxxxxxx-win_amd64.whl
For python 2.7:
pip install mysqlclient-xxxxxxxxx-win_amd64.whl
The {% csrf_token %}
put in html templates inside <form></form>
translates to something like:
<input type='hidden' name='csrfmiddlewaretoken' value='Sdgrw2HfynbFgPcZ5sjaoAI5zsMZ4wZR' />
so why not just grep it in your JS like this:
token = $("#change_password-form").find('input[name=csrfmiddlewaretoken]').val()
and then pass it e.g doing some POST, like:
$.post( "/panel/change_password/", {foo: bar, csrfmiddlewaretoken: token}, function(data){
console.log(data);
});
A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):
def spawn_as_administrator():
""" Spawn ourself with administrator rights and wait for new process to exit
Make the new process use the same console as the old one.
Raise Exception() if we could not get a handle for the new re-run the process
Raise pywintypes.error() if we could not re-spawn
Return the exit code of the new process,
or return None if already running the second admin process. """
#pylint: disable=no-name-in-module,import-error
import win32event, win32api, win32process
import win32com.shell.shell as shell
if '--admin' in sys.argv:
return None
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + ['--admin'])
SEE_MASK_NO_CONSOLE = 0x00008000
SEE_MASK_NOCLOSE_PROCESS = 0x00000040
process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS)
hProcess = process['hProcess']
if not hProcess:
raise Exception("Could not identify administrator process to install drivers")
# It is necessary to wait for the elevated process or else
# stdin lines are shared between 2 processes: they get one line each
INFINITE = -1
win32event.WaitForSingleObject(hProcess, INFINITE)
exitcode = win32process.GetExitCodeProcess(hProcess)
win32api.CloseHandle(hProcess)
return exitcode
I'd add that in case of really odd behavior - where you spend a couple of hours saying WTF - try manually deleting the /webapps/yourwebapp/WEB-INF/classes
directory. A java source file that was moved to another package will not have its compiled class file deleted - at least in the case of an exploded web-application on TC. This can seriously drive you crazy with unpredictable behavior, especially with an annotated servlet.
"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.
The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.
In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo is the shared repo. If CI was on another box, it would have to use the "deploy" goal.
<br>
worked for me.
Try this....
HTML inline
onKeydown="Javascript: if (event.keyCode==13) fnsearch();"
or
onkeypress="Javascript: if (event.keyCode==13) fnsearch();"
JavaScript
<script>
function fnsearch()
{
alert('you press enter');
}
</script>
//the following code checks if your radio button having name like 'yourRadioName'
//is checked or not
$(document).ready(function() {
if($("input:radio[name='yourRadioName']").is(":checked")) {
//its checked
}
});
Also to shed some light, it is important to know that var-arg parameters are limited to one and you can't have several var-art params. For example this is illigal:
public void myMethod(String... strings, int ... ints){
// method body
}
From the docs:
public Form createNamed(string|FormTypeInterface $type, string $name, mixed $data = null, array $options = array())
mixed $data = null is the default options. So for example I have a field called status and I implemented it as so:
$default = array('Status' => 'pending');
$filter_form = $this->get('form.factory')->createNamedBuilder('filter', 'form', $default)
->add('Status', 'choice', array(
'choices' => array(
'' => 'Please Select...',
'rejected' => 'Rejected',
'incomplete' => 'Incomplete',
'pending' => 'Pending',
'approved' => 'Approved',
'validated' => 'Validated',
'processed' => 'Processed'
)
))->getForm();
For Ubuntu 18.04 and mysql 5.7
step 1: sudo mkdir /var/run/mysqld;
step 2: sudo chown mysql /var/run/mysqld
step 3: sudo mysqld_safe --skip-grant-tables
& quit (use quit if its
stuck )
login to mysql without password
step 4: sudo mysql --user=root mysql
step 5: SELECT user,authentication_string,plugin,host FROM mysql.user;
step 6: ALTER USER 'root'@'localhost' IDENTIFIED WITH
mysql_native_password BY 'root'
now login with
mysql -u root -p <root>
Cron is a time-based scheduling service in Linux / Unix-like computer operating systems. Cron job are used to schedule commands to be executed periodically. You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron./* directories. It also checks the /var/spool/cron/ directory.
In the following example, the crontab command shown below will activate the cron tasks automatically every ten minutes:
*/10 * * * * /usr/bin/php /opt/test.php
In the above sample, the */10 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every "ten" minute. The other figures represent, respectively, hour, day, month and day of the week.
*
is a wildcard, meaning "every time".
Start with finding out your PHP binary by typing in command line:
whereis php
The output should be something like:
php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz
Specify correctly the full path in your command.
crontab -e
To see what you got in crontab.
To exit from vim editor without saving just click:
Shift+:
And then type q!
From java.util.Date JavaDocs:
The class Date represents a specific instant in time, with millisecond precision
and from the java.sql.Date JavaDocs:
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
So, the best approach is to use java.sql.Date if you are not in need of the time part
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
and the output is:
java.util.Date : Thu Apr 26 16:22:53 PST 2012
java.sql.Date : 2012-04-26
Python 3.7 is now available to be installed, but many packages have not been updated yet. As noted by another answer here, there is a GitHub issue tracking the progress of Anaconda building all the updated packages.
Until someone creates a conda package for Python 3.7, you can't install it. Unfortunately, something like 3500 packages show up in a search for "python" on Anaconda.org (https://anaconda.org/search?q=%22python%22) so I couldn't see if anyone has done that yet.
You might be able to build your own package, depending on what OS you want it for. You can start with the recipe that conda-forge uses to build Python: https://github.com/conda-forge/python-feedstock/
In the past, I think Continuum have generally waited until a stable release to push out packages for new Pythons, but I don't work there, so I don't know what their actual policy is.
In case you don't wish to set the toolbar as the action bar, you can use this:
val toggle = ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
toggle.isDrawerSlideAnimationEnabled = false
toggle.isDrawerIndicatorEnabled = false
toggle.setHomeAsUpIndicator(AppCompatResources.getDrawable(this, ...))
drawer!!.addDrawerListener(toggle)
toggle.setToolbarNavigationClickListener {
setDrawerOpened(!isDrawerOpened())
}
toggle.syncState()
fun setDrawerOpened(open: Boolean) {
if (open == drawerLayout.isDrawerOpen(GravityCompat.START))
return
if (open)
drawerLayout.openDrawer(GravityCompat.START)
else drawerLayout.closeDrawer(GravityCompat.START)
}