I was facing the same issue and below step removed all these errors :
To use variables within a query you have to use bindValue()
or bindParam()
. And do not concatenate the variables with " . $variable . "
$statement = "SELECT count(account_id) FROM account
WHERE email = ? AND is_email_confirmed;";
$preparedStatement = $this->postgreSqlHandler->prepare($statement);
$preparedStatement->bindValue(1, $account->getEmail());
$preparedStatement->execute();
$numberRows= $preparedStatement->fetchColumn();
GL
What is the young generation?
The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some survived objects are aged and eventually move to the old generation.
What is the old generation?
The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection
What is the permanent generation?
The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application.
PermGen has been replaced with Metaspace since Java 8 release.
PermSize & MaxPermSize parameters will be ignored now
How does the three generations interact/relate to each other?
Image source & oracle technetwork tutorial article: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html
"The General Garbage Collection Process" in above article explains the interactions between them with many diagrams.
Have a look at summary diagram:
I found a shorter solution that does exactly what I want https://github.com/http-party/node-http-proxy
After installing http-proxy
npm install http-proxy --save
Use it like below in your server/index/app.js
var proxyServer = require('http-route-proxy');
app.use('/api/BLABLA/', proxyServer.connect({
to: 'other_domain.com:3000/BLABLA',
https: true,
route: ['/']
}));
I really have spent days looking everywhere to avoid this issue, tried plenty of solutions and none of them worked but this one.
Hope it is going to help someone else too :)
This works for me,
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime("26/09/2015",ukDtfi).ToString(usDtfi.ShortDatePattern);
Before stumbling onto this post, I came up with this solution - to toggle the TopMost property:
this.TopMost = true;
this.TopMost = false;
I have this code in my form's constructor, eg:
public MyForm()
{
//...
// Brint-to-front hack
this.TopMost = true;
this.TopMost = false;
//...
}
Dave Markle is correct. From W3School's website:
Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit".
In other words, the browser you're using is following W3C's specification.
For React.js, you can do this with more readable code. Hope it helps.
handleCheckboxChange(e) {
console.log('value of checkbox : ', e.target.checked);
}
render() {
return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}
You can adjust the plot margins with plot.margin
in theme()
and then move your axis labels and title with the vjust
argument of element_text()
. For example :
library(ggplot2)
library(grid)
qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.title.x=element_text(vjust=-2)) +
theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
theme(plot.title=element_text(size=15, vjust=3)) +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
will give you something like this :
If you want more informations about the different theme()
parameters and their arguments, you can just enter ?theme
at the R prompt.
EDIT: Firefox and Google Chrome now have a built-in JSON
object, so you can just say alert(JSON.stringify(myArray))
without needing to use a jQuery plugin. This is not part of the Javascript language spec, so you shouldn't rely on the JSON
object being present in all browsers, but for debugging purposes it's incredibly useful.
I tend to use the jQuery-json plugin as follows:
alert( $.toJSON(myArray) );
This prints the array in a format like
[5, 6, 7, 11]
However, for debugging your Javascript code, I highly recommend Firebug It actually comes with a Javascript console, so you can type out Javascript code for any page and see the results. Things like arrays are already printed in the human-readable form used above.
Firebug also has a debugger, as well as screens for helping you view and debug your HTML and CSS.
I set the content-type in the MarshallingView in the ContentNegotiatingViewResolver bean. It works easily, clean and smoothly:
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
</constructor-arg>
<property name="contentType" value="application/xml;charset=UTF-8" />
</bean>
</list>
</property>
The most useful thing you can do here is display/i $pc
, before using stepi
as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi
command.
(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)
In ran into a kind of similar case, were I had to do this . My Table definition look like :
id(bigint)|name (character varying)|results(character varying)
1 | "Peters"| [{"jk1":"jv1"},{"jk1":"jv2"}]
2 | "Russel"| null
To filter out the results column with null or empty in it , what worked was :
SELECT * FROM tablename where results NOT IN ('null','{}');
This returned all rows which are not null on results.
I'm not sure how to fix this query to return the same all rows which are not null on results.
SELECT * FROM tablename where results is not null;
--- hmm what am I missing,casting ? any inputs?
Here is your solution for the problem,
$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
if(ord($i) % 2 != 0)
$letter[] .= $i;
}
print_r($letter);
You need to get the ASCII value for that character which will solve your problem.
Here is ord doc and working code.
For your requirement, you can do like this,
for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
$letter[] .= $i;
}
print_r($letter);
Here set $x as per your requirement.
There is a small problem missed in top-voted answers. Namely, character array may contain 0. If we will use constructor with single parameter as pointed above we will lose some data. The possible solution is:
cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;
Output is:
123
123 123
Try this code:
bool appNotRestarted = true;
This code must also be in the function:
if (appNotRestarted == true) {
appNotRestarted = false;
Application.Restart();
Application.ExitThread();
}
You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye
var groupByReference = (from m in context.Measurements
.GroupBy(m => m.Reference)
.Take(numOfEntries).AsEnumerable()
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
.ThenBy(x => x.Avg)
.ToList() select m);
Your sql query would look similar (depending on your input) this
SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
SELECT [t0].[Reference]
FROM [Measurements] AS [t0]
GROUP BY [t0].[Reference]
) AS [t1]
GO
-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO
-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
Try this:
top.document.getElementById('AppFrame').setAttribute("src",fullPath);
Go to Credential Manager Go to Windows Credentials Delete the entries under Generic Credentials Try connecting again.
I was getting this error; I just put a WHERE
clause for the field which was used within count
clause. it solved the issue. Note: if null value exist, check whether its critical for the report, as its excluded in the count.
Old query:
select city, Count(Emp_ID) as Emp_Count
from Emp_DB
group by city
New query:
select city, Count(Emp_ID) as Emp_Count
from Emp_DB
where Emp_ID is not null
group by city
Your view names need to be unique even if they are pointing to the same view method, or you can add from functools import wraps and use @wraps https://docs.python.org/2/library/functools.html
O(n)
, because you traverse each node once. Or rather - the amount of work you do for each node is constant (does not depend on the rest of the nodes).
on the basis of your only jQuery
tag :)
HTML
<select id="my-select">
<option value="1">This is text 1</option>
<option value="2">This is text 2</option>
<option value="3">This is text 3</option>
</select>
For text --
$(document).ready(function() {
$("#my-select").change(function() {
alert($('#my-select option:selected').html());
});
});
For value --
$(document).ready(function() {
$("#my-select").change(function() {
alert($(this).val());
});
});
I had this issue, but couldn't use an identity column (for various reasons). I settled on this:
DECLARE @id INT
SET @id = 0
UPDATE table SET @id = id = @id + 1
Borrowed from here.
The NuGet package Pdf2Png is available for free and is only protected by the MIT License, which is very open.
I've tested around a bit and this is the code to get it to convert a PDF file to an image (tt does save the image in the debug folder).
using cs_pdf_to_image;
using PdfToImage;
private void BtnConvert_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
string PdfFile = openFileDialog1.FileName;
string PngFile = "Convert.png";
List<string> Conversion = cs_pdf_to_image.Pdf2Image.Convert(PdfFile, PngFile);
Bitmap Output = new Bitmap(PngFile);
PbConversion.Image = Output;
}
catch(Exception E)
{
MessageBox.Show(E.Message);
}
}
}
To execute a binary, use: ./binary_name
.
If you get an error:
bash: ./binary_name: cannot execute binary file
it'll be because it was compiled using a tool chain that was for a different target to that which you're attempting to run the binary on.
For example, if you compile 'binary_name.c' with arm-none-linux-gnueabi-gcc
and try run the generated binary on an x86 machine, you will get the aforementioned error.
Normally there are two ways of initializing variables, 1) using the sess.run(tf.global_variables_initializer())
as the previous answers noted; 2) the load the graph from checkpoint.
You can do like this:
sess = tf.Session(config=config)
saver = tf.train.Saver(max_to_keep=3)
try:
saver.restore(sess, tf.train.latest_checkpoint(FLAGS.model_dir))
# start from the latest checkpoint, the sess will be initialized
# by the variables in the latest checkpoint
except ValueError:
# train from scratch
init = tf.global_variables_initializer()
sess.run(init)
And the third method is to use the tf.train.Supervisor. The session will be
Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready.
sv = tf.train.Supervisor([parameters])
sess = sv.prepare_or_wait_for_session()
Combining the different solutions, this is what worked for me.
$(document).ready(function () {
$('iframe').on('load', function() {
$("iframe").contents().find("#back-link").css("display", "none");
});
});
str_replace
- it is evident solution. But sometimes you need to know what exactly the spaces there are. I have a problem with spaces from csv file.
There were two chars but one of them was 0160 (0x0A0) and other was invisible (0x0C2)
my final solution:
$str = preg_replace('/\xC2\xA0+/', '', $str);
I found the invisible symbol from HEX viewer from mc (midnight viewer - F3 - F9)
What you have should work but can be reduced to:
select * from table where concat_ws(' ',first_name,last_name)
like '%$search_term%';
Can you provide an example name and search term where this doesn't work?
%cd C:\Users\asus\Desktop\python
import pandas as pd
df = pd.read_csv('value.txt')
df.head()
Date price factor_1 factor_2
0 2012-06-11 1600.20 1.255 1.548
1 2012-06-12 1610.02 1.258 1.554
2 2012-06-13 1618.07 1.249 1.552
3 2012-06-14 1624.40 1.253 1.556
4 2012-06-15 1626.15 1.258 1.552
Completely reset?
Delete the .git
directory locally.
Recreate the git repostory:
$ cd (project-directory)
$ git init
$ (add some files)
$ git add .
$ git commit -m 'Initial commit'
Push to remote server, overwriting. Remember you're going to mess everyone else up doing this … you better be the only client.
$ git remote add origin <url>
$ git push --force --set-upstream origin master
If you've just got the iterator then that's what you'll have to do - it doesn't know how many items it's got left to iterate over, so you can't query it for that result. There are utility methods that will seem to do this efficiently (such as Iterators.size()
in Guava), but underneath they're just consuming the iterator and counting as they go, the same as in your example.
However, many iterators come from collections, which you can often query for their size. And if it's a user made class you're getting the iterator for, you could look to provide a size() method on that class.
In short, in the situation where you only have the iterator then there's no better way, but much more often than not you have access to the underlying collection or object from which you may be able to get the size directly.
First of all you need to be sure that all attributes of that comes from the service are named the same in your class. Then you can parse the object and after that assign it to your new variable, something like this:
const parsedJSON = JSON.parse(serverResponse);
const employeeObj: Employee = parsedJSON as Employee;
Try that!
This is assuming all words are separated by spaces:
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "What are you looking at";
int i, n = strlen(string);
int tail = n-1;
for(i=n-1;i>=0;i--)
{
if(string[i] == ' ' || i == 0)
{
int cursor = (i==0? i: i+1);
while(cursor <= tail)
printf("%c", string[cursor++]);
printf(" ");
tail = i-1;
}
}
return 0;
}
NOTE: NTLK no longer supports clean_html
function
Original answer below, and an alternative in the comments sections.
Use NLTK
I wasted my 4-5 hours fixing the issues with html2text. Luckily i could encounter NLTK.
It works magically.
import nltk
from urllib import urlopen
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urlopen(url).read()
raw = nltk.clean_html(html)
print(raw)
Using "fill" attribute helps in cases like this. You can remove the text from axis using element_blank()
and show multi color bar chart with a legend. I am plotting a part removal frequency in a repair shop as below
ggplot(data=df_subset,aes(x=Part,y=Removal_Frequency,fill=Part))+geom_bar(stat="identity")+theme(axis.text.x = element_blank())
I went for this solution in my case as I had many bars in bar chart and I was not able to find a suitable font size which is both readable and also small enough not to overlap each other.
string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");
if (indexOfHyphen >= 0)
{
string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
Console.WriteLine(contentAfterLastHyphen );
}
The solution, if your list items can be display: inline
is quite easy:
#footer { text-align: center; }
#footer ul { list-style: none; }
#footer ul li { display: inline; }
However, many times you must use display:block
on your <li>
s. The following CSS will work, in this case:
#footer { width: 100%; overflow: hidden; }
#footer ul { list-style: none; position: relative; float: left; display: block; left: 50%; }
#footer ul li { position: relative; float: left; display: block; right: 50%; }
I got this when trying to push to a dokku instance. Turns out the disk was full on my server.
Ran:
du -f
And result was:
Filesystem Size Used Avail Use% Mounted on
udev 476M 0 476M 0% /dev
tmpfs 100M 4.4M 95M 5% /run
/dev/xvda1 7.8G 7.4G 8.9M 100% /
I feel most people have pip installed already with Python. On Windows, one way to check for pip is to open Command Prompt and typing in:
python -m pip
If you get Usage and Commands instructions then you have it installed.
If python
was not found though, then it needs to be added to the path. Alternatively you can run the same command from within the installation directory of python.
If all is good, then this command will install BeautifulSoup easily:
python -m pip install BeautifulSoup4
Screenshot:
N' now I see I need to upgrade my pip, which I just did :)
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
Try the following code:
if ( (myList!= null) && (!myList.Any()) )
{
// Add new item
myList.Add("new item");
}
A late EDIT because for these checks I now like to use the following solution. First, add a small reusable extension method called Safe():
public static class IEnumerableExtension
{
public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
{
if (source == null)
{
yield break;
}
foreach (var item in source)
{
yield return item;
}
}
}
And then, you can do the same like:
if (!myList.Safe().Any())
{
// Add new item
myList.Add("new item");
}
I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.
And another EDIT, using ? (Null-conditional) operator (C# 6.0):
if (!myList?.Any() ?? false)
{
// Add new item
myList.Add("new item");
}
You can use the jQuery ajax method link if you want to pass data from client to server.
In this case you can use $_SERVER['HTTP_USER_AGENT']
variable to found browser user agent.
throw something
works with both object and strings.But it is less supported than the other method.throw new Error("")
Will only work with strings and turns objects into useless [Object obj] in the catch block.
For iOS 11, I found that a modified version of Mohamed Saleh's answer worked best, with some improvements based on Apple's documentation. It animates nicely, avoids any ugly hacks or hardcoded values, and uses row heights already set in Interface Builder.
The basic concept is to set the row height to 0 for any hidden rows. Then use tableView.performBatchUpdates
to trigger an animation that works consistently.
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == indexPathOfHiddenCell {
if cellIsHidden {
return 0
}
}
// Calling super will use the height set in your storyboard, avoiding hardcoded values
return super.tableView(tableView, heightForRowAt: indexPath)
}
You'll want to make sure cellIsHidden
and indexPathOfHiddenCell
are set appropriately to your use case. For my code they're properties on my table view controller.
In whatever method controls the visibility (likely a button action or didSelectRow
), toggle the cellIsHidden state, inside a performBatchUpdates
block:
tableView.performBatchUpdates({
// Use self to capture for block
self.cellIsHidden = !self.cellIsHidden
}, completion: nil)
Apple recommends performBatchUpdates
over beginUpdates
/endUpdates
whenever possible.
For CUDA7.5 these lines work:
sudo ln -s /usr/bin/gcc-4.9 /usr/local/cuda/bin/gcc
sudo ln -s /usr/bin/g++-4.9 /usr/local/cuda/bin/g++
When I do what explains some answers:
The result is:
So, anybody can explain really really how to delete an old App ID?
My opinion is: Apple does not let you remove them. I suppose it is a way to maintain the traceability or the historical of the published.
And of course: application is no longer available in the App Store. It was available (in the past), yes.
General way:
##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
for line in text:
file.write(line)
file.write('\n')
OR
Using CSV writer :
import csv
with open(<path to output_csv>, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)
OR
Simplest way:
f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()
I think you need to put it under src/main/resources
and load it as follows:
props.load(new FileInputStream("src/main/resources/myconf.properties"));
The way you are trying to load it will first check in base folder of your project. If it is in target/classes
and you want to load it from there do the following:
props.load(new FileInputStream("target/classes/myconf.properties"));
It's possible to decide which reactor projects to build by specifying the -pl
command line argument:
$ mvn --help
[...]
-pl,--projects <arg> Build specified reactor projects
instead of all projects
[...]
It accepts a comma separated list of parameters in one of the following forms:
[groupId]:artifactId
Thus, given the following structure:
project-root [com.mycorp:parent]
|
+ --- server [com.mycorp:server]
| |
| + --- orm [com.mycorp.server:orm]
|
+ --- client [com.mycorp:client]
You can specify the following command line:
mvn -pl .,server,:client,com.mycorp.server:orm clean install
to build everything. Remove elements in the list to build only the modules you please.
EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el
flag that excludes projects from the reactor, similarly to what -pl
does:
Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.
This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.
It's not perfect, and you would usually resort to techniques like the Pimpl Idiom to properly separate interface and implementation, but it's a good start.
(I tried previous answers but they lacks in some points. For example if you don't do a return;
after finishing activity, remaining activity code runs. Also you need to edit onCreate with return. If you doesn't run super.onCreate() you will get a runtime error)
Say you have MainActivity
and ChildActivity
.
Inside ChildActivity add this:
Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
return true;
Inside MainActivity's onCreate add this:
@Override
public void onCreate(Bundle savedInstanceState) {
mContext = getApplicationContext();
super.onCreate(savedInstanceState);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
// your current codes
// your current codes
}
Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.
In Java as other suggest
listitem.setClickable(false);
Or in xml:
android:clickable="false"
It works very fine
Note that if you have table name with '_', it is removed in sequence name.
For example, table name: user_tokens column: id Sequence name: usertokens_id_seq
For text:
[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
For cell background
[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
import os
import boto3
#initiate s3 resource
s3 = boto3.resource('s3')
# select bucket
my_bucket = s3.Bucket('my_bucket_name')
# download file into current directory
for s3_object in my_bucket.objects.all():
# Need to split s3_object.key into path and file name, else it will give error file not found.
path, filename = os.path.split(s3_object.key)
my_bucket.download_file(s3_object.key, filename)
In this specific case (there is always a single character at the start you want to remove) you'll want:
str.substring(1)
However, if you want to be able to detect if the comma is there and remove it if it is, then something like:
if (str[0] == ',') {
str = str.substring(1);
}
Non-matched part of the URL is exposed as a request attribute named HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE
:
@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
...
}
In my case, I had to do this
// Initialization in the dom
// Consider the muted attribute
<audio id="notification" src="path/to/sound.mp3" muted></audio>
// in the js code unmute the audio once the event happened
document.getElementById('notification').muted = false;
document.getElementById('notification').play();
Very similar to Marc, only difference I would make would be to spool to a parameter like so:
WHENEVER SQLERROR EXIT 1
SET LINES 32000
SET TERMOUT OFF ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET SERVEROUTPUT ON
spool &1
-- Code
spool off
exit
And then to call the SQLPLUS as
sqlplus -s username/password@sid @tmp.sql /tmp/output.txt
I achieved it by switching to landscape orientation and setting layout params to MATCH_PARENT
. Just before switching to fullscreen mode, we need to store current orientation mode and VideoView
params indefaultScreenOrientationMode
and defaultVideoViewParams
variables correspondingly. So that we can use them when we exit from video fullscreen mode. Thus, when you want to open video in fullscreen mode, use makeVideoFullScreen()
method, to exit - exitVideoFullScreen()
.
Please, note I used RelativeLayout
for my VideoView
, in your case it can be another layout type.
private RelativeLayout.LayoutParams defaultVideoViewParams;
private int defaultScreenOrientationMode;
// play video in fullscreen mode
private void makeVideoFullScreen() {
defaultScreenOrientationMode = getResources().getConfiguration().orientation;
defaultVideoViewParams = (LayoutParams) videoView.getLayoutParams();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
videoView.postDelayed(new Runnable() {
@Override
public void run() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
videoView.setLayoutParams(params);
videoView.layout(10, 10, 10, 10);
}
}, 700);
}
// close fullscreen mode
private void exitVideoFullScreen() {
setRequestedOrientation(defaultScreenOrientationMode);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
videoView.postDelayed(new Runnable() {
@Override
public void run() {
videoView.setLayoutParams(defaultVideoViewParams);
videoView.layout(10, 10, 10, 10);
}
}, 700);
}
There is a online decompiler for android apks
http://www.decompileandroid.com/
Upload apk from local machine
Wait some moments
download source code in zip format.
Unzip it, you can view all resources correctly but all java files are not correctly decompiled.
For full detail visit this answer
It is best to use two DateTimePickers for the Job One will be the default for the date section and the second DateTimePicker is for the time portion. Format the second DateTimePicker as follows.
timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
timePortionDateTimePicker.ShowUpDown = true;
The Two should look like this after you capture them
To get the DateTime from both these controls use the following code
DateTime myDate = datePortionDateTimePicker.Value.Date +
timePortionDateTimePicker.Value.TimeOfDay;
To assign the DateTime to both these controls use the following code
datePortionDateTimePicker.Value = myDate.Date;
timePortionDateTimePicker.Value = myDate.TimeOfDay;
Haven't you heard about the Comparable
interface being implemented by String
? If no, try to use
"abcda".compareTo("abcza")
And it will output a good root for a solution to your problem.
No, there is not, for starters, it is impossible to have an array with elements sharing the same key
$x =array();
$x['foo'] = 'bar' ;
$x['foo'] = 'baz' ; #replaces 'bar'
Secondarily, if you wish to merely prefix the numbers so that
$x[0] --> $x['foo_0']
That is computationally implausible to do without looping. No php functions presently exist for the task of "key-prefixing", and the closest thing is "extract" which will prefix numeric keys prior to making them variables.
The very simplest way is this:
function rekey( $input , $prefix ) {
$out = array();
foreach( $input as $i => $v ) {
if ( is_numeric( $i ) ) {
$out[$prefix . $i] = $v;
continue;
}
$out[$i] = $v;
}
return $out;
}
Additionally, upon reading XMLWriter usage, I believe you would be writing XML in a bad way.
<section>
<foo_0></foo_0>
<foo_1></foo_1>
<bar></bar>
<foo_2></foo_2>
</section>
Is not good XML.
<section>
<foo></foo>
<foo></foo>
<bar></bar>
<foo></foo>
</section>
Is better XML, because when intrepreted, the names being duplicate don't matter because they're all offset numerically like so:
section => {
0 => [ foo , {} ]
1 => [ foo , {} ]
2 => [ bar , {} ]
3 => [ foo , {} ]
}
You could always try the Synth look & feel. You provide an xml file that acts as a sort of stylesheet, along with any images you want to use. The code might look like this:
try {
SynthLookAndFeel synth = new SynthLookAndFeel();
Class aClass = MainFrame.class;
InputStream stream = aClass.getResourceAsStream("\\default.xml");
if (stream == null) {
System.err.println("Missing configuration file");
System.exit(-1);
}
synth.load(stream, aClass);
UIManager.setLookAndFeel(synth);
} catch (ParseException pe) {
System.err.println("Bad configuration file");
pe.printStackTrace();
System.exit(-2);
} catch (UnsupportedLookAndFeelException ulfe) {
System.err.println("Old JRE in use. Get a new one");
System.exit(-3);
}
From there, go on and add your JButton like you normally would. The only change is that you use the setName(string) method to identify what the button should map to in the xml file.
The xml file might look like this:
<synth>
<style id="button">
<font name="DIALOG" size="12" style="BOLD"/>
<state value="MOUSE_OVER">
<imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
<insets top="2" botton="2" right="2" left="2"/>
</state>
<state value="ENABLED">
<imagePainter method="buttonBackground" path="dirt.png" sourceInsets="2 2 2 2"/>
<insets top="2" botton="2" right="2" left="2"/>
</state>
</style>
<bind style="button" type="name" key="dirt"/>
</synth>
The bind element there specifies what to map to (in this example, it will apply that styling to any buttons whose name property has been set to "dirt").
And a couple of useful links:
http://javadesktop.org/articles/synth/
http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/synth.html
Another example: Hexadecimal values for css colors start with a pound sign, or hash (#), then six characters that can either be a numeral or a letter between A and F, inclusive.
^#[0-9a-fA-F]{6}
call window.getComputedStyle()
should force a reflow
I had the same issue today using primefaces (primeng) and angular 7. Add the following to your style.css
p-button {
-webkit-appearance: none !important;
}
i am also using a bit of bootstrap which has a reboot.css, that overrides it with (thats why i had to add !important)
button {
-webkit-appearance: button;
}
do not turn off firewall, Go Control Panel\System and Security\Windows Firewall then Advanced settings then Inbound Rules->From right pan choose New Rule-> Port-> TCP and type in port number 80 then give a name in next window, that's it.
HTML : Pass the whole body inside on click
div class="calculate" id="calculate">
<div class="button" id="button" onclick="myCode(this.body)"> CALCULATE ! </div>
</div>
Then write the JavaScript code inside the function "myCode()"
function myCode()
{
var bill = document.getElementById("currency").value ;
var people_count = document.getElementById("number1").value;
var select_value = document.getElementById("select").value;
var calculate = document.getElementById("calculate");
calculate.addEventListener("click" ,function()
{
console.log(bill);
console.log(people_count);
console.log(select_value);
});
}
you will get your values I am using visual studio code editor
When Card I always use RoundedRectangleBorder.
Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(20.0),
child: Container(
child: Column(
children: <Widget>[
ListTile(
title: Text(
'example',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
],
),
),
),
Use "in" or "where".
Its gonna be something like this:
db.mycollection.find( { $where : function() {
return ( this.startTime < Now() && this.expireTime > Now() || this.expireTime == null ); } } );
From the Java Language Specification - 15.26.2 Compound Assignment Operators.
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
So a &= b;
is equivalent to a = a & b;
.
(In some usages, the type-casting makes a difference to the result, but in this one b
has to be boolean
and the type-cast does nothing.)
And, for the record, a &&= b;
is not valid Java. There is no &&=
operator.
In practice, there is little semantic difference between a = a & b;
and a = a && b;
. (If b
is a variable or a constant, the result is going to be the same for both versions. There is only a semantic difference when b
is a subexpression that has side-effects. In the &
case, the side-effect always occurs. In the &&
case it occurs depending on the value of a
.)
On the performance side, the trade-off is between the cost of evaluating b
, and the cost of a test and branch of the value of a
, and the potential saving of avoiding an unnecessary assignment to a
. The analysis is not straight-forward, but unless the cost of calculating b
is non-trivial, the performance difference between the two versions is too small to be worth considering.
The simple way to fill the shape with the Radius is:
(view.getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN);
ssh-keygen isn't a windows executable.
You can use PuttyGen (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) for example to create a key
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.
Below is the code snippet for it :
//WorkAround
for (String color : colors ){
String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));
Jmi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
IconA icon = (IconA) item.getIcon();
// HERE YOU USE THE String color variable and no errors!!!
Color kolorIkony = getColour(color);
textArea.setForeground(kolorIkony);
}
});
mnForeground.add(Jmi);
}
}
Just follow closely the chain of events.
Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.
Try this:
while (true) {
int x;
iFile >> x;
if( iFile.eof() ) break;
cerr << x << endl;
}
By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.
For practically all date and time matters I prefer to simplify things, very, very simple... Down to seconds stored in integers.
Integers will always be supported as integers in databases, flat files, etc. You do a little math and cast it into another type and you can format the date anyway you want.
Doing it this way, you don't have to worry when [insert current favorite database here] is replaced with [future favorite database] which coincidentally didn't use the date format you chose today.
It's just a little math overhead (eg. methods--takes two seconds, I'll post a gist if necessary) and simplifies things for a lot of operations regarding date/time later.
$('body').on('mouseenter mouseleave','.dropdown',function(e){_x000D_
var _d=$(e.target).closest('.dropdown');_x000D_
if (e.type === 'mouseenter')_d.addClass('show');_x000D_
setTimeout(function(){_x000D_
_d.toggleClass('show', _d.is(':hover'));_x000D_
$('[data-toggle="dropdown"]', _d).attr('aria-expanded',_d.is(':hover'));_x000D_
},300);_x000D_
});_x000D_
_x000D_
/* this is not needed, just prevents page reload when a dd link is clicked */_x000D_
$('.dropdown a').on('click tap', e => e.preventDefault())
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href>Navbar</a>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href>Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href>Features</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href>Pricing</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<a class="dropdown-item" href>Action</a>_x000D_
<a class="dropdown-item" href>Another action</a>_x000D_
<a class="dropdown-item" href>Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29
JComponent has a setFont() method. You will control the font there, not on the String.
Such as
JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));
I think you have 2 separate problems, 1. with restoring and 2. with creating
For 1. you could try checking to see if the file was transferred properly (one easy way would be to check the md5 of the file on the server and again on the local environment to see if they match).
From Hadoop page,
start-all.sh
This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.
start-dfs.sh
This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need start-mapred.sh
to separately start the job tracker
start-all.sh/stop-all.sh
has to be run on the master node
You would use start-all.sh
on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).
In multi-node setup,
You will use start-all.sh
on the master node and would start what is necessary on the slaves as well.
Alternatively,
Use start-dfs.sh
on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.
Use start-mapred.sh
on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file.
hadoop-daemon.sh
as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as start-all.sh
.In a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.
Have a look at this start-all.sh
it call config followed by dfs and mapred
I had an error with an array getting the max and the min so my solution was:
int max = Arrays.stream(arrayWithInts).max().getAsInt();
int min = Arrays.stream(arrayWithInts).min().getAsInt();
Use the hasClass
method:
jQueryCollection.hasClass(className);
or
$(selector).hasClass(className);
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
Note: If you pass a className
argument that contains whitespace, it will be matched literally against the collection's elements' className
string. So if, for instance, you have an element,
<span class="foo bar" />
then this will return true
:
$('span').hasClass('foo bar')
and these will return false
:
$('span').hasClass('bar foo')
$('span').hasClass('foo bar')
The latest release of Requests will build CookieJars for you from simple dictionaries.
import requests
cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
r = requests.post('http://wikipedia.org', cookies=cookies)
Enjoy :)
I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.
Thought I would chip in here with when I have found ON
to be more useful than USING
. It is when OUTER
joins are introduced into queries.
ON
benefits from allowing the results set of the table that a query is OUTER
joining onto to be restricted while maintaining the OUTER
join. Attempting to restrict the results set through specifying a WHERE
clause will, effectively, change the OUTER
join into an INNER
join.
Granted this may be a relative corner case. Worth putting out there though.....
For example:
CREATE TABLE country (
countryId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
country varchar(50) not null,
UNIQUE KEY countryUIdx1 (country)
) ENGINE=InnoDB;
insert into country(country) values ("France");
insert into country(country) values ("China");
insert into country(country) values ("USA");
insert into country(country) values ("Italy");
insert into country(country) values ("UK");
insert into country(country) values ("Monaco");
CREATE TABLE city (
cityId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
countryId int(10) unsigned not null,
city varchar(50) not null,
hasAirport boolean not null default true,
UNIQUE KEY cityUIdx1 (countryId,city),
CONSTRAINT city_country_fk1 FOREIGN KEY (countryId) REFERENCES country (countryId)
) ENGINE=InnoDB;
insert into city (countryId,city,hasAirport) values (1,"Paris",true);
insert into city (countryId,city,hasAirport) values (2,"Bejing",true);
insert into city (countryId,city,hasAirport) values (3,"New York",true);
insert into city (countryId,city,hasAirport) values (4,"Napoli",true);
insert into city (countryId,city,hasAirport) values (5,"Manchester",true);
insert into city (countryId,city,hasAirport) values (5,"Birmingham",false);
insert into city (countryId,city,hasAirport) values (3,"Cincinatti",false);
insert into city (countryId,city,hasAirport) values (6,"Monaco",false);
-- Gah. Left outer join is now effectively an inner join
-- because of the where predicate
select *
from country left join city using (countryId)
where hasAirport
;
-- Hooray! I can see Monaco again thanks to
-- moving my predicate into the ON
select *
from country co left join city ci on (co.countryId=ci.countryId and ci.hasAirport)
;
You can just get the individual time components and calculate the total. You seem to be expecting Moment to already have this feature neatly packaged up for you, but it doesn't. I doubt it's something that people have a need for very often.
Example:
var m = moment();_x000D_
_x000D_
var ms = m.milliseconds() + 1000 * (m.seconds() + 60 * (m.minutes() + 60 * m.hours()));_x000D_
_x000D_
console.log(ms);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
When specifying your cron values you'll need to make sure that your values fall within the ranges. For instance, some cron's use a 0-7 range for the day of week where both 0 and 7 represent Sunday. We do not(check below).
Seconds: 0-59
Minutes: 0-59
Hours: 0-23
Day of Month: 1-31
Months: 0-11
Day of Week: 0-6
reference: https://github.com/ncb000gt/node-cron
No need to make the nested class as static but it must be public
public class Test {
public static void main(String[] args) {
Shape shape = new Shape();
Shape s = shape.new Shape.ZShape();
}
}
An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.
It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.
Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.
Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.
As you see, that's actually a natural error ..
A typical construct for reading from an Unpickler object would be like this ..
try:
data = unpickler.load()
except EOFError:
data = list() # or whatever you want
EOFError is simply raised, because it was reading an empty file, it just meant End of File ..
Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem. If you are in Eclipse, you can do this by going through Window -> Preferences and then it is in DDMS under Android.
As described here: Android error: Failed to install *.apk on device *: timeout
Using url-loader, described here (SurviveJS - Loading Images), you can then use in your code :
import LogoImg from 'YOUR_PATH/logo.png';
and
<img src={LogoImg}/>
Edit: a precision, images are inlined in the js archive with this technique. It can be worthy for small images, but use the technique wisely.
You can do this with the hex codec. ie:
>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'
there is new API in Android 11 called WindowInsetsController
, Apps can get access to a controller from any view, by which we can use hide()
and show()
method
val controller = view.windowInsetsController
// Show the keyboard (IME)
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())
see https://developer.android.com/reference/android/view/WindowInsetsController
If you have a double array named numbers
, you can use:
firstNum = numbers[0];
lastNum = numbers[numbers.length-1];
or with ArrayList
firstNum = numbers.get(0);
lastNum = numbers.get(numbers.size() - 1);
What database are you using? As far as I'm aware, there is no database agnostic method for doing this.
That's an easy one:
[aView convertPoint:localPosition toView:nil];
... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:
[aView.superview convertPoint:aView.frame.origin toView:nil];
2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...
@media (max-width: @iphone-screen) {
background-attachment:inherit;
background-size:cover;
-webkit-background-size:cover;
}
from sklearn import svm, datasets
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import matplotlib.pyplot as plt
breast_cancer = load_breast_cancer()
X = breast_cancer.data
y = breast_cancer.target
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33, random_state=44)
clf = LogisticRegression(penalty='l2', C=0.1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy", metrics.accuracy_score(y_test, y_pred))
y_pred_proba = clf.predict_proba(X_test)[::,1]
fpr, tpr, _ = metrics.roc_curve(y_test, y_pred_proba)
auc = metrics.roc_auc_score(y_test, y_pred_proba)
plt.plot(fpr,tpr,label="data 1, auc="+str(auc))
plt.legend(loc=4)
plt.show()
It’s a common error and it can be easily fixed. This error message is an indication of that the file you are trying to import is larger than your web host allows
No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See FAQ 1.16.
Solution:
A solution is easy, Need to increase file size upload limit as per your requirement.
First of all, stop the XAMPP/Wamp and then find the php.ini
in the following locations. Windows: C:\xampp\php\php.ini
Open the php.ini
file. Find these lines in the php.ini
file and replace it following numbers
upload_max_filesize = 64M
And then restart your XAMPP/Wamp
NOTE: For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder)
Mac Users, let me save you the time:
The pageContext
is an implicit object available in JSPs. The EL documentation says
The context for the JSP page. Provides access to various objects including:
servletContext: ...
session: ...
request: ...
response: ...
Thus this expression will get the current HttpServletRequest
object and get the context path for the current request and append /JSPAddress.jsp
to it to create a link (that will work even if the context-path this resource is accessed at changes).
The primary purpose of this expression would be to keep your links 'relative' to the application context and insulate them from changes to the application path.
For example, if your JSP (named thisJSP.jsp
) is accessed at http://myhost.com/myWebApp/thisJSP.jsp
, thecontext path will be myWebApp
. Thus, the link href generated will be /myWebApp/JSPAddress.jsp
.
If someday, you decide to deploy the JSP on another server with the context-path of corpWebApp
, the href generated for the link will automatically change to /corpWebApp/JSPAddress.jsp
without any work on your part.
I found that with spring boot 2.0.2.RELEASE, configuring spring-boot-starter-data-jpa and com.h2database in the POM file is not just enough to have H2 console working. You must configure spring-boot-devtools as below. Optionally you could follow the instruction from Aaron Zeckoski in this post
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
Of all the answers I think this one is the best:
let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))
that transforms:
{
a: { p: 1, q: 2},
b: { p: 3, q: 4}
}
to:
[
{ key: 'a', p: 1, q: 2 },
{ key: 'b', p: 3, q: 4 }
]
To transform back:
let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})
To transform back keeping the key in the value:
let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})
Will give:
{
a: { key: 'a', p: 1, q: 2 },
b: { key: 'b', p: 3, q: 4 }
}
For the last example you can also use lodash _.keyBy(arr, 'key')
or _.keyBy(arr, i => i.key)
.
You have to get the window using the new JSDOM API.
const jsdom = require("jsdom");
const { window } = new jsdom.JSDOM(`...`);
var $ = require("jquery")(window);
r stands for a raw string, so things like \ will be automatically escaped by Python.
Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.
In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)
As per re.match vs re.search here's an example that will clarify it for you:
>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>
So search will find a match anywhere, match will only start at the beginning
I've found a way to get only the Contacts application:
git clone https://android.googlesource.com/platform/packages/apps/Contacts
which is good enough for me for now, but doesn't answer the question of browsing the code on the web.
kubectl create can work with one object configuration file at a time. This is also known as imperative management
kubectl create -f filename|url
kubectl apply works with directories and its sub directories containing object configuration yaml files. This is also known as declarative management. Multiple object configuration files from directories can be picked up. kubectl apply -f directory/
Details :
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-config/
No need to do so much works..
var query = from c in obj.tbCourses
where ...
select c;
Then you can use:
List<course> list_course= query.ToList<course>();
It works fine for me.
To avoid an input with only spaces, use: "[a-zA-Z0-9]+[a-zA-Z0-9 ]+"
.
eg: abc | abc aBc | abc 123 AbC 938234
To ensure, for example, that a first AND last name are entered, use a slight variation like
"[a-zA-Z]+[ ][a-zA-Z]+"
eg: abc def
If I understand your question correctly, you need %p
to show the address that a pointer is using, for example:
int main() {
int a = 5;
int *p = &a;
printf("%d, %u, %p", p, p, p);
return 0;
}
will output something like:
-1083791044, 3211176252, 0xbf66a93c
long
can only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float
the value before calling the long
. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int
to provide the key as well.
So, the answer is long(float('234.89'))
or it could just be int(float('234.89'))
if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int
From the official documentation regarding the Formatter class:
The constructor takes two optional arguments: a message format string and a date format string.
So change
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
to
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
"%Y-%m-%d %H:%M:%S")
One other point that I didn't see anyone make:
If you don't do anything in your catch {} block, having a try...catch is pointless. I see this all the time:
try
{
//Code here
}
catch
{
throw;
}
Or worse:
try
{
//Code here
}
catch(Exception ex)
{
throw ex;
}
Worst yet:
try
{
//Code here
}
catch(Exception ex)
{
throw new System.Exception(ex.Message);
}
First of all you should fix modal HTML structure. Now it's not correct, you don't need class .hide
:
<div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body edit-content">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Then links should point to this modal via data-target
attribute:
<a href="#myModal" data-toggle="modal" id="1" data-target="#edit-modal">Edit 1</a>
Finally Js part becomes very simple:
$('#edit-modal').on('show.bs.modal', function(e) {
var $modal = $(this),
esseyId = e.relatedTarget.id;
$.ajax({
cache: false,
type: 'POST',
url: 'backend.php',
data: 'EID=' + essayId,
success: function(data) {
$modal.find('.edit-content').html(data);
}
});
})
I've the same problem right now. check if you fix fetch in lazy with a @jsonIQgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="teachers")
@JsonIgnoreProperties("course")
Teacher teach;
Just delete the "(fetch=...)" or the annotation "@jsonIgnore" and it will work
@ManyToOne
@JoinColumn(name="teachers")
@JsonIgnoreProperties("course")
Teacher teach;
You DO NOT have to provide a body for getters and setters IF you'd like the automated compiler to provide a basic implementation.
This DOES however require you to make sure you're using the v3.5 compiler by updating your web.config to something like
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
with 5 columns and colspan
, this is possible (click here) (but doesn't make much sense to me):
<table width="100%" border="1" bgcolor="#ffffff">
<colgroup>
<col width="25%">
<col width="25%">
<col width="25%">
<col width="5%">
<col width="20%">
</colgroup>
<tr>
<td>25</td>
<td colspan="2">50</td>
<td colspan="2">25</td>
</tr>
<tr>
<td colspan="2">50</td>
<td colspan="2">30</td>
<td>20</td>
</tr>
</table>
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
If you are using Eclipse then please note that while running on XDebug mode the magic constant __FILE__ will always be evaluated to:
xdebug://debug-eval
So the following check will return true if your session is under XDebug:
$is_xdebug = false !== strpos(__FILE__,'xdebug'); // true while on XDebug
If using Windows as host, you can use WinSCP to connect to Docker and transfer files through the GUI.
If on Linux, the scp
command would also work through the terminal.
Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:
Using client As New Net.WebClient
Dim reqparm As New Specialized.NameValueCollection
reqparm.Add("param1", "somevalue")
reqparm.Add("param2", "othervalue")
Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using
The key part is this:
client.UploadValues(someurl, "POST", reqparm)
It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.
var str = "hello world & hello universe"
In order to replace both Spaces and Symbols in one shot, we can use the below regex code.
str.replaceAll("\\W+","")
Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches
Try it!
For those who do not want to include System.Web
in projects that don't already use it, you can use FormUrlEncodedContent
from System.Net.Http
and do something like the following:
string query;
using(var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]{
new KeyValuePair<string, string>("ham", "Glazed?"),
new KeyValuePair<string, string>("x-men", "Wolverine + Logan"),
new KeyValuePair<string, string>("Time", DateTime.UtcNow.ToString()),
})) {
query = content.ReadAsStringAsync().Result;
}
string query;
using(var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{ "ham", "Glaced?"},
{ "x-men", "Wolverine + Logan"},
{ "Time", DateTime.UtcNow.ToString() },
})) {
query = content.ReadAsStringAsync().Result;
}
you can read this tutorial for how to use functions of statistical distributions in python. http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
#initialize a normal distribution with frozen in mean=-1, std. dev.= 1
rv = norm(loc = -1., scale = 1.0)
rv1 = norm(loc = 0., scale = 2.0)
rv2 = norm(loc = 2., scale = 3.0)
x = np.arange(-10, 10, .1)
#plot the pdfs of these normal distributions
plt.plot(x, rv.pdf(x), x, rv1.pdf(x), x, rv2.pdf(x))
I needed something a bit different than what these solutions gave, in that I needed to create an array with a number of distinct random numbers held to a specified range. Below is my solution.
function getDistinctRandomIntForArray(array, range){
var n = Math.floor((Math.random() * range));
if(array.indexOf(n) == -1){
return n;
} else {
return getDistinctRandomIntForArray(array, range);
}
}
function generateArrayOfRandomInts(count, range) {
var array = [];
for (i=0; i<count; ++i){
array[i] = getDistinctRandomIntForArray(array, range);
};
return array;
}
I would have preferred to not create a loop that has the possibility to end up with a lot of unnecessary calls (if your count, and range are high and are close to the same number) but this is the best I could come up with.
if (obj === undefined)
{
// Create obj
}
If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.
Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.
I have programmed a module wich is able to hash big files with different algorithms.
pip3 install py_essentials
Use the module like this:
from py_essentials import hashing as hs
hash = hs.fileChecksum("path/to/the/file.txt", "sha256")
Java Beans are not the same thing as EJBs.
The JavaBeans specification in Java 1.0 was Sun's attempt to allow Java objects to be manipulated in an IDE that looked like VB. There were rules laid down for objects that qualified as "Java Beans":
EJBs came later. They combine distributed components and a transactional model, running in a container that manages threads, pooling, life cycle, and provides services. They are a far cry from Java Beans.
DTOs came about in the Java context because people found out that the EJB 1.0 spec was too "chatty" with the database. Rather than make a roundtrip for every data element, people would package them into Java Beans in bulk and ship them around.
POJOs were a reaction against EJBs.
For the best performance and zero garbage, use this:
using System;
using T = MyNamespace.MyFlags;
namespace MyNamespace
{
[Flags]
public enum MyFlags
{
None = 0,
Flag1 = 1,
Flag2 = 2
}
static class MyFlagsEx
{
public static bool Has(this T type, T value)
{
return (type & value) == value;
}
public static bool Is(this T type, T value)
{
return type == value;
}
public static T Add(this T type, T value)
{
return type | value;
}
public static T Remove(this T type, T value)
{
return type & ~value;
}
}
}
Here is a jquery function that returns an object of any class or id on the page
var elementPosition = function(idClass) {
var element = $(idClass);
var offset = element.offset();
return {
'top': offset.top,
'right': offset.left + element.outerWidth(),
'bottom': offset.top + element.outerHeight(),
'left': offset.left,
};
};
console.log(elementPosition('#my-class-or-id'));
I am using
bin(1)[2:].zfill(8)
will print
'00000001'
You need to understand the difference between classes and objects. From the Java tutorial:
An object is a software bundle of related state and behavior
A class is a blueprint or prototype from which objects are created
You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new
keyword.
new Date();
You will need to assign the object to a variable of the same type as the class the object was created from.
Date d = new Date();
Once you have a reference to the object you can interact with it
d.date("01", "12", "14");
The exception to this is static methods that belong to the class and are referenced through it
public class MyDate{
public static date(){ ... }
}
...
MyDate.date();
In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.
This simply means that something in the backend ( DBMS ) decided to stop working due to unavailability of resources etc. It has nothing to do with your code or the number of inserts. You can read more about similar problems here:
This may not answer your question, but you will get an idea of why it might be happening. You could further discuss with your DBA and see if there is something specific in your case.
If you want to compare two Maps then, below code may help you
(new TreeMap<String, Object>(map1).toString().hashCode()) == new TreeMap<String, Object>(map2).toString().hashCode()
1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:
Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:
urn:oasis:names:tc:SAML:1.0: urn:oasis:names:tc:SAML:1.1: urn:oasis:names:tc:SAML:2.0:
Don't add the bcc header.
See this: http://mail.python.org/pipermail/email-sig/2004-September/000151.html
And this: """Notice that the second argument to sendmail(), the recipients, is passed as a list. You can include any number of addresses in the list to have the message delivered to each of them in turn. Since the envelope information is separate from the message headers, you can even BCC someone by including them in the method argument but not in the message header.""" from http://pymotw.com/2/smtplib
toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '[email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
# don't add this, otherwise "to and cc" receivers will know who are the bcc receivers
# + "BCC: %s\r\n" % ",".join(bcc)
+ "Subject: %s\r\n" % message_subject
+ "\r\n"
+ message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('smtp.sunnydale.k12.ca.us')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()
read about the lists() method
$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
This error also happens if you have got the order of your components wrong.
Example: this wrong:
<ComponentA>
<ComponentB>
</ComponentA>
</ComponentB>
correct way:
<ComponentA>
<ComponentB>
</ComponentB>
</ComponentA>
You could also do it this way.
specialRegex = /[^A-Z a-z0-9]/
specialRegex.test('test!') // evaluates to true
Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character
You can't. See the Git FAQ.
Currently the design of the git index (staging area) only permits files to be listed, and nobody competent enough to make the change to allow empty directories has cared enough about this situation to remedy it.
Directories are added automatically when adding files inside them. That is, directories never have to be added to the repository, and are not tracked on their own.
You can say "
git add <dir>
" and it will add files in there.If you really need a directory to exist in checkouts you should create a file in it. .gitignore works well for this purpose; you can leave it empty, or fill in the names of files you expect to show up in the directory.
When you want to create an external_table, all field's name must be written in UPPERCASE.
Done.
I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT name
FROM table1)
Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.
I was also facing that problem, but I resolved it. Make sure that both the programs for client-side and server-side are on different projects in your IDE, in my case NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects.
Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N
for the S/U and U/S contention, as in No Conflict.
As for the HOLDLOCK hint the documentation states:
HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.
...
SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...
and the Transaction Isolation Level topic explains what SERIALIZABLE means:
No other transactions can modify data that has been read by the current transaction until the current transaction completes.
Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.
Therefore the behavior you see is perfectly explained by the product documentation:
SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...
After OP edit:
I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.
The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.
For a single boxplot:
import seaborn as sb
sb.boxplot(data=Array).set_title('Title')
For more boxplot in the same plot:
import seaborn as sb
sb.boxplot(data=ArrayofArray).set_title('Title')
e.g.
import seaborn as sb
myarray=[78.195229, 59.104538, 19.884109, 25.941648, 72.234825, 82.313911]
sb.boxplot(data=myarray).set_title('myTitle')
There is the solution if you need only outline without border. It's not mine. I got if from Bootstrap css file. If you specify outline: 1px auto certain_color
, you'll get thin outer line around div of certain color. In this case the specified width has no matter, even if you specify 10 px width, anyway it will be thin line. The key word in mentioned rule is "auto".
If you need outline with rounded corners and certain width, you may add css rule on border with needed width and same color. It makes outline thicker.
Just add an app setting bundle and implement a toggle to reset the keychain on app restart or something based on the value selected through settings (available through userDefaults)
None?
I mean, other than removing it from the layout entirely with display: none
, I'm pretty sure that's it.
Are you facing a particular situation in which position: absolute
is not a viable solution?
import itertools
foos=[1.0, 2.0, 3.0, 4.0, 5.0]
bars=[1, 2, 3]
print zip(foos, itertools.cycle([bars]))
It is convenient to set the option in the CMakeLists.txt
file as:
set(CMAKE_VERBOSE_MAKEFILE ON)
What worked for me (with JDK7) was the following:
Alternatively, if you don't want to write to your JDK folder, you could also attach src.zip to (at least) rt.jar in eclipse in the Window | Preferences menu in Java | Installed JREs.
If you're not comfortable with downloading the sources from GrepCode, you could also get them from openJDK directly. This requires requires a bit more effort, though. Replace step one above by the following steps:
A third alternative to acquire src.zip is to download the unofficial OpenJDK builds from here. The src.zip is contained within the downloaded zip.
This might be old. But, it just occurred in angular, the content type for request and response were different in my code. So, check headers for ,
let headers = new Headers({
'Content-Type': 'application/json',
**Accept**: 'application/json'
});
in React axios
axios({
method:'get',
url:'http:// ',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
responseType:'json'
})
jQuery Ajax:
$.ajax({
url: this.props.url,
dataType: 'json',
**headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},**
cache: false,
success: function (data) {
this.setState({ data: data });
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
Found solution on the error page itself. Just needed to add requestValidationMode="2.0" in web.config
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime requestValidationMode="2.0" />
</system.web>
MSDN information: HttpRuntimeSection.RequestValidationMode Property
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
The ant solution above is easiest to configure, but I have had luck using the maven-upload-plugin from Atlassian. I was unable to find good documentation, here is how I use it:
<build>
<plugin>
<groupId>com.atlassian.maven.plugins</groupId>
<artifactId>maven-upload-plugin</artifactId>
<version>1.1</version>
<configuration>
<resourceSrc>
${project.build.directory}/${project.build.finalName}.${project.packaging}
</resourceSrc>
<resourceDest>${jboss.deployDir}</resourceDest>
<serverId>${jboss.host}</serverId>
<url>${jboss.deployUrl}</url>
</configuration>
</plugin>
</build>
The variables like "${jboss.host}" referenced above are defined in my ~/.m2/settings.xml and are activated using maven profiles. This solution is not constrained to JBoss, this is just what I named my variables. I have a profile for dev, test, and live. So to upload my ear to a jboss instance in test environment I would execute:
mvn upload:upload -P test
Here is a snipet from settings.xml:
<server>
<id>localhost</id>
<username>username</username>
<password>{Pz+6YRsDJ8dUJD7XE8=} an encrypted password. Supported since maven 2.1</password>
</server>
...
<profiles>
<profile>
<id>dev</id>
<properties>
<jboss.host>localhost</jboss.host>
<jboss.deployDir>/opt/jboss/server/default/deploy/</jboss.deployDir>
<jboss.deployUrl>scp://root@localhost</jboss.deployUrl>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<jboss.host>testserver</jboss.host>
...
Notes: The Atlassian maven repo that has this plugin is here: https://maven.atlassian.com/public/
I recommend downloading the sources and looking at the documentation inside to see all the features the plugin provides.
`
I personally think all the answers here are mis-understanding the question. The answer to this lies in the difference of how spring-boot builds the .jar. Everyone knows that Spring Boot sets up a manifest like this, which varies from everyones asssumption that this is a standard .jar launch, which it may or may not be :
Start-Class: com.myco.eventlogging.MyService
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Version: 1.4.0.RELEASE
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_131
Main-Class: org.springframework.boot.loader.JarLauncher
Perhaps it needs to executed with org.springframework.boot.loader.JarLauncher
on the classpath?
Have a look at Determine and count unique values of an array.
Or, to count the number of occurrences of 5
, simply do
sum(your_matrix == 5)
What worked for me was adding a div around the content. Originally i had this. Css applied to the td had no effect.
<td>
@Html.DisplayFor(modelItem => item.Message)
</td>
Then I wrapped the content in a div and the css worked as expected
<td>
<div class="largeContent">
@Html.DisplayFor(modelItem => item.Message)
</div>
</td>
Use a terminal-handling library like the curses module:
The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.
Try This!
I have added 5 circles you can add more. And instead of RaisedButton use InkResponse.
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(home: new ExampleWidget()));
}
class ExampleWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
Widget bigCircle = new Container(
width: 300.0,
height: 300.0,
decoration: new BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
);
return new Material(
color: Colors.black,
child: new Center(
child: new Stack(
children: <Widget>[
bigCircle,
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.favorite_border),
top: 10.0,
left: 130.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.timer),
top: 120.0,
left: 10.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.place),
top: 120.0,
right: 10.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.local_pizza),
top: 240.0,
left: 130.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.satellite),
top: 120.0,
left: 130.0,
),
],
),
),
);
}
}
class CircleButton extends StatelessWidget {
final GestureTapCallback onTap;
final IconData iconData;
const CircleButton({Key key, this.onTap, this.iconData}) : super(key: key);
@override
Widget build(BuildContext context) {
double size = 50.0;
return new InkResponse(
onTap: onTap,
child: new Container(
width: size,
height: size,
decoration: new BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: new Icon(
iconData,
color: Colors.black,
),
),
);
}
}
Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial
to utilize the two-parameter operator.mul
with a fixed multiple
>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
The correct properties are
server.servlet.path
to configure the path of the DispatcherServlet
and
server.servlet.context-path
to configure the path of the applications context below that.
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
The difference is in the second argument. The second argument to substring
is the index to stop at (but not include), but the second argument to substr
is the maximum length to return.
Links?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
I am using Visual Studio 2013 & SQL Server 2014. I got the below error Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 not found by visual studio. I have tried all the things like installing
ENU\x64\SharedManagementObjects.msi for X64 OS or
ENU\x86\SharedManagementObjects.msi for X86 OS
ENU\x64\SQLSysClrTypes.msi
Reinstalling Sql Server 2014
What actually solved my problem is to repair the visual studio 2013(or any other version you are using) now the problem is removed . What i think it is problem of Visual Studio not Sql Server as i was able to access and use the Sql Server tool.
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
seems you need to link with the obj file that implements tolayer5()
Update: your function declaration doesn't match the implementation:
void tolayer5(int AorB, struct msg msgReceived)
void tolayer5(int, char data[])
So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().
float
and double
don't store decimal places. They store binary places: float
is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).
Converting from double
to float
will give you the closest possible float
, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.
#include <stdio.h>
int main(void) {
double orig = 12345.67;
float f = (float) orig;
printf("%.17g\n", f); // prints 12345.669921875
return 0;
}
To get a double
approximation to the nice decimal value you intended, you can write something like:
double round_to_decimal(float f) {
char buf[42];
sprintf(buf, "%.7g", f); // round to 7 decimal digits
return atof(buf);
}
This worked for me:
location / {
alias /path/to/my/indexfile/;
try_files $uri /index.html;
}
This allowed me to create a catch-all URL for a javascript single-page app. All static files like css, fonts, and javascript built by npm run build
will be found if they are in the same directory as index.html
.
If the static files were in another directory, for some reason, you'd also need something like:
# Static pages generated by "npm run build"
location ~ ^/css/|^/fonts/|^/semantic/|^/static/ {
alias /path/to/my/staticfiles/;
}
Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean.
RestTemplateBuilder offers proper way to configure and instantiate the rest template bean, for example for basic auth or interceptors.
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.basicAuthorization("user", "name") // Optional Basic auth example
.interceptors(new MyCustomInterceptor()) // Optional Custom interceptors, etc..
.build();
}
Do you have Bitnami installed? If so it is most likely one of those installations check by opening command prompt as admin or terminal in linux, enter this...
netstat -b
This will give an application name to those processes and ports in use. Look for :80 or :443
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
Make sure that you don't declare it as a integer, float, string or boolean before. http://php.net/manual/en/function.is-scalar.php
And if you're using Xamarin (monotouch) framework, simply call
SystemSound.Vibrate.PlayAlertSound()
You do not sort entries in the Dictionary. Dictionary class in .NET is implemented as a hashtable - this data structure is not sortable by definition.
If you need to be able to iterate over your collection (by key) - you need to use SortedDictionary, which is implemented as a Binary Search Tree.
In your case, however the source structure is irrelevant, because it is sorted by a different field. You would still need to sort it by frequency and put it in a new collection sorted by the relevant field (frequency). So in this collection the frequencies are keys and words are values. Since many words can have the same frequency (and you are going to use it as a key) you cannot use neither Dictionary nor SortedDictionary (they require unique keys). This leaves you with a SortedList.
I don't understand why you insist on maintaining a link to the original item in your main/first dictionary.
If the objects in your collection had a more complex structure (more fields) and you needed to be able to efficiently access/sort them using several different fields as keys - You would probably need a custom data structure that would consist of the main storage that supports O(1) insertion and removal (LinkedList) and several indexing structures - Dictionaries/SortedDictionaries/SortedLists. These indexes would use one of the fields from your complex class as a key and a pointer/reference to the LinkedListNode in the LinkedList as a value.
You would need to coordinate insertions and removals to keep your indexes in sync with the main collection (LinkedList) and removals would be pretty expensive I'd think. This is similar to how database indexes work - they are fantastic for lookups but they become a burden when you need to perform many insetions and deletions.
All of the above is only justified if you are going to do some look-up heavy processing. If you only need to output them once sorted by frequency then you could just produce a list of (anonymous) tuples:
var dict = new SortedDictionary<string, int>();
// ToDo: populate dict
var output = dict.OrderBy(e => e.Value).Select(e => new {frequency = e.Value, word = e.Key}).ToList();
foreach (var entry in output)
{
Console.WriteLine("frequency:{0}, word: {1}",entry.frequency,entry.word);
}
you can get the data from the XML by using "simplexml_load_file" Function. Please refer this link
http://php.net/manual/en/function.simplexml-load-file.php
$url = "http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false";
$xml = simplexml_load_file($url);
print_r($xml);
As far as I can tell there is no upper limit in 2008.
In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg
variable with
Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.
the code below fails with
REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.
However it appears these limitations have quietly been lifted. On 2008
DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681);
SET @y = REPLICATE(@y,92681);
SELECT LEN(@y)
Returns
8589767761
I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory
Running
select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid
Returned
internal_objects_alloc_page_co
------------------------------
2144456
so I presume this all just gets stored in LOB
pages in tempdb
with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681);
statement. The initial variable assignment to @y
and the LEN
calculation did not increase this.
The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE
method isn't supported for varchar(max) variables.
Addition
I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max)
and nvarchar(max) + varchar(max)
. Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
again. The script for that is below (may take a long time to run).
DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647);
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1) /*4294967294, 4294967292*/
DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823);
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2) /*2147483646, 4294967292*/
DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3) /*6442450940, 12884901880*/
/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test
Pragma
is the HTTP/1.0 implementation and cache-control
is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.
Component code:
import { Component } from "@angular/core";
@Component({
templateUrl:"home.html"
})
export class HomePage {
public items: Array<string>;
constructor() {
this.items = ["item1", "item2", "item3"]
}
public open(event, item) {
alert('Open ' + item);
}
}
View:
<ion-header>
<ion-navbar primary>
<ion-title>
<span>My App</span>
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let item of items" (click)="open($event, item)">
{{ item }}
</ion-item>
</ion-list>
</ion-content>
As you can see in the code, I'm declaring the click handler like this (click)="open($event, item)"
and sending both the event and the item (declared in the *ngFor
) to the open()
method (declared in the component code).
If you just want to show the item and you don't need to get info from the event, you can just do (click)="open(item)"
and modify the open
method like this public open(item) { ... }
Try this
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray"/>
What does res.render do and what does the html file look like?
res.render()
function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.
Answering Edit 2 part.
// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');
// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');
// here you render `orders` template
response.render("orders", {orders: orders_json});
So, the template path is views/
(first part) + orders
(second part) + .ejs
(third part) === views/orders.ejs
Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.
I'd use a timedelta
object.
from datetime import datetime, timedelta
...
period = timedelta(minutes=1)
next_time = datetime.now() + period
minutes = 0
while run == 'start':
if next_time <= datetime.now():
minutes += 1
next_time += period
We just ran into this same issue. Our Cpanel has expanded from PHP only to PHP and .NET and defaulted to .NET.
Log in to you Cpanel and make sure you don’t have the same issue.
<style type="text/css">
p {margin-bottom: -1em; margin-top: 0em;}
</style>
This completely worked for me. Paragraphs were right below each other. When I used 0em for both the margins, there was still some space left in between the lines. I went for Developer tools in my browser, tried with -1em and it worked.
Python dictionaries don't support duplicate keys. One way around is to store lists or sets inside the dictionary.
One easy way to achieve this is by using defaultdict
:
from collections import defaultdict
data_dict = defaultdict(list)
All you have to do is replace
data_dict[regNumber] = details
with
data_dict[regNumber].append(details)
and you'll get a dictionary of lists.
In practical terms, the limit is usually determined by stack space. If each thread gets a 1MB stack (I can't remember if that is the default on Linux), then you a 32-bit system will run out of address space after 3000 threads (assuming that the last gb is reserved to the kernel).
However, you'll most likely experience terrible performance if you use more than a few dozen threads. Sooner or later, you get too much context-switching overhead, too much overhead in the scheduler, and so on. (Creating a large number of threads does little more than eat a lot of memory. But a lot of threads with actual work to do is going to slow you down as they're fighting for the available CPU time)
What are you doing where this limit is even relevant?
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
Place the following HTML redirect code between the and tags of your HTML code.
<meta HTTP-EQUIV="REFRESH" content="3; url=http://www.yourdomain.com/index.html">
The above HTML redirect code will redirect your visitors to another web page instantly. The content="3; may be changed to the number of seconds you want the browser to wait before redirecting. 4, 5, 8, 10 or 15 seconds, etc.
const mergedMaps = (...maps) => {
const dataMap = new Map([])
for (const map of maps) {
for (const [key, value] of map) {
dataMap.set(key, value)
}
}
return dataMap
}
const map = mergedMaps(new Map([[1, false]]), new Map([['foo', 'bar']]), new Map([['lat', 1241.173512]]))
Array.from(map.keys()) // [1, 'foo', 'lat']
Your web server isn't running! You need to find the XAMPP control panel and start the web server up.
Of course, you might find other problems after that, but this is the first step.
the position:fixed; property should do the work, I used it on my Website and it worked fine. http://www.w3schools.com/css/css_positioning.asp
Since Java 13 you have formatted
1 method on String, which was added along with text blocks as a preview feature 2.
You can use it instead of String.format()
Assertions.assertEquals(
"%s %d %.3f".formatted("foo", 123, 7.89),
"foo 123 7.890"
);