Changing com.android.tools.build:gradle:2.2.0-beta1
to com.android.tools.build:gradle:2.1.2
fixed it for me.
My Android Studio version is 2.1.2, perhaps that's why
Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx
(as noted already by @jewelsea above)
/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
On Ubuntu 14.04, it is in /usr/lib/jvm/default-java
.
In my case, I was using a dependency scoped as <scope>test</scope>
. This made the class available at development time but, by at compile time, I got this message.
Turn the class scope for <scope>provided</scope>
solved the problem.
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.Check your X Window environment variables using the "env" command.
It is hard to give a sensible solution since you are keen to avoid all sane approaches. Refactoring one line of code is the senible solution.
Note: Using -Xss sets the stack size of every thread and is a very bad idea.
Another approach is byte code manipulation to change the code as follows;
public static long fact(int n) {
return n < 2 ? n : n > 127 ? 0 : n * fact(n - 1);
}
given every answer for n > 127 is 0. This avoid changing the source code.
What's the memory profile of your machine ? e.g. if you run top
, how much free memory do you have ?
I suspect UnixProcess
performs a fork()
and it's simply not getting enough memory from the OS (if memory serves, it'll fork()
to duplicate the process and then exec()
to run the ls in the new memory process, and it's not getting as far as that)
EDIT: Re. your overcommit solution, it permits overcommitting of system memory, possibly allowing processes to allocate (but not use) more memory than is actually available. So I guess that the fork()
duplicates the Java process memory as discussed in the comments below. Of course you don't use the memory since the 'ls' replaces the duplicate Java process.
You can use SilverLight to launch an application from the browser (this will work only on IE and Firefox, newer versions of chrome don't support this)
Example code here
Use HTTPS:
change remote url to https:
git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git
and you are good to go:
git push
To ensure that the commits appear as performed by USERNAME, one can setup the user.name and user.email for this project, too:
git config user.name USERNAME
git config user.email [email protected]
It's the only construct in C that you can use to #define
a multistatement operation, put a semicolon after, and still use within an if
statement. An example might help:
#define FOO(x) foo(x); bar(x)
if (condition)
FOO(x);
else // syntax error here
...;
Even using braces doesn't help:
#define FOO(x) { foo(x); bar(x); }
Using this in an if
statement would require that you omit the semicolon, which is counterintuitive:
if (condition)
FOO(x)
else
...
If you define FOO like this:
#define FOO(x) do { foo(x); bar(x); } while (0)
then the following is syntactically correct:
if (condition)
FOO(x);
else
....
I'd have thought you need to use a MessageFormat rather than DecimalFormat. That should be more flexible.
I'm on OSX and have a macbook retina. Switching the USB port that my device was plugged into, for some reason, fixed my issue.
You can simply use the data-interval
attribute of the carousel
class.
It's default value is set to data-interval="3000"
i.e 3seconds.
All you need to do is set it to your desired requirements.
If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:
"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)
If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:
$isTall = $true
$isDark = $false
$isHandsome = $true
$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"
Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.
or just use for date strings 2015-05-20 or 2015.05.20
date.split(/\.|-/);
I could not use localStorage
directly in the Firefox (v27) console. I got the error:
[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: debugger eval code :: :: line 1" data: no]
What worked was:
window.content.localStorage
just use this and feelfree:
#define BitVal(data,y) ( (data>>y) & 1) /** Return Data.Y value **/
#define SetBit(data,y) data |= (1 << y) /** Set Data.Y to 1 **/
#define ClearBit(data,y) data &= ~(1 << y) /** Clear Data.Y to 0 **/
#define TogleBit(data,y) (data ^=BitVal(y)) /** Togle Data.Y value **/
#define Togle(data) (data =~data ) /** Togle Data value **/
for example:
uint8_t number = 0x05; //0b00000101
uint8_t bit_2 = BitVal(number,2); // bit_2 = 1
uint8_t bit_1 = BitVal(number,1); // bit_1 = 0
SetBit(number,1); // number = 0x07 => 0b00000111
ClearBit(number,2); // number =0x03 => 0b0000011
The way I use is:
git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master
git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705
But may have unexpected side-effects. See --mainline parent-number
option in git-scm.com/docs/git-revert
Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD
again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !
@Autowired + @Qualifier will work only with spring DI, if you want to use some other DI in future @Resource is good option.
other difference which I found very significant is @Qualifier does not support dynamic bean wiring, as @Qualifier does not support placeholder, while @Resource does it very well.
For example: if you have an interface with multiple implementations like this
interface parent {
}
@Service("actualService")
class ActualService implements parent{
}
@Service("stubbedService")
class SubbedService implements parent{
}
with @Autowired & @Qualifier you need to set specific child implementation like
@Autowired
@Qualifier("actualService") or
@Qualifier("stubbedService")
Parent object;
which does not provide placeholder while with @Resource you can put placeholder and use property file to inject specific child implementation like
@Resource(name="${service.name}")
Parent object;
where service.name is set in property file as
#service.name=actualService
service.name=stubbedService
Hope that helps someone :)
You might looking for the placeholder
attribute which will display a grey text in the input field while empty.
From Mozilla Developer Network:
A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.
However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )
And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/
Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/
It sounds like you want to use a transparent background, in which case you could try using the rgba()
function:
rgba(R, G, B, A)
R (red), G (green), and B (blue) can be either
<integer>
s or<percentage>
s, where the number 255 corresponds to 100%. A (alpha) can be a<number>
between 0 and 1, or a<percentage>
, where the number 1 corresponds to 100% (full opacity).RGBa example
rgba(51, 170, 51, .1) /* 10% opaque green */ rgba(51, 170, 51, .4) /* 40% opaque green */ rgba(51, 170, 51, .7) /* 70% opaque green */ rgba(51, 170, 51, 1) /* full opaque green */
A small example showing how rgba
can be used.
As of 2018, practically every browser supports the rgba
syntax.
The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same
No, it is not.
The one that is new to the N Developer Preview has this method signature:
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
The one that is supported by all Android versions, including N, has this method signature:
public boolean shouldOverrideUrlLoading(WebView view, String url)
So why should I do to make it work on all versions?
Override the deprecated one, the one that takes a String
as the second parameter.
public enum MyEvents
{
Event1
}
public class CustomEventArgs : EventArgs
{
public MyEvents MyEvents { get; set; }
}
private EventHandler<CustomEventArgs> onTrigger;
public event EventHandler<CustomEventArgs> Trigger
{
add
{
onTrigger += value;
}
remove
{
onTrigger -= value;
}
}
protected void OnTrigger(CustomEventArgs e)
{
if (onTrigger != null)
{
onTrigger(this, e);
}
}
Use varchar instead of VAR_CHAR and omit the comma in the last line i.e.phone INT NOT NULL );. The last line during creating table is kept "comma free". Ex:- CREATE TABLE COMPUTER ( Model varchar(50) ); Here, since we have only one column ,that's why there is no comma used during entire code.
I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
Hope this helps :)
Even if it's a late answer: I think this is still a very good question and IMHO Python (without additional libraries or toolkits like numpy) is still lacking a convenient method to access the indices of list elements according to a manually defined filter.
You could manually define a function, which provides that functionality:
def indices(list, filtr=lambda x: bool(x)):
return [i for i,x in enumerate(list) if filtr(x)]
print(indices([1,0,3,5,1], lambda x: x==1))
Yields: [0, 4]
In my imagination the perfect way would be making a child class of list and adding the indices function as class method. In this way only the filter method would be needed:
class MyList(list):
def __init__(self, *args):
list.__init__(self, *args)
def indices(self, filtr=lambda x: bool(x)):
return [i for i,x in enumerate(self) if filtr(x)]
my_list = MyList([1,0,3,5,1])
my_list.indices(lambda x: x==1)
I elaborated a bit more on that topic here: http://tinyurl.com/jajrr87
Use animation-delay
:
div {
width: 100px;
height: 100px;
background: red;
opacity: 0;
animation: fadeIn 3s;
animation-delay: 5s;
animation-fill-mode: forwards;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
You could also do a for loop as you would for an array but instead of array[i] you would use list.get(i)
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Source: http://www.java2s.com/Code/Java/File-Input-Output/Getextensionpathandfilename.htm
such an utility class :
class Filename {
private String fullPath;
private char pathSeparator, extensionSeparator;
public Filename(String str, char sep, char ext) {
fullPath = str;
pathSeparator = sep;
extensionSeparator = ext;
}
public String extension() {
int dot = fullPath.lastIndexOf(extensionSeparator);
return fullPath.substring(dot + 1);
}
public String filename() { // gets filename without extension
int dot = fullPath.lastIndexOf(extensionSeparator);
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(sep + 1, dot);
}
public String path() {
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
}
usage:
public class FilenameDemo {
public static void main(String[] args) {
final String FPATH = "/home/mem/index.html";
Filename myHomePage = new Filename(FPATH, '/', '.');
System.out.println("Extension = " + myHomePage.extension());
System.out.println("Filename = " + myHomePage.filename());
System.out.println("Path = " + myHomePage.path());
}
}
APC is going to be included in PHP 6, and I'd guess it has been chosen for good reason :)
It's fairly easy to install and certainly speeds things up.
What error is it giving you?
If you do exactly this:
data = json.loads('{"lat":444, "lon":555}')
Then:
data['lat']
SHOULD NOT give you any error at all.
I guess you can use the size
attribute. It works in all recent browsers.
<select name="courses" multiple="multiple" size="30" style="height: 100%;">
If you don't want to import anything, you can always write your own simple function as:
def RoundUP(num):
if num== int(num):
return num
return int(num + 1)
You can download a source RPMs and binary RPMs for RHEL6 / CentOS6 from here
This is a backport from the newest Fedora development source rpm to RHEL6 / CentOS6
The app project you downloaded may include a signed info in the file of build.gradle. If you saw codes like these:
buildTypes {
debug {
signingConfig signingConfigs.release
}
release {
signingConfig signingConfigs.release
}
}
you could delete them and try again.
Set the display property to none
as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px
in the media query with whatever the minimum px value is where your div should be visible.
#title_message {
display: none;
}
@media screen and (min-width: 768px) {
#title_message {
clear: both;
display: block;
float: left;
margin: 10px auto 5px 20px;
width: 28%;
}
}
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!
In my Case, it is because of having more than one connection string in your Solution. one for your current project and the other one for a startup project in your Solution. for more information please refer to Telerik report not working
here we have the same situation.
pip install -U pip
pip install -U cython
You could also use eval()
but JSON.parse()
is safer and easier way, so why would you?
good and works
var yourJsonObject = JSON.parse(json_as_text);
I don't see any reason why would you prefer to use eval
. It only puts your application at risk.
That said - this is also possible.
bad - but also works
var yourJsonObject = eval(json_as_text);
Why is eval
a bad idea?
Consider the following example.
Some third party or user provided JSON string data.
var json = `
[{
"adjacencies": [
{
"nodeTo": function(){
return "delete server files - you have been hacked!";
}(),
"nodeFrom": "graphnode1",
"data": {
"$color": "#557EAA"
}
}
],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode1",
"name": "graphnode1"
},{
"adjacencies": [],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode2",
"name": "graphnode2"
}]
`;
Your server-side script processes that data.
Using JSON.parse
:
window.onload = function(){
var placeholder = document.getElementById('placeholder1');
placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}
will throw:
Uncaught SyntaxError: Unexpected token u in JSON at position X.
Function will not get executed.
You are safe.
Using eval()
:
window.onload = function(){
var placeholder = document.getElementById('placeholder1');
placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}
will execute the function and return the text.
If I replace that harmless function with one that removes files from your website folder you have been hacked. No errors/warnings will get thrown in this example.
You are NOT safe.
I was able to manipulate a JSON text string so it acts as a function which will execute on the server.
eval(JSON)[0].adjacencies[0].nodeTo
expects to process a JSON string but, in reality, we just executed a function on our server.
This could also be prevented if we server-side check all user-provided data before passing it to an eval()
function but why not just use the built-in tool for parsing JSON and avoid all this trouble and danger?
so it's easy)))
Watch this...
var stuff = {};
$('input[type=checkbox]').each(function(i, e) {
stuff[i] = e.checked;
});
And you will have:
Object {0: true, 1: false, 2: false, 3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff['row'+i] = e.checked;
});
You will have:
Object {row0: true, row1: false, row2: false, row3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff[e.className+i] = e.checked;
});
You will have:
Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
Something like this??
Jsfiddle Demo
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.searchinput{
display:inline-block;vertical-align: bottom;
width:30%;padding: 5px;padding-right:27px;border:1px solid #ccc;
outline: none;
}
.clearspace{width: 20px;display: inline-block;margin-left:-25px;
}
.clear {
width: 20px;
transition: max-width 0.3s;overflow: hidden;float: right;
display: block;max-width: 0px;
}
.show {
cursor: pointer;width: 20px;max-width:20px;
}
form{white-space: nowrap;}
</style>
</head>
<body>
<form>
<input type="text" class="searchinput">
</form>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script> <script>
$(document).ready(function() {
$("input.searchinput").after('<span class="clearspace"><i class="clear" title="clear">✗</i></span>');
$("input.searchinput").on('keyup input',function(){
if ($(this).val()) {$(".clear").addClass("show");} else {$(".clear").removeClass("show");}
});
$('.clear').click(function(){
$('input.searchinput').val('').focus();
$(".clear").removeClass("show");
});
});
</script>
</body>
</html>
Here's an HTML5 alternative to homebrew: http://www.rgraph.net/ You might be able to reverse engineer their methods....
You might also consider something like Flot (http://code.google.com/p/flot/) or GCharts: (http://www.maxb.net/scripts/jgcharts/include/demo/#1) It's not quite as cool, but fully backwards compatible and scary easy to implement.
In my case I forgot to enable
app.use(express.json());
in my NodeJs server.
I would recommend not using onsubmit
and instead attaching an event in the script.
var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
submit.addEventListener("click", returnToPreviousPage);
} else {
submit.attachEvent("onclick", returnToPreviousPage);
}
Then use preventDefault()
(or returnValue = false
for older browsers).
function returnToPreviousPage (e) {
e = e || window.event;
// validation code
// if invalid
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw
alone does not produce the plot (at least with the qt backend).
The following works for me:
import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
#Suppose we know the x range
min_x = 0
max_x = 10
def on_launch(self):
#Set up plot
self.figure, self.ax = plt.subplots()
self.lines, = self.ax.plot([],[], 'o')
#Autoscale on unknown axis and known lims on the other
self.ax.set_autoscaley_on(True)
self.ax.set_xlim(self.min_x, self.max_x)
#Other stuff
self.ax.grid()
...
def on_running(self, xdata, ydata):
#Update data (with the new _and_ the old points)
self.lines.set_xdata(xdata)
self.lines.set_ydata(ydata)
#Need both of these in order to rescale
self.ax.relim()
self.ax.autoscale_view()
#We need to draw *and* flush
self.figure.canvas.draw()
self.figure.canvas.flush_events()
#Example
def __call__(self):
import numpy as np
import time
self.on_launch()
xdata = []
ydata = []
for x in np.arange(0,10,0.5):
xdata.append(x)
ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
self.on_running(xdata, ydata)
time.sleep(1)
return xdata, ydata
d = DynamicUpdate()
d()
I solve this by deleting all "PROVISIONING_PROFILE=..."
and "PROVISIONING_PROFILE[sdk=iphoneos*]" = ...
in project.pbxproj and restart Xcode and set provisioning profiles for the target again.
While editing include the id or primary key of the entity as a hidden field in the view
ie
@Html.HiddenFor(m => m.Id)
that solves the problem.
Also if your model includes non-used item include that too and post that to the controller
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
I agree with Jarek, and I furthermore note that the ISO offset separator character is a colon, so I think the final answer should be:
isodate.datetime_isoformat(datetime.datetime.now()) + str.format('{0:+06.2f}', -float(time.timezone) / 3600).replace('.', ':')
I made this simple tool to take the place of hosts. Regular expressions are supported. https://github.com/stackia/DNSAgent
A sample configuration:
[
{
"Pattern": "^.*$",
"NameServer": "8.8.8.8"
},
{
"Pattern": "^(.*\\.googlevideo\\.com)|((.*\\.)?(youtube|ytimg)\\.com)$",
"Address": "203.66.168.119"
},
{
"Pattern": "^.*\\.cn$",
"NameServer": "114.114.114.114"
},
{
"Pattern": "baidu.com$",
"Address": "127.0.0.1"
}
]
If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue
: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)
ObjectMapper mapper = new ObjectMapper();
JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
JsonNode tree = jsonParser.readValueAsTree();
// Do stuff to the tree
mapper.readValue(tree, Foo.class);
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them. Let's begin with giving the checkboxes a class so we can round them up very nicely. I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true. the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Well lots of us seem to have been bitten by this, and although the reason this happens makes sense I needed a way to ensure that the value on my Model was shown, and not ModelState.
Some have suggested ModelState.Remove(string key)
, but it's not obvious what key
should be, especially for nested models. Here are a couple methods I came up with to assist with this.
The RemoveStateFor
method will take a ModelStateDictionary
, a Model, and an expression for the desired property, and remove it. HiddenForModel
can be used in your View to create a hidden input field using only the value from the Model, by first removing its ModelState entry. (This could easily be expanded for the other helper extension methods).
/// <summary>
/// Returns a hidden input field for the specified property. The corresponding value will first be removed from
/// the ModelState to ensure that the current Model value is shown.
/// </summary>
public static MvcHtmlString HiddenForModel<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
RemoveStateFor(helper.ViewData.ModelState, helper.ViewData.Model, expression);
return helper.HiddenFor(expression);
}
/// <summary>
/// Removes the ModelState entry corresponding to the specified property on the model. Call this when changing
/// Model values on the server after a postback, to prevent ModelState entries from taking precedence.
/// </summary>
public static void RemoveStateFor<TModel, TProperty>(this ModelStateDictionary modelState, TModel model,
Expression<Func<TModel, TProperty>> expression)
{
var key = ExpressionHelper.GetExpressionText(expression);
modelState.Remove(key);
}
Call from a controller like this:
ModelState.RemoveStateFor(model, m => m.MySubProperty.MySubValue);
or from a view like this:
@Html.HiddenForModel(m => m.MySubProperty.MySubValue)
It uses System.Web.Mvc.ExpressionHelper
to get the name of the ModelState property.
This does it:
Do
c = c + 1
Loop While Cells(c, "A").Value <> ""
'prints the last empty row
Debug.Print c
Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
for the point no 2 we have to follow below steps :
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
2) write below method, which calls doTrustToCertificates before trying to connect to URL
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to URL.
If date
and col_date
are the same columns you should simply do:
SELECT A, MAX(date) FROM t GROUP BY A
Why not use:
WITH x AS ( SELECT A, MAX(col_date) m FROM TABLENAME )
SELECT A, date FROM TABLENAME t JOIN x ON x.A = t.A AND x.m = t.col_date
Otherwise:
SELECT A, FIRST_VALUE(date) KEEP(dense_rank FIRST ORDER BY col_date DESC)
FROM TABLENAME
GROUP BY A
Very easy, just call the function within a specific amount of milliseconds using setTimeout()
setTimeout(myFunction, 2000)
function myFunction() {
alert('Was called after 2 seconds');
}
Or you can even initiate the function inside the timeout, like so:
setTimeout(function() {
alert('Was called after 2 seconds');
}, 2000)
In the case of winforms:
If you include the images to your resources you can do it like this, very simple and straight forward:
public Form1()
{
InitializeComponent();
button1.MouseEnter += new EventHandler(button1_MouseEnter);
button1.MouseLeave += new EventHandler(button1_MouseLeave);
}
void button1_MouseLeave(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}
void button1_MouseEnter(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
I would not recommend hardcoding image paths.
As you have altered your question ...
There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :
in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover);
button1.MouseMove += new MouseEventHandler(button1_MouseMove);
void button1_MouseMove(object sender, MouseEventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
void button1_MouseHover(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
To add images to your resources: Projectproperties/resources/add/existing file
One Year later, let's test mkoistinen's answer with python 3.4.3:
Nothing changed. Join is still the fastest method. With intp being arguably the best choice in terms of readability you might want to use intp nevertheless.
You could use a simple regular expression to assert that the id only contains allowed characters, like so:
if(id.match(/^[0-9a-zA-Z]{1,16}$/)){
//The id is fine
}
else{
//The id is illegal
}
My example allows only alphanumerical characters, and strings of length 1 to 16, you should change it to match the type of ids that you use.
By the way, at line 6, the value property is missing a pair of quotes, an easy mistake to make when you quote on two levels.
I can't see your actual data flow, depending on context this check may not at all be needed, or it may not be enough. In order to make a proper security review we would need more information.
In general, about built in escape or sanitize functions, don't trust them blindly. You need to know exactly what they do, and you need to establish that that is actually what you need. If it is not what you need, the code your own, most of the time a simple whitelisting regex like the one I gave you works just fine.
You can do it using string.indexOf("{item}")
. If the result is greater than -1 {item}
is in the string
Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
function getFirstDayOfWeek(date, from) {
//Default start week from 'Sunday'. You can change it yourself.
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 7 : start);
d.setDate(diff);
return d;
};
Last day of week is just 6 days after first day of week
function getLastDayOfWeek(date, from) {
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
d.setDate(diff);
return d;
};
Test:
getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017
If you are looking for a quick and manual process with UI. I always use Mozilla Firefox to convert from PFX to P12. First import the certificate into the Firefox browser (Options > Privacy & Security > View Certificates... > Import...). Once installed, perform the export to create the P12 file by choosing the certificate name from the Certificate Manager and then click Backup... and enter the file name and then enter the password.
A browser's default styles are defined in its user agent stylesheet, the sources of which you can find here. Unfortunately, the Cascading and Inheritance level 3 spec does not appear to propose a way to reset a style property to its browser default. However there are plans to reintroduce a keyword for this in Cascading and Inheritance level 4 — the working group simply hasn't settled on a name for this keyword yet (the link currently says revert
, but it is not final). Information about browser support for revert
can be found on caniuse.com.
While the level 3 spec does introduce an initial
keyword, setting a property to its initial value resets it to its default value as defined by CSS, not as defined by the browser. The initial value of display
is inline
; this is specified here. The initial
keyword refers to that value, not the browser default. The spec itself makes this note under the all
property:
For example, if an author specifies
all: initial
on an element it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade.This can be useful for the root element of a "widget" included in a page, which does not wish to inherit the styles of the outer page. Note, however, that any "default" style applied to that element (such as, e.g.
display: block
from the UA style sheet on block elements such as<div>
) will also be blown away.
So I guess the only way right now using pure CSS is to look up the browser default value and set it manually to that:
div.foo { display: inline-block; }
div.foo.bar { display: block; }
(An alternative to the above would be div.foo:not(.bar) { display: inline-block; }
, but that involves modifying the original selector rather than an override.)
You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.
For your code to get the position you could do something like this:
$("#myTextInput").bind("keydown keypress mousemove", function() {
alert("Current position: " + $(this).caret().start);
});
Updated to use the more modern Luxon instead of MomentJS.
Don't reinvent the wheel. Use a tried and tested library do this for you, Luxon for example: https://moment.github.io/luxon/index.html
From their site:
//=> 'Thu, Apr 20, 11:27 AM'
DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
The easiest way to get a new list would be:
List<long> unique = longs.Distinct().ToList();
Is that good enough for you, or do you need to mutate the existing list? The latter is significantly more long-winded.
Note that Distinct()
isn't guaranteed to preserve the original order, but in the current implementation it will - and that's the most natural implementation. See my Edulinq blog post about Distinct()
for more information.
If you don't need it to be a List<long>
, you could just keep it as:
IEnumerable<long> unique = longs.Distinct();
At this point it will go through the de-duping each time you iterate over unique
though. Whether that's good or not will depend on your requirements.
$(".element").select2(/*Your code*/)
.on('change', function (e) {
var getID = $(this).select2('data');
alert(getID[0]['id']); // That's the selected ID :)
});
Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.
In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.
Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!
Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).
There is a whole new approach that you may want to consider if what you're after is the power and performance of stored procedures, and the rapid development that tools like Entity Framework provide.
I've taken SQL+ for a test drive on a small project, and it is really something special. You basically add what amounts to comments to your SQL routines, and those comments provide instructions to a code generator, which then builds a really nice object oriented class library based on the actual SQL routine. Kind of like entity framework in reverse.
Input parameters become part of an input object, output parameters and result sets become part of an output object, and a service component provides the method calls.
If you want to use stored procedures, but still want rapid development, you might want to have a look at this stuff.
I have a suspicion, that the Answer doesn't give the correct result. In the question the asker wants to convert timestamp from server to current time in Hellsinki disregarding current time zone of the user.
It's the fact that the user's timezone can be what ever so we cannot trust to it.
If eg. timestamp is 1270544790922 and we have a function:
var _date = new Date();
_date.setTime(1270544790922);
var _helsenkiOffset = 2*60*60;//maybe 3
var _userOffset = _date.getTimezoneOffset()*60*60;
var _helsenkiTime = new Date(_date.getTime()+_helsenkiOffset+_userOffset);
When a New Yorker visits the page, alert(_helsenkiTime) prints:
Tue Apr 06 2010 05:21:02 GMT-0400 (EDT)
And when a Finlander visits the page, alert(_helsenkiTime) prints:
Tue Apr 06 2010 11:55:50 GMT+0300 (EEST)
So the function is correct only if the page visitor has the target timezone (Europe/Helsinki) in his computer, but fails in nearly every other part of the world. And because the server timestamp is usually UNIX timestamp, which is by definition in UTC, the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT), we cannot determine DST or non-DST from timestamp.
So the solution is to DISREGARD the current time zone of the user and implement some way to calculate UTC offset whether the date is in DST or not. Javascript has not native method to determine DST transition history of other timezone than the current timezone of user. We can achieve this most simply using server side script, because we have easy access to server's timezone database with the whole transition history of all timezones.
But if you have no access to the server's (or any other server's) timezone database AND the timestamp is in UTC, you can get the similar functionality by hard coding the DST rules in Javascript.
To cover dates in years 1998 - 2099 in Europe/Helsinki you can use the following function (jsfiddled):
function timestampToHellsinki(server_timestamp) {
function pad(num) {
num = num.toString();
if (num.length == 1) return "0" + num;
return num;
}
var _date = new Date();
_date.setTime(server_timestamp);
var _year = _date.getUTCFullYear();
// Return false, if DST rules have been different than nowadays:
if (_year<=1998 && _year>2099) return false;
// Calculate DST start day, it is the last sunday of March
var start_day = (31 - ((((5 * _year) / 4) + 4) % 7));
var SUMMER_start = new Date(Date.UTC(_year, 2, start_day, 1, 0, 0));
// Calculate DST end day, it is the last sunday of October
var end_day = (31 - ((((5 * _year) / 4) + 1) % 7))
var SUMMER_end = new Date(Date.UTC(_year, 9, end_day, 1, 0, 0));
// Check if the time is between SUMMER_start and SUMMER_end
// If the time is in summer, the offset is 2 hours
// else offset is 3 hours
var hellsinkiOffset = 2 * 60 * 60 * 1000;
if (_date > SUMMER_start && _date < SUMMER_end) hellsinkiOffset =
3 * 60 * 60 * 1000;
// Add server timestamp to midnight January 1, 1970
// Add Hellsinki offset to that
_date.setTime(server_timestamp + hellsinkiOffset);
var hellsinkiTime = pad(_date.getUTCDate()) + "." +
pad(_date.getUTCMonth()) + "." + _date.getUTCFullYear() +
" " + pad(_date.getUTCHours()) + ":" +
pad(_date.getUTCMinutes()) + ":" + pad(_date.getUTCSeconds());
return hellsinkiTime;
}
Examples of usage:
var server_timestamp = 1270544790922;
document.getElementById("time").innerHTML = "The timestamp " +
server_timestamp + " is in Hellsinki " +
timestampToHellsinki(server_timestamp);
server_timestamp = 1349841923 * 1000;
document.getElementById("time").innerHTML += "<br><br>The timestamp " +
server_timestamp + " is in Hellsinki " + timestampToHellsinki(server_timestamp);
var now = new Date();
server_timestamp = now.getTime();
document.getElementById("time").innerHTML += "<br><br>The timestamp is now " +
server_timestamp + " and the current local time in Hellsinki is " +
timestampToHellsinki(server_timestamp);?
And this print the following regardless of user timezone:
The timestamp 1270544790922 is in Hellsinki 06.03.2010 12:06:30
The timestamp 1349841923000 is in Hellsinki 10.09.2012 07:05:23
The timestamp is now 1349853751034 and the current local time in Hellsinki is 10.09.2012 10:22:31
Of course if you can return timestamp in a form that the offset (DST or non-DST one) is already added to timestamp on server, you don't have to calculate it clientside and you can simplify the function a lot. BUT remember to NOT use timezoneOffset(), because then you have to deal with user timezone and this is not the wanted behaviour.
With the new and popular f-strings in Python 3.6, here is how we left-align say a string with 16 padding length:
string = "Stack Overflow"
print(f"{string:<16}..")
Stack Overflow ..
If you have variable padding length:
k = 20
print(f"{string:<{k}}..")
Stack Overflow ..
f-strings are more compact.
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
No, that's not true. The session-timeout
configures a per session timeout in case of inactivity.
Are these methods equivalent? Should I favour the web.xml config?
The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.
There is nothing much to add to your code except appending the li tag to the ul
ul.appendChild(li)
and there you go just add this to your function and then it should work.
As other answers already say, Python can keep from releasing memory to the OS even if it's no longer in use by Python code (so gc.collect()
doesn't free anything) especially in a long-running program. Anyway if you're on Linux you can try to release memory by invoking directly the libc function malloc_trim
(man page).
Something like:
import ctypes
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)
Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.
Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:
http://docs.python.org/library/decimal.html
Among other things you can explicitly specify the precision that you wish to obtain (from the docs):
>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')
A simple example from my prompt (python 2.6):
>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29
Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.
Hope this helps, Francesco
Code
spinner.setOnTouchListener(new View.OnTouchListener() {
@Override public boolean onTouch(View view, MotionEvent motionEvent) { isSpinnerTouch=true; return false; }});
holder.spinner_from.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int slot_position, long l) {
if(isSpinnerTouch)
{
Log.d("spinner_from", "spinner_from");
spinnerItemClickListener.onSpinnerItemClickListener(position, slot_position, AppConstant.FROM_SLOT_ONCLICK_CODE);
}
else {
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Anything using the managed environment (which includes anything written in C# and VB.NET) requires the .NET framework. You can simply redistribute your .EXE in that scenario, but they'll need to install the appropriate framework if they don't already have it.
In Bootstrap 3 I've added a table-no-border class
.table-no-border>thead>tr>th,
.table-no-border>tbody>tr>th,
.table-no-border>tfoot>tr>th,
.table-no-border>thead>tr>td,
.table-no-border>tbody>tr>td,
.table-no-border>tfoot>tr>td {
border-top: none;
}
List<Conversation> conversations = **jdbcTemplate**.**queryForList**(
**SQL_QUERY**,
new Object[] {userId, dateFrom, dateTo}); //placeholders values
Suppose the sql query is like
SQL_QUERY = "**select** info,count(*),IF(info is null , 'DATA' , 'NO DATA') **from** table where userId=? , dateFrom=? , dateTo=?";
**HERE userId=? , dateFrom=? , dateTo=?**
the question marks are place holders
**SQL_QUERY**,
new Object[] {userId, dateFrom, dateTo});
It will go as an object array along with the sql query
You can template a struct as well as a class. However you can't template a typedef. So template<typename T> struct array {...};
works, but template<typename T> typedef struct {...} array;
does not. Note that there is no need for the typedef trick in C++ (you can use structs without the struct
modifier just fine in C++).
In the terminal just write : $ mongod --version
I would use a bound service to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there!
Setting the table's separatorStyle
to UITableViewCellSeparatorStyleNone
(in code or in IB) should do the trick.
Use transform: scale(...);
and add matching margin: -...px
to compensate free space from scaling. (you can use * {outline: 1px solid}
to see element boundaries).
In case someone (like me) out there is looking for ways deal with Objects instead of primitive types then use mapToObj()
String ss = "An alternative way is to insert the following VM option before "
+ "the -vmargs option in the Eclipse shortcut properties(edit the "
+ "field Target inside the Shortcut tab):";
List<Character> ll = ss
.chars()
.mapToObj(c -> new Character((char) c))
.collect(Collectors.toList());
System.out.println("List type: " + ll.getClass());
System.out.println("Elem type: " + ll.get(0).getClass());
ll.stream().limit(50).forEach(System.out::print);
prints:
List type: class java.util.ArrayList
Elem type: class java.lang.Character
An alternative way is to insert the following VM o
Now I've found the problem.
Removing the obj_exception_throw
from my breakpoints solved this. Now it's caught by the @try
block and also, NSSetUncaughtExceptionHandler
will handle this if a @try
block is missing.
Got this from a network filter (LuLu on macOS) blocking traffic to/from Docker-related processes.
No. You can't send headers after they were sent. Try to use hooks in wordpress
I had this issue when leaving a view (pop back to the previous view).
the reason was having
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
view.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
view.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
view.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
])
Change safeAreaLayoutGuide
to self
solve the issue.
Meaning aligns the view with the superview's leading, trailing, top, bottom instead of to safe area)
If you are using reactiveFormModule and have formGroup defined like this:
public exampleForm = new FormGroup({
name: new FormControl('Test name', [Validators.required, Validators.minLength(3)]),
email: new FormControl('[email protected]', [Validators.required, Validators.maxLength(50)]),
age: new FormControl(45, [Validators.min(18), Validators.max(65)])
});
than you are able to add a new validator (and keep old ones) to FormControl with this approach:
this.exampleForm.get('age').setValidators([
Validators.pattern('^[0-9]*$'),
this.exampleForm.get('age').validator
]);
this.exampleForm.get('email').setValidators([
Validators.email,
this.exampleForm.get('email').validator
]);
FormControl.validator returns a compose validator containing all previously defined validators.
I use them all the time. The only thing I worry about is giving away IP in log files. If your function names are really good you might be making a trade secret easier to uncover. It's sort of like shipping with debug symbols, only more difficult to find things. In 99.999% of the cases nothing bad will come of it.
uint32_t
is defined in the standard, in
<cstdint>
synopsis [cstdint.syn]namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}
uint32
is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32
) for ease of use.
What you need is nm
and its -D
option:
$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
U atanf
U calloc
.
.
.
Exported sumbols are indicated by a T
. Required symbols that must be loaded from other shared objects have a U
. Note that the symbol table does not include just functions, but exported variables as well.
See the nm
manual page for more information.
I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:
const car = carFactory.getCar();
car.drive() //throws TypeError: drive is not a function
The fix was:
const car = await carFactory.getCar();
car.drive()
Posting this incase it helps anyone else facing this error.
<context:property-placeholder ... />
is the XML equivalent to the PropertyPlaceholderConfigurer.
Example: applicationContext.xml
<context:property-placeholder location="classpath:test.properties"/>
Component class
private @Value("${propertyName}") String propertyField;
You're essentially running out of memory to run the process smoothly. Options that come to mind:
-Xmx512m
firstHashMap
objects to process at once if possibleString.intern()
on them before putting them into the HashMap
HashMap(int initialCapacity, float loadFactor)
constructor to tune for your caseDid you call your function properly? Ie. is the thing you pass as as a parameter really a string?
Otherwise, I don't see a problem with your code - the example below works as expected
function trim(str) {
return str.replace(/^\s+|\s+$/g,'');
}
trim(' hello '); // --> 'hello'
However, if you call your functoin with something non-string, you will indeed get the error above:
trim({}); // --> TypeError: str.replace is not a function
You can use as following.
$start_date = date('Y-m-d H:i:s');
$end_date = date("Y-m-d 23:59:59", strtotime('+3 days', strtotime($start_date)));
You can also set days as constant and use like below.
if (!defined('ADD_DAYS')) define('ADD_DAYS','+3 days');
$end_date = date("Y-m-d 23:59:59", strtotime(ADD_DAYS, strtotime($start_date)));
If you are interested in only selecting one column this will work.
df[["item1"]].to_dict("records")
The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.
df["item1"].to_dict("records")
I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.
Method Object JComboBox.getSelectedItem()
returns a value that is wrapped by Object
type so you have to cast it accordingly.
Syntax:
YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();
Some people find the following alternative syntax easier to see what is going on:
select t1.value,t2.value
from MyTable t1
inner join MyTable t2 on
t1.id = t2.id
where t1.id = @id
Step 1
Go to Help --->
Install New Software...
Step 2 Try to find "http://download.eclipse.org/webtools/updates" under work with drop down. If you find then select and install all the available updates.
If you can not find then click on Add -> Add Repository. Name: Eclipse Webtools Location: http://download.eclipse.org/webtools/updates Select all available updates and Install them.
Visit http://download.eclipse.org/webtools/updates/ for more details.
This is a typical startup failure due to the embedded servlet container’s port being in use.
Your embedded tomcat container failed to start because Port 8080 was already in use.
Just Identify and stop the process that's listening on port 8080 or configure (in you application.properties file )this application to listen on another port.
It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en
Assign the values of nested json
to struct until you know the underlying type of json keys:-
package main
import (
"encoding/json"
"fmt"
)
// Object
type Object struct {
Foo map[string]map[string]string `json:"foo"`
More string `json:"more"`
}
func main(){
someJSONString := []byte(`{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}`)
var obj Object
err := json.Unmarshal(someJSONString, &obj)
if err != nil{
fmt.Println(err)
}
fmt.Println("jsonObj", obj)
}
This is what solved my problem
Add the following line to WebApiConfig.cs
config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));
Yes there is retainAll
check out this
Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);
I had the "same" problem because I was writting
@GeneratedValue(strategy = GenerationType.IDENTITY)
I deleted that line due that I do not need it at the moment, I was testing with objects and so. I think it is <generator class="native" />
in your case
I do not have any controller and my API is not being accessed, it is only for testing (at the moment).
we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.
point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
more details in this answer: https://stackoverflow.com/a/37465080/473040
The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT
packageData: (data) => {
const form = new FormData()
for ( const key in data ) {
form.append(key, data[key]);
}
return form
}
Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following
packageData: (obj, form, namespace) => {
for(const property in obj) {
// if form is passed in through recursion assign otherwise create new
const formData = form || new FormData()
let formKey
if(obj.hasOwnProperty(property)) {
if(namespace) {
formKey = namespace + '[' + property + ']';
} else {
formKey = property;
}
// if the property is an object, but not a File, use recursion.
if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
packageData(obj[property], formData, property);
} else {
// if it's a string or a File
formData.append(formKey, obj[property]);
}
}
}
return formData;
}
I think your cron is not correct. According to what you described, you may need to change cron schedule to
*/5 * * * *
What you put in your schedule now mean it will poll the SCM at 5 past of every hour.
Inside the col-md-?, create another div and put picture in that div, than you can easily add padding like so.
<div class="row">
<div class="col-md-8">
<div class="thumbnail">
<img src="#"/>
</div>
</div>
<div class="col-md-4">
<div class="thumbnail">
<img src="#"/>
</div>
</div>
</div>
<style>
thumbnail{
padding:4px;
}
</style>
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
The answer here is not clear, so I wanted to add more detail.
Using the link provided above, I performed the following step.
In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.
This information is available at the link the OP posted in the Answer.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
By the way - ASP.NET has nothing to do with it. Encodings are universal.
Events are pretty easy in C#, but the MSDN docs in my opinion make them pretty confusing. Normally, most documentation you see discusses making a class inherit from the EventArgs
base class and there's a reason for that. However, it's not the simplest way to make events, and for someone wanting something quick and easy, and in a time crunch, using the Action
type is your ticket.
1. Create your event on your class right after your class
declaration.
public event Action<string,string,string,string>MyEvent;
2. Create your event handler class method in your class.
private void MyEventHandler(string s1,string s2,string s3,string s4)
{
Console.WriteLine("{0} {1} {2} {3}",s1,s2,s3,s4);
}
3. Now when your class is invoked, tell it to connect the event to your new event handler. The reason the +=
operator is used is because you are appending your particular event handler to the event. You can actually do this with multiple separate event handlers, and when an event is raised, each event handler will operate in the sequence in which you added them.
class Example
{
public Example() // I'm a C# style class constructor
{
MyEvent += new Action<string,string,string,string>(MyEventHandler);
}
}
4. Now, when you're ready, trigger (aka raise) the event somewhere in your class code like so:
MyEvent("wow","this","is","cool");
The end result when you run this is that the console will emit "wow this is cool". And if you changed "cool" with a date or a sequence, and ran this event trigger multiple times, you'd see the result come out in a FIFO sequence like events should normally operate.
In this example, I passed 4 strings. But you could change those to any kind of acceptable type, or used more or less types, or even remove the <...>
out and pass nothing to your event handler.
And, again, if you had multiple custom event handlers, and subscribed them all to your event with the +=
operator, then your event trigger would have called them all in sequence.
But what if you want to identify the caller to this event in your event handler? This is useful if you want an event handler that reacts with conditions based on who's raised/triggered the event. There are a few ways to do this. Below are examples that are shown in order by how fast they operate:
Option 1. (Fastest) If you already know it, then pass the name as a literal string to the event handler when you trigger it.
Option 2. (Somewhat Fast) Add this into your class and call it from the calling method, and then pass that string to the event handler when you trigger it:
private static string GetCaller([System.Runtime.CompilerServices.CallerMemberName] string s = null) => s;
Option 3. (Least Fast But Still Fast) In your event handler when you trigger it, get the calling method name string with this:
string callingMethod = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().ReflectedType.Name.Split('<', '>')[1];
You may have a scenario where your custom event has multiple event handlers, but you want to remove one special one out of the list of event handlers. To do so, use the -=
operator like so:
MyEvent -= MyEventHandler;
A word of minor caution with this, however. If you do this and that event no longer has any event handlers, and you trigger that event again, it will throw an exception. (Exceptions, of course, you can trap with try/catch blocks.)
Okay, let's say you're through with events and you don't want to process any more. Just set it to null like so:
MyEvent = null;
The same caution for Unsubscribing events is here, as well. If your custom event handler no longer has any events, and you trigger it again, your program will throw an exception.
private static UserService userService = ApplicationContextHolder.getContext().getBean(UserService.class);
A simple Android Easy QR Code Library. It is very easy to use, to use this library follow these steps.
Step 1. Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency:
dependencies {
compile 'com.github.mrasif:easyqrlibrary:v1.0.0'
}
Step 1. Add the JitPack repository to your build file:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Step 2. Add the dependency:
<dependency>
<groupId>com.github.mrasif</groupId>
<artifactId>easyqrlibrary</artifactId>
<version>v1.0.0</version>
</dependency>
Step 1. Add the JitPack repository to your build.sbt file:
resolvers += "jitpack" at "https://jitpack.io"
Step 2. Add the dependency:
libraryDependencies += "com.github.mrasif" % "easyqrlibrary" % "v1.0.0"
Step 1. Add it in your project.clj at the end of repositories:
:repositories [["jitpack" "https://jitpack.io"]]
Step 2. Add the dependency:
:dependencies [[com.github.mrasif/easyqrlibrary "v1.0.0"]]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/tvData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="No QR Data"/>
<Button
android:id="@+id/btnQRScan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="QR Scan"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView tvData;
Button btnQRScan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData=findViewById(R.id.tvData);
btnQRScan=findViewById(R.id.btnQRScan);
btnQRScan.setOnClickListener(this);
}
@Override
public void onClick(View view){
switch (view.getId()){
case R.id.btnQRScan: {
Intent intent=new Intent(MainActivity.this, QRScanner.class);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);
} break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case EasyQR.QR_SCANNER_REQUEST: {
if (resultCode==RESULT_OK){
tvData.setText(data.getStringExtra(EasyQR.DATA));
}
} break;
}
}
}
For customized scanner screen just add these lines when you start the scanner Activity.
Intent intent=new Intent(MainActivity.this, QRScanner.class);
intent.putExtra(EasyQR.IS_TOOLBAR_SHOW,true);
intent.putExtra(EasyQR.TOOLBAR_DRAWABLE_ID,R.drawable.ic_audiotrack_dark);
intent.putExtra(EasyQR.TOOLBAR_TEXT,"My QR");
intent.putExtra(EasyQR.TOOLBAR_BACKGROUND_COLOR,"#0588EE");
intent.putExtra(EasyQR.TOOLBAR_TEXT_COLOR,"#FFFFFF");
intent.putExtra(EasyQR.BACKGROUND_COLOR,"#000000");
intent.putExtra(EasyQR.CAMERA_MARGIN_LEFT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_TOP,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_RIGHT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_BOTTOM,50);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);
You are done. Ref. Link: https://mrasif.github.io/easyqrlibrary
Well, your code is not reproducible so we will never know for sure, but this is what help('break')
says:
break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.
So yes, break
only breaks the current loop. You can also see it in action with e.g.:
for (i in 1:10)
{
for (j in 1:10)
{
for (k in 1:10)
{
cat(i," ",j," ",k,"\n")
if (k ==5) break
}
}
}
Split your date into year, month, and day components then use Date:
var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);
Date will take care of fixing the year.
If you want to unit test code then you need to isolate your code you want to test (in this case your service) from external resources (e.g. databases). You could probably do this with some sort of in-memory EF provider, however a much more common way is to abstract away your EF implementation e.g. with some sort of repository pattern. Without this isolation any tests you write will be integration tests, not unit tests.
As for testing EF code - I write automated integration tests for my repositories that write various rows to the database during their initialization, and then call my repository implementations to make sure that they behave as expected (e.g. making sure that results are filtered correctly, or that they are sorted in the correct order).
These are integration tests not unit tests, as the tests rely on having a database connection present, and that the target database already has the latest up-to-date schema installed.
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
You can set the title in action-bar using AndroidManifest.xml
. Add label to the activity
<activity
android:name=".YourActivity"
android:label="Your Title" />
This will search and replace all non ASCII letters:
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
I am not sure in your case. But as I know to run any jar file from cmd we can use following command:
Go up to the directory where your jar file is saved:
java -jar <jarfilename>.jar
But you can check following links. I hope it'll help you:
Run Netbeans maven project from command-line?
http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html
This happens if the .git file is missing in the target path. It happend to me after I executed git clean -f -d
.
I had to delete all target folders showing in the message and then executing git submodule update --remote
I know this is an old thread, but what about borrowing from C syntax:
(o.get('uses_votes')).equals("1") ? true : false;
Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
resp = app.make_response(xml)
resp.mimetype = "text/xml"
return resp
If you use Response
directly, you lose the chance to customize the responses by setting app.response_class
. The make_response
method uses the app.responses_class
to make the response object. In this you can create your own class, add make your application uses it globally:
class MyResponse(app.response_class):
def __init__(self, *args, **kwargs):
super(MyResponse, self).__init__(*args, **kwargs)
self.set_cookie("last-visit", time.ctime())
app.response_class = MyResponse
Not sure if this is really beneficial or why I prefer this style but what I do (in vanilla js) is:
document.querySelector('#selector').toggleAttribute('data-something');
This will add the attribute in all lowercase without a value or remove it if it already exists on the element.
https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute
You should investigate why VBA can't find queryname.
I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute
.
CurrentDb.Execute "qryAddLoginfoRow"
My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.
Edit:
You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute
line.
Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name
The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb
to Execute
.
If your hardware is 32-bit only, then no. If you have 64 bit hardware and a 32-bit operating system, then maybe. See Hardware and Firmware Requirements for 64-Bit Guest Operating Systems for details. It has nothing to do with one vs. multiple processors.
Nanda's answer wasn't enough in my setup. What I needed to do is:
In MomentJs We can declare it like :
const start = moment().format('YYYY-MM-DD 00:00:01');
const end = moment().format('YYYY-MM-DD 23:59:59');
File >> Import >> Existing Projects into Workspace >> Select Archive Filed >> Browse and locate file >> Finish. If its already imported some other way delete it and try it that way. I was having the same problem until i tried that.
Create a .htaccess file in the images folder and add this
<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>
you can put this Options All -Indexes
in the project file .htaccess
,file to deny direct access to other folders.
This does what you want
In 2012 OData underwent standardization, so I'll just add an update here..
First the definitions:
REST - is an architecture of how to send messages over HTTP.
OData V4- is a specific implementation of REST, really defines the content of the messages in different formats (currently I think is AtomPub and JSON). ODataV4 follows rest principles.
For example, asp.net people will mostly use WebApi controller to serialize/deserialize objects into JSON and have javascript do something with it. The point of Odata is being able to query directly from the URL with out-of-the-box options.
Call list() on the GroupBy object
print(list(df.groupby('A')))
gives you:
[('one', A B
0 one 0
1 one 1
5 one 5), ('three', A B
3 three 3
4 three 4), ('two', A B
2 two 2)]
You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':
len(data['result'][0]['run'])
This worked best for me
"0x%02X" % 5 # => 0x05
"0x%02X" % 17 # => 0x11
Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following
"0x%03X" % 5 # => 0x005
"0x%03X" % 17 # => 0x011
>
Data ExportIt's rather simple. Private setters allow you to create read-only public or protected properties.
That's it. That's the only reason.
Yes, you can create a read-only property by only specifying the getter, but with auto-implmeneted properties you are required to specify both get and set, so if you want an auto-implemented property to be read-only, you must use private setters. There is no other way to do it.
It's true that Private setters were not created specificlly for auto-implemented read-only properties, but their use is a bit more esoteric for other reasons, largely centering around read-only properties and the use of reflection and serialization.
Quick summary, you can do either:
Include the JavaFX modules via --module-path
and --add-modules
like in José's answer.
OR
Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java
file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java
file).
This answer is a supplement to Jose's answer.
The situation is this:
IllegalAccessError
involving an "unnamed module" when trying to launch the app.Excerpt for a stack trace generating an IllegalAccessError
when trying to run a JavaFX app from Intellij Idea:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main
OK, now you are kind of stuck and have no clue what is going on.
What has actually happened is this:
So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError
. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).
This is where some of the other answers to this question, which reference module-info.java
, come into the picture.
So let's take a crash course in Java modules:
The key part is this:
4.9. Opens
If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.
But remember, this will open the package up to the entire world, so make sure that is what you want:
module my.module { opens com.my.package; }
So, perhaps you don't want to open your package to the entire world, then you can do:
4.10. Opens … To
Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:
module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }
So, you end up creating a src/main/java/module-info.java class which looks like this:
module org.jewelsea.demo.javafx.springboot {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}
Where, org.jewelsea.demo.javafx.springboot
is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics
and javafx.fxml
to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot
package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError
generated by JavaFX's use of reflection will no longer occur.
But what if you don't want to create a module-info.java file
If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:
javafx.run
.Run Maven Build
or Debug...
.Then the app will run without the module-info.java
file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java
file, though I don't know how this is accomplished.
To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run
Maven target and choose the option to Create Run/Debug Configuration
for the target. Then you can just choose Run from the top toolbar to execute the Maven target.
In my case it was a virtual function in an interface class that wasn't defined as a pure virtual.
class IInterface
{
public:
virtual void Foo() = 0;
}
I forgot the = 0
bit.
Try
$("#myModal").modal("toggle")
To open or close the modal with id myModal.
If the above is not working then it means bootstrap.js has been overridden by some other js file. Here is a solution
1:- Move bootstrap.js to the bottom so that it will override other js files.
2:- Make sure the order is like below
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Other js files -->
<script src="plugins/jQuery/bootstrap.min.js"></script>
For Those Running on Older Hardware:
You may get this same error due to having an older CPU using tensorflow-gpu 1.6.
If your cpu was made before 2011, then your max tensorflow-gpu version is 1.5.
Tensorflow 1.6 requires AVX instructions on your cpu. Verified here: Tensorflow Github docs
AVX enabled CPUs: Wiki AVX CPUs
What I did in my conda environment for tensorflow:
pip install --ignore-installed --upgrade tensorflow-gpu==1.5
Similar to the previous answers, the problem is some character (possibly invisible) that the Python interpreter doesn't recognize. Because this is often due to copy-pasting code, re-typing the line is one option.
But if you don't want to re-type the line, you can paste your code into this tool or something similar (Google "show unicode characters online"), and it will reveal any non-standard characters. For example,
s=' values ??= list(analysis.values ??())'
becomes
s=' values U+200B U+200B?? = list(analysis.values U+200B U+200B ??())'
You can then delete the non-standard characters from the string.
$('#fm_submit').submit(function(e){_x000D_
e.preventDefault();_x000D_
var ck_box = $('input[type="checkbox"]:checked').length;_x000D_
_x000D_
// return in firefox or chrome console _x000D_
// the number of checkbox checked_x000D_
console.log(ck_box); _x000D_
_x000D_
if(ck_box > 0){_x000D_
alert(ck_box);_x000D_
} _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name = "frmTest[]" id="fm_submit">_x000D_
<input type="checkbox" value="true" checked="true" >_x000D_
<input type="checkbox" value="true" checked="true" >_x000D_
<input type="checkbox" >_x000D_
<input type="checkbox" >_x000D_
<input type="submit" id="fm_submit" name="fm_submit" value="Submit">_x000D_
</form>_x000D_
<div class="container"></div>
_x000D_
As pointed out by others in related questions (see here, here, here, here, here, here, and here), you can now unstage a file with git restore --staged <file>
.
To unstage all the files in your project, run the following from the root of the repository (the command is recursive):
git restore --staged .
If you only want to unstage the files in a directory, navigate to it before running the above or run:
git restore --staged <directory-path>
git restore
was introduced in July 2019 and released in version 2.23.
With the --staged
flag, it restores the content of the working tree from HEAD (so it does the opposite of git add
and does not delete any change).
This is a new command, but the behaviour of the old commands remains unchanged. So the older answers with git reset
or git reset HEAD
are still perfectly valid.
When running git status
with staged uncommitted file(s), this is now what Git suggests to use to unstage file(s) (instead of git reset HEAD <file>
as it used to prior to v2.23).
select substr(orderno,1,2) from shipment;
You may want to have a look at the documentation too.
You could sort the array first (Ascending by default) and then apply np.flip() (https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html)
FYI It works with datetime objects as well.
Example:
x = np.array([2,3,1,0])
x_sort_asc=np.sort(x)
print(x_sort_asc)
>>> array([0, 1, 2, 3])
x_sort_desc=np.flip(x_sort_asc)
print(x_sort_desc)
>>> array([3,2,1,0])
Works for every binary, not only java:
file - < $(which java) # heavyly bashic
cat `which java` | file - # universal
INSERT INTO table 2
SELECT * FROM table1/view1
Try writing the file path as "C:\\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener"
i.e with double backslash after the drive as opposed to "C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener"
null
removes it:
[attr.checked]="value ? '' : null"
or
[attr.checked]="value ? 'checked' : null"
When the HTML element where you add this binding does not have a property with the name used in the binding (checked
in this case) and also no Angular component or directive is applied to the same element that has an @Input() checked;
, then [xxx]="..."
can not be used.
See also What is the difference between properties and attributes in HTML?
Alternatives are [style.xxx]="..."
, [attr.xxx]="..."
, [class.xxx]="..."
depending on what you try to accomplish.
Because <input>
only has a checked
attribute, but no checked
property [attr.checked]="..."
is the right way for this specific case.
A common pitfall is also that for [attr.xxx]="..."
bindings the value (...
) is always stringified. Only properties and @Input()
s can receive other value types like boolean, number, object, ...
Most properties and attributes of elements are connected and have the same name.
When bound to the attribute the property also only receives the stringified value from the attribute.
When bound to the property the property receives the value bound to it (boolean, number, object, ...) and the attribute again the stringified value.
Two cases where attribute and property names do not match.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor (see the first sentence of the description htmlFor property reflects the value of the for
- for
probably didn't work because it's a keyword in C or JavaScript)
Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [for]="
even though no such property exists (same for colspan
)
There are no PowerShell-native commands for Base64 conversion - yet (as of PowerShell [Core] 7.1), but adding dedicated cmdlets has been suggested.
For now, direct use of .NET is needed.
Important:
Base64 encoding is an encoding of binary data using bytes whose values are constrained to a well-defined 64-character subrange of the ASCII character set representing printable characters, devised at a time when sending arbitrary bytes was problematic, especially with the high bit set (byte values > 0x7f).
Therefore, you must always specify explicitly what character encoding the Base64 bytes do / should represent.
Ergo:
on converting TO Base64, you must first obtain a byte representation of the string you're trying to encode using the character encoding the consumer of the Base64 string expects.
on converting FROM Base64, you must interpret the resultant array of bytes as a string using the same encoding that was used to create the Base64 representation.
Examples:
Note:
The following examples convert to and from UTF-8 encoded strings:
To convert to and from UTF-16LE ("Unicode") instead, substitute [Text.Encoding]::Unicode
for [Text.Encoding]::UTF8
Convert TO Base64:
PS> [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Motörhead'))
TW90w7ZyaGVhZA==
Convert FROM Base64:
PS> [Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('TW90w7ZyaGVhZA=='))
Motörhead
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
Update: MySQL 8.0 is finally getting the feature of common table expressions, including recursive CTEs.
Here's a blog announcing it: http://mysqlserverteam.com/mysql-8-0-labs-recursive-common-table-expressions-in-mysql-ctes/
Below is my earlier answer, which I originally wrote in 2008.
MySQL 5.x does not support queries using the WITH
syntax defined in SQL-99, also called Common Table Expressions.
This has been a feature request for MySQL since January 2006: http://bugs.mysql.com/bug.php?id=16244
Other RDBMS products that support common table expressions:
To fully comply with RSpec ~> 3.1 syntax and rubocop-rspec
's default option for rule RSpec/MessageSpies
, here's what you can do with spy
:
Message expectations put an example's expectation at the start, before you've invoked the code-under-test. Many developers prefer using an arrange-act-assert (or given-when-then) pattern for structuring tests. Spies are an alternate type of test double that support this pattern by allowing you to expect that a message has been received after the fact, using have_received.
# arrange.
invitation = spy('invitation')
# act.
invitation.deliver("[email protected]")
# assert.
expect(invitation).to have_received(:deliver).with("[email protected]")
If you don't use rubocop-rspec or using non-default option. You may, of course, use RSpec 3 default with expect.
dbl = double("Some Collaborator")
expect(dbl).to receive(:foo).with("[email protected]")
The browser is not adding any padding. Instead, letters (even uppercase letters) are generally considerably smaller in the vertical direction than the height of the font, not to mention the line height, which is typically by default about 1.2 times the font height (font size).
There is no general solution to this because fonts are different. Even for fixed font size, the height of a letter varies by font. And uppercase letters need not have the same height in a font.
Practical solutions can be found by experimentation, but they are unavoidably font-dependent. You will need to set the line height essentially smaller than the font size. The following seems to yield the desired result in different browsers on Windows, for the Arial font:
span.foo_x000D_
{_x000D_
display: inline-block;_x000D_
font-size: 50px;_x000D_
background-color: green;_x000D_
line-height: 0.75em;_x000D_
font-family: Arial;_x000D_
}_x000D_
_x000D_
span.bar_x000D_
{_x000D_
position: relative;_x000D_
bottom: -0.02em;_x000D_
}
_x000D_
<span class=foo><span class=bar>BIG TEXT</span></span>
_x000D_
The nested span
elements are used to displace the text vertically. Otherwise, the text sits on the baseline, and under the baseline, there is room reserved for descenders (as in letters j and y).
If you look closely (with zooming), you will notice that there is very small space above and below most letters here. I have set things so that the letter “G” fits in. It extends vertically a bit farther than other uppercase letters because that way the letters look similar in height. There are similar issues with other letters, like “O”. And you need to tune the settings if you’ll need the letter “Q” since it has a descender that extends a bit below the baseline (in Arial). And of course, if you’ll ever need “É”, or almost any diacritic mark, you’re in trouble.
By default mysqldump
always creates the CREATE DATABASE IF NOT EXISTS db_name;
statement at the beginning of the dump file.
[EDIT] Few things about the mysqldump
file and it's options:
--all-databases
, -A
Dump all tables in all databases. This is the same as using the --databases
option and naming all the databases on the command line.
--add-drop-database
Add a DROP DATABASE
statement before each CREATE DATABASE
statement. This option is typically used in conjunction with the --all-databases
or --databases
option because no CREATE DATABASE
statements are written unless one of those options is specified.
--databases
, -B
Dump several databases. Normally, mysqldump
treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE
and USE
statements are included in the output before each new database.
--no-create-db
, -n
This option suppresses the CREATE DATABASE
statements that are otherwise included in the output if the --databases
or --all-databases
option is given.
Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.
So to answer your question:
--add-drop-database
option in your mysqldump
statement.--databases
or --all-databases
and the CREATE DATABASE
syntax will be added
automaticallyMore information at MySQL Reference Manual
You need to define something in the interface, such as:
public interface ITest
{
string Name { get; }
}
Implement ITest
in your classes:
public class MyClass1 : ITest
{
public string Name { get { return "Test1"; } }
}
public class MyClass2 : ITest
{
public string Name { get { return "Test2"; } }
}
Then restrict your generic Print
function, to ITest
:
public void Print<T>(T test) where T : ITest
{
}
After the last Firefox update we had the same session timeout issue and the following setting helped to resolve it.
We can control it with network.http.response.timeout
parameter.
network.http.response.timeout
parameter will be displayed.network.http.response.timeout
parameter and enter the time value (it is in seconds) that you don't want your session not to timeout, in the box.To simply repeat the same letter 10 times:
string_val = "x" * 10 # gives you "xxxxxxxxxx"
And if you want something more complex, like n
random lowercase letters, it's still only one line of code (not counting the import statements and defining n
):
from random import choice
from string import ascii_lowercase
n = 10
string_val = "".join(choice(ascii_lowercase) for i in range(n))
When you see this trying to push to github you may have to initialize this repo at github first: https://github.com/new.
Months in Calendar object start from 0
0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
CASE
is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY
clause of a SELECT
statement.
It looks like you just need:
ORDER BY
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc,
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
Or possibly:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.
This may be the answer we're looking for:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN 5
WHEN TblList.HighCallAlertCount <> 0 THEN 4
WHEN TblList.HighAlertCount <> 0 THEN 3
WHEN TblList.MediumCallAlertCount <> 0 THEN 2
WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
For non-preemptive system,
waitingTime = startTime - arrivalTime
turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime
startTime = Time at which the process started executing
finishTime = Time at which the process finished executing
You can keep track of the current time elapsed in the system(timeElapsed
). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime
, when finishes, record its finishTime
(both same as timeElapsed
). That way you can calculate what you need.
For me this issue came after a long period of not using mysql nor the webserver. So I was sure that my settings where correct; Simply restarting the service fixes this issue; The weird part about the issue is that one can still connect to the database, and even query/add tables using the mysql tool. for example :
mysql -u root -p
I restarted using :
systemctl start mysqld.service
or service mysqld restart or /etc/init.d/mysqld restart
Note : depending on the machine/environment on of these commands should restart the service.
I had similar issue Cannot resolve com.google.android.gms.common.
I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!
Summary:
compile 'com.google.android.gms:play-services:4.0.30'
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
When you do the second one, you're making a new arraylist, you're not trying to pretend the other list is an arraylist.
I mean, what if the original list is implemented as a linkedlist, or some custom list? You won't know. The second approach is preferred if you really need to make an arraylist from the result. But you can just leave it as a list, that's one of the best advantages of using Interfaces!
Also you can use postgres fdw system
https://www.postgresql.org/docs/9.5/postgres-fdw.html
You will be able to connect different db in postgres. After that, in one query, you can access tables that are in different databases.
create a full-width View
with alignItems: "center"
then insert desired children inside.
import React from "react";
import {View} from "react-native";
export default class AbsoluteComponent extends React.Component {
render(){
return(
<View style={{position: "absolute", left: 0, right: 0, alignItems: "center"}}>
{this.props.children}
</View>
)
}
}
you can add properties like bottom: 30
for bottom aligned component.
I use the following code on http://www.diagnomics.com/
Smooth transition from b/w to color with magnifying effect (scale)
img.color_flip {
filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
filter: gray; /* IE5+ */
-webkit-filter: grayscale(1); /* Webkit Nightlies & Chrome Canary */
-webkit-transition: all .5s ease-in-out;
}
img.color_flip:hover {
filter: none;
-webkit-filter: grayscale(0);
-webkit-transform: scale(1.1);
}
Unfortunately, I had problem with Local SQL Server installed within Visual Studio and here many solutions didn't work out for me. All I have to do is to reset my Visual Studio, by going to:
Control Panel > Program & Features > Visual Studio Setup Launcher
and click on More button and choose Repair
After that I was able to access my Local SQL Server and work with local SQL Databases.
I'm using Eclipse Kepler release. There is no Installation Details or About Eclipse menu item under help. For me, it was Help | Eclipse Marketplace...
I had to click on the "Installed" tab. The plug-in I wanted to remove was listed there, with an "Uninstall" option.
The use of IIF? And it depends on version of SQL Server.
SELECT
IIF(Column1 = Column2, 1, 0) AS MyDesiredResult
FROM Table;
Test if a file exists:
HOST="example.com"
FILE="/path/to/file"
if ssh $HOST "test -e $FILE"; then
echo "File exists."
else
echo "File does not exist."
fi
And the opposite, test if a file does not exist:
HOST="example.com"
FILE="/path/to/file"
if ! ssh $HOST "test -e $FILE"; then
echo "File does not exist."
else
echo "File exists."
fi
In ~/.subversion/config
, you probably have store-passwords = no
. Change it to yes
(or just comment it out because it defaults to yes), and the next time you give Subversion your password it should save it.
You might want to ensure that the owner and permissions of ~/.subversion/config
are correct (no public or group access; 600).
I have searched/googled quite a few webpages on javascript sleep/wait... and there is NO answer if you want javascript to "RUN, DELAY, RUN"... what most people got was either, "RUN, RUN(useless stuff), RUN" or "RUN, RUN + delayed RUN"....
So I ate some burgers and got thinking::: here is a solution that works... but you have to chop up your running codes...::: yes, I know, this is just an easier to read refactoring... still...
//......................................... //example1:
<html>
<body>
<div id="id1">DISPLAY</div>
<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setInterval
var i = 0;
function run() {
//pieces of codes to run
if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
if (i >2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
if (i==5){document.getElementById("id1").innerHTML= "<p>all code segment finished running</p>"; clearInterval(t); } //end interval, stops run
i++; //segment of code finished running, next...
}
run();
t=setInterval("run()",1000);
</script>
</body>
</html>
//.................................... //example2:
<html>
<body>
<div id="id1">DISPLAY</div>
<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;
function run() {
//pieces of codes to run, can use switch statement
if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(1000);}
if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(2000);}
if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(3000);}
if (i==3){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>";} //stops automatically
i++;
}
function sleep(dur) {t=setTimeout("run()",dur);} //starts flow control again after dur
run(); //starts
</script>
</body>
</html>
//................. example3:
<html>
<body>
<div id="id1">DISPLAY</div>
<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;
function flow() {
run(i);
i++; //code segment finished running, increment i; can put elsewhere
sleep(1000);
if (i==5) {clearTimeout(t);} //stops flow, must be after sleep()
}
function run(segment) {
//pieces of codes to run, can use switch statement
if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
}
function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur
flow(); //starts flow
</script>
</body>
</html>
//.............. example4:
<html>
<body>
<div id="id1">DISPLAY</div>
<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout, switch
var i = 0;
function flow() {
switch(i)
{
case 0:
run(i);
sleep(1000);
break;
case 1:
run(i);
sleep(2000);
break;
case 5:
run(i);
clearTimeout(t); //stops flow
break;
default:
run(i);
sleep(3000);
break;
}
}
function run(segment) {
//pieces of codes to run, can use switch statement
if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
i++; //current segment of code finished running, next...
}
function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur
flow(); //starts flow control for first time...
</script>
</body>
</html>
This worked for me:
In package.json
Changed "@angular-devkit/build-angular": "^0.800.0" --> "@angular-devkit/build-angular": "^0.10.0" Then:
npm install
ng serve
Specs:
Angular CLI: 6.1.5 Node: 10.15.3 OS: win32 x64 Angular: 6.1.9
If you want an else
you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value
as the statement instead, and remove the filter from the end:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD
for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD
is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!or:
YYYY-MM-DDTHH:MM:SS
for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T
as delimiter between the date and time portion of your DATETIME
.This is valid for SQL Server 2000 and newer.
So in your concrete case - use these strings:
insert into table1 values('2012-02-21T18:10:00', '2012-01-01T00:00:00');
and you should be fine (note: you need to use the international 24-hour format rather than 12-hour AM/PM format for this).
Alternatively: if you're on SQL Server 2008 or newer, you could also use the DATETIME2
datatype (instead of plain DATETIME
) and your current INSERT
would just work without any problems! :-) DATETIME2
is a lot better and a lot less picky on conversions - and it's the recommend date/time data types for SQL Server 2008 or newer anyway.
SELECT
CAST('02-21-2012 6:10:00 PM' AS DATETIME2), -- works just fine
CAST('01-01-2012 12:00:00 AM' AS DATETIME2) -- works just fine
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD
format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
import java.util.HashMap;
import java.util.Scanner;
public class HashMapDemo {
public static void main(String[] args) {
//Create HashMap object to Store Element as Key and Value
HashMap<Character,Integer> hm= new HashMap<Character,Integer>();
//Enter Your String From Console
System.out.println("Enter an String:");
//Create Scanner Class Object From Retrive the element from console to our java application
Scanner sc = new Scanner(System.in);
//Store Data in an string format
String s1=sc.nextLine();
//find the length of an string and check that hashmap object contain the character or not by using
//containskey() if that map object contain element only one than count that value as one or if it contain more than one than increment value
for(int i=0;i<s1.length();i++){
if(!hm.containsKey(s1.charAt(i))){
hm.put(s1.charAt(i),(Integer)1);
}//if
else{
hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
}//else
}//for
System.out.println("The Charecters are:"+hm);
}//main
}//HashMapDemo
You can utilize a HashMap<String, Object>
as follows
public HashMap<String, Object> yourMethod()
{
.... different logic here
HashMap<String, Object> returnHashMap = new HashMap<String, Object>();
returnHashMap.put("objectA", objectAValue);
returnHashMap.put("myString", myStringValue);
returnHashMap.put("myBoolean", myBooleanValue);
return returnHashMap;
}
Then when calling the method in a different scope, you can cast each object back to its initial type:
// call the method
HashMap<String, Object> resultMap = yourMethod();
// fetch the results and cast them
ObjectA objectA = (ObjectA) resultMap.get("objectA");
String myString = (String) resultMap.get("myString");
Boolean myBoolean = (Boolean) resultMap.get("myBoolean");
You can add/edit content on multiple lines by using control button. This is multi edit feature in Notepad++, we need to enable it from settings. Press and hold control, select places where you want to enter text, release control and start typing, this will update the text at all the places selected previously.
Ref: http://notepad-plus-plus.org/features/multi-editing.html
If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):
virtualenv
is a tool to create isolated Python environments.The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into
/usr/lib/python2.7/site-packages
(or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global
site-packages
directory? For instance, on a shared host.In all these cases,
virtualenv
can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).
That's why people consider insert(0,
to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.
We can also use -
$('#x').prop('scrollHeight') <!-- Height -->
$('#x').prop('scrollWidth') <!-- Width -->
Something like a "Stopwatch" object comes to my mind:
Usage:
var st = new Stopwatch();
st.start(); //Start the stopwatch
// As a test, I use the setTimeout function to delay st.stop();
setTimeout(function (){
st.stop(); // Stop it 5 seconds later...
alert(st.getSeconds());
}, 5000);
Implementation:
function Stopwatch(){
var startTime, endTime, instance = this;
this.start = function (){
startTime = new Date();
};
this.stop = function (){
endTime = new Date();
}
this.clear = function (){
startTime = null;
endTime = null;
}
this.getSeconds = function(){
if (!endTime){
return 0;
}
return Math.round((endTime.getTime() - startTime.getTime()) / 1000);
}
this.getMinutes = function(){
return instance.getSeconds() / 60;
}
this.getHours = function(){
return instance.getSeconds() / 60 / 60;
}
this.getDays = function(){
return instance.getHours() / 24;
}
}
What you need is properly a service:
.factory('DataLayer', ['$http',
function($http) {
var factory = {};
var locations;
factory.getLocations = function(success) {
if(locations){
success(locations);
return;
}
$http.get('locations/locations.json').success(function(data) {
locations = data;
success(locations);
});
};
return factory;
}
]);
The locations
would be cached in the service which worked as singleton model. This is the right way to fetch data.
Use this service DataLayer
in your controller and directive is ok as following:
appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
DataLayer.getLocations(function(data){
$scope.locations = data;
});
});
.directive('map', function(DataLayer) {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function(scope, element, attrs) {
DataLayer.getLocations(function(data) {
angular.forEach(data, function(location, key){
//do something
});
});
}
};
});
You're not adding columns to your DataGridView
DataGridView dataGridView1 = new DataGridView();//Create new grid
dataGridView1.Columns[0].Name = "ItemID";// refer to column which is not there
Is it clear now why you get an exception?
Add this line before you use columns to fix the error
dataGridView1.ColumnCount = 5;
Spring Security Documentation mentions the reason for blocking // in the request.
For example, it could contain path-traversal sequences (like /../) or multiple forward slashes (//) which could also cause pattern-matches to fail. Some containers normalize these out before performing the servlet mapping, but others don’t. To protect against issues like these, FilterChainProxy uses an HttpFirewall strategy to check and wrap the request. Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes.
So there are two possible solutions -
Step 1 Create custom firewall that allows slash in URL.
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
return firewall;
}
Step 2 And then configure this bean in websecurity
@Override
public void configure(WebSecurity web) throws Exception {
//@formatter:off
super.configure(web);
web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
....
}
Step 2 is an optional step, Spring Boot just needs a bean to be declared of type HttpFirewall
and it will auto-configure it in filter chain.
Spring Security 5.4 Update
In Spring security 5.4 and above (Spring Boot >= 2.4.0), we can get rid of too many logs complaining about the request rejected by creating the below bean.
import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.firewall.HttpStatusRequestRejectedHandler;
@Bean
RequestRejectedHandler requestRejectedHandler() {
return new HttpStatusRequestRejectedHandler();
}
The command is date
To customise the output there are a myriad of options available, see date --help
for a list.
For example, date '+%A %W %Y %X'
gives Tuesday 34 2013 08:04:22
which is the name of the day of the week, the week number, the year and the time.
At first choose your API level from the following links:
API Level 17: http://dl-ssl.google.com/android/repository/docs-17_r02.zip
API Level 18: http://dl-ssl.google.com/android/repository/docs-18_r02.zip
API Level 19: http://dl-ssl.google.com/android/repository/docs-19_r02.zip
Android-L API doc: http://dl-ssl.google.com/android/repository/docs-L_r01.zip
API Level 24 doc: https://dl-ssl.google.com/android/repository/docs-24_r01.zip
download and extract it in your sdk driectory.
In your eclipse IDE:
at project -> properties -> java build path -> Libraries -> Android x.x -> android.jar -> javadoc
press edit in right:
javadoc URL -> Browse
select "docs/reference/" in archive extracted directory
press validate
... to validate this javadoc.
In your IntelliJ IDEA
at file -> Project Structure
Select SDKs from left panel -> select your sdk from middle panel -> in right panel go to Documentation Paths
tab so click plus icon and select docs/reference/
in archive extracted directory.
enjoy the offline javadoc...
I'm making a guess here, but your start
invocation probably looks like this:
start "\Foo\Bar\Path with spaces in it\program.exe"
This will open a new console window, using “\Foo\Bar\Path with spaces in it\program.exe” as its title.
If you use start
with something that is (or needs to be) surrounded by quotes, you need to put empty quotes as the first argument:
start "" "\Foo\Bar\Path with spaces in it\program.exe"
This is because start
interprets the first quoted argument it finds as the window title for a new console window.
The encodings are spelled out in the buffer documentation.
Character Encodings
utf8
: Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding.utf16le
: Multi-byte encoded Unicode characters. Unlikeutf8
, each character in the string will be encoded using either 2 or 4 bytes.latin1
: Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters fromU+0000
toU+00FF
.Binary-to-Text Encodings
base64
: Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC 4648, Section 5.hex
: Encode each byte as two hexadecimal characters.Legacy Character Encodings
ascii
: For 7-bit ASCII data only. Generally, there should be no reason to use this encoding, as 'utf8' (or, if the data is known to always be ASCII-only, 'latin1') will be a better choice when encoding or decoding ASCII-only text.binary
: Alias for 'latin1'.ucs2
: Alias of 'utf16le'.
I have made django-templated-email in an effort to solve this problem, inspired by this solution (and the need to, at some point, switch from using django templates to using a mailchimp etc. set of templates for transactional, templated emails for my own project). It is still a work-in-progress though, but for the example above, you would do:
from templated_email import send_templated_mail
send_templated_mail(
'email',
'[email protected]',
['[email protected]'],
{ 'username':username }
)
With the addition of the following to settings.py (to complete the example):
TEMPLATED_EMAIL_DJANGO_SUBJECTS = {'email':'hello',}
This will automatically look for templates named 'templated_email/email.txt' and 'templated_email/email.html' for the plain and html parts respectively, in the normal django template dirs/loaders (complaining if it cannot find at least one of those).
If you want to create table with data . First create the table :
create table new_table as ( select * from old_table);
and then insert
insert into new_table ( select * from old_table);
If you want to create table without data . You can use :
create table new_table as ( select * from old_table where 1=0);
A trivial approach would be to replace
<[^>]*>
with nothing. But depending on how ill-structured your input is that may well fail.
You need to tell the query what value to pick for the other columns, MIN
or MAX
seem like suitable choices.
SELECT
U.NAME, MIN(P.PIC_ID)
FROM
USERS U,
PICTURES P,
POSTINGS P1
WHERE
U.EMAIL_ID = P1.EMAIL_ID AND
P1.PIC_ID = P.PIC_ID AND
P.CAPTION LIKE '%car%'
GROUP BY
U.NAME;
i have used following method to use input data from excel sheet: Need to import following as well
import jxl.Workbook;
then
Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0);
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();
it will Work
This should give you the current date minus 1 year:
select now() - interval '1 year';
This one works fine for me :
theme.applyStyle(R.style.AppTheme, true)
Usage:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//The call goes right after super.onCreate() and before setContentView()
theme.applyStyle(R.style.AppTheme, true)
setContentView(layoutId)
onViewCreated(savedInstanceState)
}
For ASP.NET MVC, we successfully save a form with checkboxes via an AJAX POST with the following, which is a combination of several methods referenced in this post, including @Jecoms suggestion:
var form = $('#myForm');
// Serialize the form into a JavaScript object using the jQuery.serializeObject plugin
// https://plugins.jquery.com/serializeObject/
var data = form.serializeObject();
// Change the submitted value of checkboxes to the value of the checked property
$('#myForm input[type=checkbox]').each( function () { data[this.name] = this.checked; } );
// For a MVC controller, convert the JS object back into a query string using jQuery.param function
data = $.param(data);
// Perform AJAX POST with the form data
$.ajax({
async: true,
url: 'mvcActionMethodURL',
type: 'POST',
data: data,
success: function (data, textStatus, xhr) {
},
error: function (xhr, status, error) {
}
});