printf already crops the trailing newline for you:
$ printf '%s' $(wc -l < log.txt)
Detail:
%s
string place holder. %s\n
), it won't.Please change your javascript function as like below....
$(function () {
$("#projectKey").change(function () {
alert($('option:selected').text());
});
});
You do not need to use $(this)
in alert.
What you can do is
RelationActiveEnum ae = Enum.valueOf(RelationActiveEnum.class,
RelationActiveEnum.ACTIVE.name();
or
RelationActiveEnum ae = RelationActiveEnum.valueOf(
RelationActiveEnum.ACTIVE.name();
or
// not recommended as the ordinal might not match the value
RelationActiveEnum ae = RelationActiveEnum.values()[
RelationActiveEnum.ACTIVE.value];
By if you want to lookup by a field of an enum you need to construct a collection such as a List, an array or a Map.
public enum RelationActiveEnum {
Invited(0),
Active(1),
Suspended(2);
private final int code;
private RelationActiveEnum(final int code) {
this.code = code;
}
private static final Map<Integer, RelationActiveEnum> BY_CODE_MAP = new LinkedHashMap<>();
static {
for (RelationActiveEnum rae : RelationActiveEnum.values()) {
BY_CODE_MAP.put(rae.code, rae);
}
}
public static RelationActiveEnum forCode(int code) {
return BY_CODE_MAP.get(code);
}
}
allows you to write
String name = RelationActiveEnum.forCode(RelationActiveEnum.ACTIVE.code).name();
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
Rather than use "d", why not "p". I am not sure if the "p *" will work. I didn't try that. You can; however use the following script"
#!/bin/bash
#
MAIL_INDEX=$(printf 'h a\nq\n' | mail | egrep -o '[0-9]* unread' | awk '{print $1}')
markAllRead=
for (( i=1; i<=$MAIL_INDEX; i++ ))
do
markAllRead=$markAllRead"p $i\n"
done
markAllRead=$markAllRead"q\n"
printf "$markAllRead" | mail
For newbies who just can't get it to work who need their hands held.
Make a folder /home/el/foo and make a file main.py
under /home/el/foo Put this code in there:
from hellokitty import *
spam.spamfunc()
ham.hamfunc()
Make a directory /home/el/foo/hellokitty
Make a file __init__.py
under /home/el/foo/hellokitty
and put this code in there:
__all__ = ["spam", "ham"]
Make two python files: spam.py
and ham.py
under /home/el/foo/hellokitty
Define a function inside spam.py:
def spamfunc():
print("Spammity spam")
Define a function inside ham.py:
def hamfunc():
print("Upgrade from baloney")
Run it:
el@apollo:/home/el/foo$ python main.py
spammity spam
Upgrade from baloney
Try to run Your XAMPP Control Panel as Run as administrator
, then install Apache and MySQL.
When XAMPP opens, ensure that Apache and MySQL services are stopped.
Now just check/tick on Apache and Mysql service module.
Now Apache and MySQL will be added to window services. You can set these services to start when Windows boots.
you can use pandas.set_option(), for column, you can specify any of these options
pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", 100)
pd.set_option("display.max_colwidth", 200)
For full print column, you can use like this
import pandas as pd
pd.set_option('display.max_colwidth', -1)
print(words.head())
$(document).ready(function(){
// alert("test");
$("#name").click(function(){
var content = document.getElementById("ghufran").innerHTML ;
alert(content);
});
//var content = $('#one').text();
})
there u go buddy this code actually works
Here is an example using the DOM cookie API (https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie), so we can see for ourselves the behavior.
If we execute the following JavaScript:
document.cookie = "key=value"
It appears to be the same as executing:
document.cookie = "key=value;domain=mydomain.com"
The cookie key becomes available (only) on the domain mydomain.com.
Now, if you execute the following JavaScript on mydomain.com:
document.cookie = "key=value;domain=.mydomain.com"
The cookie key becomes available to mydomain.com as well as subdomain.mydomain.com.
Finally, if you were to try and execute the following on subdomain.mydomain.com:
document.cookie = "key=value;domain=.mydomain.com"
Does the cookie key become available to subdomain.mydomain.com? I was a bit surprised that this is allowed; I had assumed it would be a security violation for a subdomain to be able to set a cookie on a parent domain.
Now Kibana 4 allows you to use aggregations. Apart from building a panel like the one that was explained in this answer for Kibana 3, now we can see the number of unique IPs in different periods, that was (IMO) what the OP wanted at the first place.
To build a dashboard like this you should go to Visualize -> Select your Index -> Select a Vertical Bar chart and then in the visualize panel:
Just take into account that the unique counts are approximate. For more information check also this answer.
Add a method to the enum like:
public String getString() {
return this.name();
}
For example
public enum MyEnum {
VALUE_1,
VALUE_2;
public String getString() {
return this.name();
}
}
Then you can use:
<c:if test="${myObject.myEnumProperty.string eq 'VALUE_2'}">...</c:if>
Without jQuery:
var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;
Or:
function hasClass(e,c){
return e&&(e instanceof HTMLElement)&&!!((' '+e.className+' ').indexOf(' '+c+' ')+1);
}
/*example of usage*/
var has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');
This is WAY faster than jQuery!
You may use ng-include to avoid using nested ng-views.
http://docs.angularjs.org/api/ng/directive/ngInclude
http://plnkr.co/edit/ngdoc:example-example39@snapshot?p=preview
My index page I use ng-view. Then on my sub pages which I need to have nested frames. I use ng-include. The demo shows a dropdown. I replaced mine with a link ng-click. In the function I would put $scope.template = $scope.templates[0]; or $scope.template = $scope.templates[1];
$scope.clickToSomePage= function(){
$scope.template = $scope.templates[0];
};
git config credential.helper store
Note: While this is convenient, Git will store your credentials in clear text in a local file (.git-credentials) under your project directory (see below for the "home" directory). If you don't like this, delete this file and switch to using the cache option.
If you want Git to resume to asking you for credentials every time it needs to connect to the remote repository, you can run this command:
git config --unset credential.helper
To store the passwords in .git-credentials in your %HOME% directory as opposed to the project directory: use the --global flag
git config --global credential.helper store
Just so I don't lose my answer that works:
new {var_data[counter] =new [] {
new{ "S NO": "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
}
};
This works in Chrome 26, Internet Explorer 9 and Safari 5.1.7 (without the use of a helper page, ala Nick's answer):
<script type="text/javascript">
window.open('javascript:window.open("", "_self", "");window.close();', '_self');
</script>
The nested window.open
is to make IE not display the Do you want to close this window prompt.
Unfortunately it is impossible to get Firefox to close the window.
How to reproduce the bug:
Settings -> Developer Options -> Don't keep Activities
.AsyncTask
is executing and the ProgressDialog
is showing.The Android OS will destroy an activity as soon as it is hidden. When onPostExecute
is called the Activity
will be in "finishing" state and the ProgressDialog
will be not attached to Activity
.
How to fix it:
onPostExecute
method. ProgressDialog
in onDestroy
method. Otherwise, android.view.WindowLeaked
exception will be thrown. This exception usually comes from dialogs that are still active when the activity is finishing.Try this fixed code:
public class YourActivity extends Activity {
private void showProgressDialog() {
if (pDialog == null) {
pDialog = new ProgressDialog(StartActivity.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
}
pDialog.show();
}
private void dismissProgressDialog() {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
@Override
protected void onDestroy() {
dismissProgressDialog();
super.onDestroy();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
@Override
protected void onPreExecute() {
showProgressDialog();
}
//getting All products from url
protected String doInBackground(String... args) {
doMoreStuff("internet");
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
return;
}
dismissProgressDialog();
something(note);
}
}
}
In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime()
gives you the mentioned milliseconds).
In your solution:
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.
Another possible solution would be to utilise the static fields of the Calendar
class:
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.
Here THIS context is getting changed. Use arrow function to keep context of React class.
VK.init(() => {
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},(data) => {
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
});
}, function(){
console.info("API initialisation failed");
}, '5.34');
I'm adding this solution for people who make the same mistake as I did.
In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.
Problem occurs when you import 'something' when your python file name is 'something.py'.
Using the CLI, to create a functioning NUnit project is really easy. The template does everything for you.
dotnet new -i NUnit3.DotNetNew.Template
dotnet new nunit
On .NET Core, this is definitely my preferred way to go.
public class X { static {
System.out.println("Main not required to print this");
System.exit(0);
}}
Run from the cmdline with java X
.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
If you don't want to use local storage then you could attach the y position of the page to the url and grab it with js on load and set the page offset to the get param you passed in, i.e.:
//code to refresh the page
var page_y = $( document ).scrollTop();
window.location.href = window.location.href + '?page_y=' + page_y;
//code to handle setting page offset on load
$(function() {
if ( window.location.href.indexOf( 'page_y' ) != -1 ) {
//gets the number from end of url
var match = window.location.href.split('?')[1].match( /\d+$/ );
var page_y = match[0];
//sets the page offset
$( 'html, body' ).scrollTop( page_y );
}
});
Need to kill a Node.js server, and you don't have any other Node processes running, you can tell your machine to kill all processes named node.exe
. That would look like this:
taskkill /im node.exe
And if the processes still persist, you can force the processes to terminate by adding the /f
flag:
taskkill /f /im node.exe
If you need more fine-grained control and need to only kill a server that is running on a specific port, you can use netstat
to find the process ID, then send a kill signal to it. So in your case, where the port is 8080
, you could run the following:
C:\>netstat -ano | find "LISTENING" | find "8080"
The fifth column of the output is the process ID:
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 14828
TCP [::]:8080 [::]:0 LISTENING 14828
You could then kill the process with taskkill /pid 14828
. If the process refuses to exit, then just add the /f
(force) parameter to the command.
The process is almost identical. You could either kill all Node processes running on the machine (use -$SIGNAL
if SIGKILL
is insufficient):
killall node
Or also using netstat
, you can find the PID of a process listening on a port:
$ netstat -nlp | grep :8080
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 1073/node
The process ID in this case is the number before the process name in the sixth column, which you could then pass to the kill
command:
$ kill 1073
If the process refuses to exit, then just use the -9
flag, which is a SIGTERM
and cannot be ignored:
$ kill -9 1073
Use stored procedures.
And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".
For curl
, how about using the -d
switch? Like: curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"
?
According to the documentation:
$validator = Validator::make($request->all(), [
'file' => 'max:500000',
]);
The value is in kilobytes. I.e. max:10240
= max 10 MB.
I had been having issues where I was using
overflow: none;
But I knew CSS didn't really like it and it didn’t work 100% for how I wanted it to.
However, this is a perfect solution as none of my content is supposed to be larger than intended and this has fixed the issue I had.
overflow: auto;
In addition to the other answers (particularly by Lekakis), some string replacements can also be used in the option --log-file=
as elaborated in the Valgrind's user manual.
Four replacements were available at the time of writing:
%p
: Prints the current process ID
valgrind --log-file="myFile-%p.dat" <application-name>
%n
: Prints file sequence number unique for the current process
valgrind --log-file="myFile-%p-%n.dat" <application-name>
%q{ENV}
: Prints contents of the environment variable ENV
valgrind --log-file="myFile-%q{HOME}.dat" <application-name>
%%
: Prints %
valgrind --log-file="myFile-%%.dat" <application-name>
I use pendulum:
import pendulum
d = pendulum.now("UTC").to_iso8601_string()
print(d)
>>> 2019-10-30T00:11:21.818265Z
There is a very easy free and open source solution at http://jordiburgos.com/post/2014/excellentexport-javascript-export-to-excel-csv.html
First download the javascript file and sample files from https://github.com/jmaister/excellentexport/releases/tag/v1.4
The html page looks like below.
Make sure the the javascript file is in the same folder or change the path of the script in the html file accordingly.
<html>
<head>
<title>Export to excel test</title>
<script src="excellentexport.js"></script>
<style>
table, tr, td {
border: 1px black solid;
}
</style>
</head>
<body>
<h1>ExcellentExport.js</h1>
Check on <a href="http://jordiburgos.com">jordiburgos.com</a> and <a href="https://github.com/jmaister/excellentexport">GitHub</a>.
<h3>Test page</h3>
<br/>
<a download="somedata.xls" href="#" onclick="return ExcellentExport.excel(this, 'datatable', 'Sheet Name Here');">Export to Excel</a>
<br/>
<a download="somedata.csv" href="#" onclick="return ExcellentExport.csv(this, 'datatable');">Export to CSV</a>
<br/>
<table id="datatable">
<tr>
<th>Column 1</th>
<th>Column "cool" 2</th>
<th>Column 3</th>
</tr>
<tr>
<td>100,111</td>
<td>200</td>
<td>300</td>
</tr>
<tr>
<td>400</td>
<td>500</td>
<td>600</td>
</tr>
<tr>
<td>Text</td>
<td>More text</td>
<td>Text with
new line</td>
</tr>
</table>
</body>
It is very easy to use this as I have tried most of the other methods.
You need jackson dependency for this serialization and deserialization.
Add this dependency:
Gradle:
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4")
Maven:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
After that, You need to tell Jackson ObjectMapper to use JavaTimeModule. To do that, Autowire ObjectMapper in the main class and register JavaTimeModule to it.
import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@SpringBootApplication
public class MockEmployeeApplication {
@Autowired
private ObjectMapper objectMapper;
public static void main(String[] args) {
SpringApplication.run(MockEmployeeApplication.class, args);
}
@PostConstruct
public void setUp() {
objectMapper.registerModule(new JavaTimeModule());
}
}
After that, Your LocalDate and LocalDateTime should be serialized and deserialized correctly.
I spent around 6 hours on the same issue today. Inserts go at a 'regular' speed (less than 3sec per 100K) up until to 5MI (out of total 30MI) rows and then the performance sinks drastically (all the way down to 1min per 100K).
I will not list all of the things that did not work and cut straight to the meat.
I dropped a primary key on the target table (which was a GUID) and my 30MI or rows happily flowed to their destination at a constant speed of less than 3sec per 100K.
I had the same problem. Turns out the project I was referencing did not get build. When I went to the build configuration manager in visual studio and enabled the reference project , the issue got resolved.
if you are using PyCharm, when you open or clone the project into the PyCharm it shows an alert and ask you for installing all necessary packages.
with open(fname, 'rb') as fh:
first = next(fh).decode()
fh.seek(-1024, 2)
last = fh.readlines()[-1].decode()
The variable value here is 1024: it represents the average string length. I choose 1024 only for example. If you have an estimate of average line length you could just use that value times 2.
Since you have no idea whatsoever about the possible upper bound for the line length, the obvious solution would be to loop over the file:
for line in fh:
pass
last = line
You don't need to bother with the binary flag you could just use open(fname)
.
ETA: Since you have many files to work on, you could create a sample of couple of dozens of files using random.sample
and run this code on them to determine length of last line. With an a priori large value of the position shift (let say 1 MB). This will help you to estimate the value for the full run.
Seems there is another format now
where: {
LastName: "Doe",
$or: [
{
FirstName:
{
$eq: "John"
}
},
{
FirstName:
{
$eq: "Jane"
}
},
{
Age:
{
$gt: 18
}
}
]
}
Will generate
WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)
See the doc: http://docs.sequelizejs.com/en/latest/docs/querying/#where
Your code is in the default package, i.e. you have source all files in src/main/java with no custom package. I strongly suggest u to create package n then place your source file in it.
Ex-
src->
main->
java->
com.myfirst.example
Example.java
com.myfirst.example.controller
PersonController.java
com.myfirst.example.repository
PersonRepository.java
com.myfirst.example.model
Person.java
I hope it will resolve your problem.
Checkout this screen cast about finding memory leaks with JProfiler. It's visual explanation of @Dima Malenko Answer.
Note: Though JProfiler is not freeware, But Trial version can deal with current situation.
If you want the result plus the number of rows returned do something like this. Using PHP.
$query = "SELECT * FROM Employee";
$result = mysql_query($query);
echo "There are ".mysql_num_rows($result)." Employee(s).";
If you work with generics, use List instead of ArrayList. The List has exactly the GetEnumerator method you need.
List<MyObject> myList = new List<MyObject>();
Can't test it right now, but:
select * from tablename where date >= dateadd(day, datediff(day, 1, getdate()), 0) and date < dateadd(day, datediff(day, 0, getdate()), 0)
bbox_to_anchor
)A legend is positioned inside the bounding box of the axes using the loc
argument to plt.legend
.
E.g. loc="upper right"
places the legend in the upper right corner of the bounding box, which by default extents from (0,0)
to (1,1)
in axes coordinates (or in bounding box notation (x0,y0, width, height)=(0,0,1,1)
).
To place the legend outside of the axes bounding box, one may specify a tuple (x0,y0)
of axes coordinates of the lower left corner of the legend.
plt.legend(loc=(1.04,0))
A more versatile approach is to manually specify the bounding box into which the legend should be placed, using the bbox_to_anchor
argument. One can restrict oneself to supply only the (x0, y0)
part of the bbox. This creates a zero span box, out of which the legend will expand in the direction given by the loc
argument. E.g.
plt.legend(bbox_to_anchor=(1.04,1), loc="upper left")
places the legend outside the axes, such that the upper left corner of the legend is at position (1.04,1)
in axes coordinates.
Further examples are given below, where additionally the interplay between different arguments like mode
and ncols
are shown.
l1 = plt.legend(bbox_to_anchor=(1.04,1), borderaxespad=0)
l2 = plt.legend(bbox_to_anchor=(1.04,0), loc="lower left", borderaxespad=0)
l3 = plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
l4 = plt.legend(bbox_to_anchor=(0,1.02,1,0.2), loc="lower left",
mode="expand", borderaxespad=0, ncol=3)
l5 = plt.legend(bbox_to_anchor=(1,0), loc="lower right",
bbox_transform=fig.transFigure, ncol=3)
l6 = plt.legend(bbox_to_anchor=(0.4,0.8), loc="upper right")
Details about how to interpret the 4-tuple argument to bbox_to_anchor
, as in l4
, can be found in this question. The mode="expand"
expands the legend horizontally inside the bounding box given by the 4-tuple. For a vertically expanded legend, see this question.
Sometimes it may be useful to specify the bounding box in figure coordinates instead of axes coordinates. This is shown in the example l5
from above, where the bbox_transform
argument is used to put the legend in the lower left corner of the figure.
Having placed the legend outside the axes often leads to the undesired situation that it is completely or partially outside the figure canvas.
Solutions to this problem are:
Adjust the subplot parameters
One can adjust the subplot parameters such, that the axes take less space inside the figure (and thereby leave more space to the legend) by using plt.subplots_adjust
. E.g.
plt.subplots_adjust(right=0.7)
leaves 30% space on the right-hand side of the figure, where one could place the legend.
Tight layout
Using plt.tight_layout
Allows to automatically adjust the subplot parameters such that the elements in the figure sit tight against the figure edges. Unfortunately, the legend is not taken into account in this automatism, but we can supply a rectangle box that the whole subplots area (including labels) will fit into.
plt.tight_layout(rect=[0,0,0.75,1])
Saving the figure with bbox_inches = "tight"
The argument bbox_inches = "tight"
to plt.savefig
can be used to save the figure such that all artist on the canvas (including the legend) are fit into the saved area. If needed, the figure size is automatically adjusted.
plt.savefig("output.png", bbox_inches="tight")
automatically adjusting the subplot params
A way to automatically adjust the subplot position such that the legend fits inside the canvas without changing the figure size can be found in this answer: Creating figure with exact size and no padding (and legend outside the axes)
Comparison between the cases discussed above:
A figure legend
One may use a legend to the figure instead of the axes, matplotlib.figure.Figure.legend
. This has become especially useful for matplotlib version >=2.1, where no special arguments are needed
fig.legend(loc=7)
to create a legend for all artists in the different axes of the figure. The legend is placed using the loc
argument, similar to how it is placed inside an axes, but in reference to the whole figure - hence it will be outside the axes somewhat automatically. What remains is to adjust the subplots such that there is no overlap between the legend and the axes. Here the point "Adjust the subplot parameters" from above will be helpful. An example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,2*np.pi)
colors=["#7aa0c4","#ca82e1" ,"#8bcd50","#e18882"]
fig, axes = plt.subplots(ncols=2)
for i in range(4):
axes[i//2].plot(x,np.sin(x+i), color=colors[i],label="y=sin(x+{})".format(i))
fig.legend(loc=7)
fig.tight_layout()
fig.subplots_adjust(right=0.75)
plt.show()
Legend inside dedicated subplot axes
An alternative to using bbox_to_anchor
would be to place the legend in its dedicated subplot axes (lax
).
Since the legend subplot should be smaller than the plot, we may use gridspec_kw={"width_ratios":[4,1]}
at axes creation.
We can hide the axes lax.axis("off")
but still put a legend in. The legend handles and labels need to obtained from the real plot via h,l = ax.get_legend_handles_labels()
, and can then be supplied to the legend in the lax
subplot, lax.legend(h,l)
. A complete example is below.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6,2
fig, (ax,lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[4,1]})
ax.plot(x,y, label="y=sin(x)")
....
h,l = ax.get_legend_handles_labels()
lax.legend(h,l, borderaxespad=0)
lax.axis("off")
plt.tight_layout()
plt.show()
This produces a plot, which is visually pretty similar to the plot from above:
We could also use the first axes to place the legend, but use the bbox_transform
of the legend axes,
ax.legend(bbox_to_anchor=(0,0,1,1), bbox_transform=lax.transAxes)
lax.axis("off")
In this approach, we do not need to obtain the legend handles externally, but we need to specify the bbox_to_anchor
argument.
loc
argument can take numbers instead of strings, which make calls shorter, however, they are not very intuitively mapped to each other. Here is the mapping for reference:If you need different column width, do this:
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="9">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</td>
</tr>
When in doubt, follow MVC conventions.
Create a viewModel if you haven't already that contains a property for JobID
public class Model
{
public string JobId {get; set;}
public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
//...any other properties you may need
}
Strongly type your view
@model Fully.Qualified.Path.To.Model
Add a hidden field for JobId to the form
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{
//...
@Html.HiddenFor(m => m.JobId)
}
And accept the model as the parameter in your controller action:
[HttpPost]
public FileStreamResult myMethod(Model model)
{
sting str = model.JobId;
}
There are 5 cases for using the underscore in Python.
For storing the value of last expression in interpreter.
For ignoring the specific values. (so-called “I don’t care”)
To give special meanings and functions to name of variables or functions.
To use as ‘internationalization (i18n)’ or ‘localization (l10n)’ functions.
To separate the digits of number literal value.
Here is a nice article with examples by mingrammer.
My suspicion is the problem lies in your route definition.
You defined the route as a GET
request but the form is probably sending a POST
request. Change your route definition to match the form's request method.
Route::post('/validate', [MemberController::class, 'validateCredentials']);
It's generally better practice to use named routes (helps to scale if the controller method/class changes).
Route::post('/validate', [MemberController::class, 'validateCredentials'])
->name('member.validateCredentials');
In the view, use the validation route as the form's action.
<form action="{{ route('member.validateCredentials') }}" method="POST">
@csrf
...
</form>
Just use the size attribute:
<select name="sometext" size="5">
<option>text1</option>
<option>text2</option>
<option>text3</option>
<option>text4</option>
<option>text5</option>
</select>
To clarify, adding the size attribute did not remove the multiple selection.
The single selection works because you removed the multiple="multiple" attribute.
Adding the size="5" attribute is still a good idea, it means that at least 5 lines must be displayed. See the full reference here
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
Sometimes you actually want to return a DataTable
than a DataView
. So a DataView
was not good in my case and I guess few others would want that too. Here is what I used to do
myDataTable.select("myquery").CopyToDataTable()
This will filter myDataTable
which is a DataTable and return a new DataTable
Hope someone will find that is useful
$("#date").datepicker.regional[""].dateFormat = 'dd/mm/yy';
$("#date").datepicker("setDate", new Date());
Always work for me
There's a method that does this for you:
def show
@city = @user.city.present?
end
The present?
method tests for not-nil
plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.
Since this pattern is so common there's even a shortcut in ActiveRecord:
def show
@city = @user.city?
end
This is roughly equivalent.
As a note, testing vs nil
is almost always redundant. There are only two logically false values in Ruby: nil
and false
. Unless it's possible for a variable to be literal false
, this would be sufficient:
if (variable)
# ...
end
This is preferable to the usual if (!variable.nil?)
or if (variable != nil)
stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.
One reason you'd want to compare vs. nil
is if you have a tri-state variable that can be true
, false
or nil
and you need to distinguish between the last two states.
Another alternative would be to specify the list of libraries twice:
gcc prog.o libA.a libB.a libA.a libB.a -o prog.x
Doing this, you don't have to bother with the right sequence since the reference will be resolved in the second block.
Use below JavaScript method :
function msieversion()
{
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0) // If Internet Explorer, return version number
{
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
}
else // If another browser, return 0
{
alert('otherbrowser');
}
return false;
}
You may find the details on below Microsoft support site :
How to determine browser version from script
Update : (IE 11 support)
function msieversion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
{
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
}
else // If another browser, return 0
{
alert('otherbrowser');
}
return false;
}
Professional Excel Development by Stephen Bullen describes how to register UDFs, which allows a description to appear in the Function Arguments dialog:
Function IFERROR(ByRef ToEvaluate As Variant, ByRef Default As Variant) As Variant
If IsError(ToEvaluate) Then
IFERROR = Default
Else
IFERROR = ToEvaluate
End If
End Function
Sub RegisterUDF()
Dim s As String
s = "Provides a shortcut replacement for the common worksheet construct" & vbLf _
& "IF(ISERROR(<expression>), <default>, <expression>)"
Application.MacroOptions macro:="IFERROR", Description:=s, Category:=9
End Sub
Sub UnregisterUDF()
Application.MacroOptions Macro:="IFERROR", Description:=Empty, Category:=Empty
End Sub
From: http://www.ozgrid.com/forum/showthread.php?t=78123&page=1
To show the Function Arguments dialog, type the function name and press CtrlA. Alternatively, click the "fx" symbol in the formula bar:
Github recently released a cli utility called github-cli. After installing it, you can checkout a pull request's branch locally by using its id (ref)
e.g: gh pr checkout 2267
This works with forks as well but if you then need to push back to the fork, you'll need to add the remote repository and use traditional git push
(until this ticket gets implemented in gh utility)
You can, once you escape the HTML correctly. This page shows what needs to be done.
If using PHP, you could use json_encode()
Hope this helps :)
Combining the previous answers provides these solutions:
if (typeof str == 'string' || str instanceof String)
or
Object.prototype.toString.call(str) == '[object String]'
This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:
http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
Where are you getting the tiff images from? Is it possible for them to be generated in a different format?
If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.
If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.
By using this way you can get the list of selected records.
GregorianCalendar gregorianCalendar = new GregorianCalendar();
Criteria cri = session.createCriteria(ProjectActivities.class);
cri.add(Restrictions.ge("EffectiveFrom", gregorianCalendar.getTime()));
List list = cri.list();
All the Records will be generated into list which are greater than or equal to '08-Oct-2012' or else pass the date of user acceptance date at 2nd parameter of Restrictions (gregorianCalendar.getTime()
) of criteria to get the records.
Historically, in early C times, when processors had 8 or 16 bit wordlength,int
was identical to todays short
(16 bit). In a certain sense, int is a more abstract data type thanchar
,short
,long
orlong long
, as you cannot be sure about the bitwidth.
When definingint n;
you could translate this with "give me the best compromise of bitwidth and speed on this machine for n". Maybe in the future you should expect compilers to translateint
to be 64 bit. So when you want your variable to have 32 bits and not more, better use an explicitlong
as data type.
[Edit: #include <stdint.h>
seems to be the proper way to ensure bitwidths using the int##_t types, though it's not yet part of the standard.]
use this
final int childCount = mainL.getChildCount();
for (int i = 0; i < childCount; i++) {
View element = mainL.getChildAt(i);
// EditText
if (element instanceof EditText) {
EditText editText = (EditText)element;
System.out.println("ELEMENTS EditText getId=>"+editText.getId()+ " getTag=>"+element.getTag()+
" getText=>"+editText.getText());
}
// CheckBox
if (element instanceof CheckBox) {
CheckBox checkBox = (CheckBox)element;
System.out.println("ELEMENTS CheckBox getId=>"+checkBox.getId()+ " getTag=>"+checkBox.getTag()+
" getText=>"+checkBox.getText()+" isChecked=>"+checkBox.isChecked());
}
// DatePicker
if (element instanceof DatePicker) {
DatePicker datePicker = (DatePicker)element;
System.out.println("ELEMENTS DatePicker getId=>"+datePicker.getId()+ " getTag=>"+datePicker.getTag()+
" getDayOfMonth=>"+datePicker.getDayOfMonth());
}
// Spinner
if (element instanceof Spinner) {
Spinner spinner = (Spinner)element;
System.out.println("ELEMENTS Spinner getId=>"+spinner.getId()+ " getTag=>"+spinner.getTag()+
" getSelectedItemId=>"+spinner.getSelectedItemId()+
" getSelectedItemPosition=>"+spinner.getSelectedItemPosition()+
" getTag(key)=>"+spinner.getTag(spinner.getSelectedItemPosition()));
}
}
https://github.com/quartzjer/js0n
Ugliest interface possible, but does what you ask. Zero allocations.
http://zserge.com/jsmn.html Another zero-allocation approach.
The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.
Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.
And to answer your "writer" part of the question i doubt that you could beat an efficient
printf("{%s:%s}",name,value)
implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.
EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.
@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.
WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;
Hope this helps... :D
Discovered that calling stat
is slow and collects a lot of info that is not required for file existence check.
After spending some time searching for solution, i discovered following solution, which works much faster:
- raw: test -e /path/to/something && echo true || echo false
register: file_exists
- debug: msg="Path exists"
when: file_exists == true
The windows.load function is useful if you want to do something when everything is loaded.
$(window).load(function(){
// full load
});
But you can also use the .load function on any other element. So if you have one particularly large image and you want to do something when that loads but the rest of your page loading code when the dom has loaded you could do:
$(function(){
// Dom loaded code
$('#largeImage').load({
// Image loaded code
});
});
Also the jquery .load function is pretty much the same as a normal .onload.
void main()
{
int a,b,c,d,e,max;
max=a;
if(b/max)
max=b;
if(c/max)
max=c;
if(d/max)
max=d;
if(e/max)
max=e;
cout<<"Maximum is"<<max;
}
This will show original dimensions of Image on Hover using jQuery custom code
HTML
<ul class="thumb">
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/1.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/2.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/3.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/4.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/5.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/6.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/7.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/8.jpg)"></div>
</a>
</li>
<li>
<a href="javascript:void(0)">
<div class="thumbnail-wrap" style="background-image:url(./images/9.jpg)"></div>
</a>
</li>
</ul>
CSS
ul.thumb {
float: left;
list-style: none;
padding: 10px;
width: 360px;
margin: 80px;
}
ul.thumb li {
margin: 0;
padding: 5px;
float: left;
position: relative;
/* Set the absolute positioning base coordinate */
width: 110px;
height: 110px;
}
ul.thumb li .thumbnail-wrap {
width: 100px;
height: 100px;
/* Set the small thumbnail size */
-ms-interpolation-mode: bicubic;
/* IE Fix for Bicubic Scaling */
border: 1px solid #ddd;
padding: 5px;
position: absolute;
left: 0;
top: 0;
background-size: cover;
background-repeat: no-repeat;
-webkit-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
-moz-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
}
ul.thumb li .thumbnail-wrap.hover {
-webkit-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
-moz-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
}
.thumnail-zoomed-wrapper {
display: none;
position: fixed;
top: 0px;
left: 0px;
height: 100vh;
width: 100%;
background: rgba(0, 0, 0, 0.2);
z-index: 99;
}
.thumbnail-zoomed-image {
margin: auto;
display: block;
text-align: center;
margin-top: 12%;
}
.thumbnail-zoomed-image img {
max-width: 100%;
}
.close-image-zoom {
z-index: 10;
float: right;
margin: 10px;
cursor: pointer;
}
jQuery
var perc = 40;
$("ul.thumb li").hover(function () {
$("ul.thumb li").find(".thumbnail-wrap").css({
"z-index": "0"
});
$(this).find(".thumbnail-wrap").css({
"z-index": "10"
});
var imageval = $(this).find(".thumbnail-wrap").css("background-image").slice(5);
var img;
var thisImage = this;
img = new Image();
img.src = imageval.substring(0, imageval.length - 2);
img.onload = function () {
var imgh = this.height * (perc / 100);
var imgw = this.width * (perc / 100);
$(thisImage).find(".thumbnail-wrap").addClass("hover").stop()
.animate({
marginTop: "-" + (imgh / 4) + "px",
marginLeft: "-" + (imgw / 4) + "px",
width: imgw + "px",
height: imgh + "px"
}, 200);
}
}, function () {
var thisImage = this;
$(this).find(".thumbnail-wrap").removeClass("hover").stop()
.animate({
marginTop: "0",
marginLeft: "0",
top: "0",
left: "0",
width: "100px",
height: "100px",
padding: "5px"
}, 400, function () {});
});
//Show thumbnail in fullscreen
$("ul.thumb li .thumbnail-wrap").click(function () {
var imageval = $(this).css("background-image").slice(5);
imageval = imageval.substring(0, imageval.length - 2);
$(".thumbnail-zoomed-image img").attr({
src: imageval
});
$(".thumnail-zoomed-wrapper").fadeIn();
return false;
});
//Close fullscreen preview
$(".thumnail-zoomed-wrapper .close-image-zoom").click(function () {
$(".thumnail-zoomed-wrapper").hide();
return false;
});
I work with a computed property like:
items:{
get(){
return this.resources;
},
set(v){
this.$emit("update:resources", v)
}
},
Resources is in this case a property:
props: [ 'resources' ]
WakeLock doesn't usually cause Reboot problems. There may be some other issues in your coding. WakeLock hogs battery heavily, if not released after usage.
WakeLock is an Inefficient way of keeping the screen on. Instead use the WindowManager to do the magic. The following one line will suffice the WakeLock. The WakeLock Permission is also needed for this to work. Also this code is more efficient than the wakeLock.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
You need not relase the WakeLock Manually. This code will allow the Android System to handle the Lock Automatically. When your application is in the Foreground then WakeLock is held and else android System releases the Lock automatically.
Try this and post your comment...
STATICFILES_DIRS
: You can keep the static files for your project here e.g. the ones used by your templates.
STATIC_ROOT
: leave this empty, when you do manage.py collectstatic
, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.
--------Edit----------------
As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
or
STATIC_ROOT = '/opt/web/project/static_files'
--------End Edit -----------------
STATIC_URL
: '/static/' is usually fine, it's just a prefix for static files.
Or, if you are doing a split - join:
GROUP_CONCAT(split(thing, " "), '----') AS thing_name,
You may want to inclue WITHIN RECORD
, like this:
GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,
from BigQuery API page
I assume those XAML namespace declarations are in the parent tag of your control? You can't put comments inside of another tag. Other than that, the syntax you're using is correct.
<UserControl xmlns="...">
<!-- Here's a valid comment. Notice it's outside the <UserControl> tag's braces -->
[..snip..]
</UserControl>
The easiest way to determine the week number ISO 8601 style using c# and the DateTime class.
Ask this: the how-many-eth thursday of the year is the thursday of this week. The answer equals the wanted week number.
var dayOfWeek = (int)moment.DayOfWeek;
// Make monday the first day of the week
if (--dayOfWeek < 0)
dayOfWeek = 6;
// The whole nr of weeks before this thursday plus one is the week number
var weekNumber = (moment.AddDays(3 - dayOfWeek).DayOfYear - 1) / 7 + 1;
I got here with an MS Access problem.
Backticks are good for MySQL, but they create weird errors, like "Invalid Query Name: Query1" in MS Access, for MS Access only, use square brackets:
It should look like this
SELECT Customer.[Customer ID], Customer.[Full Name] ...
use the below code.
alert(+(Math.round(number + "e+2") + "e-2"));
$(form).ajaxSubmit();
triggers another validation resulting to a recursion. try changing it to
form.ajaxSubmit();
You have to take whole columns under resizebox. This code worked for me
\begin{table}[htbp]
\caption{Sample Table.}\label{tab1}
\resizebox{\columnwidth}{!}{\begin{tabular}{|l|l|l|l|l|}
\hline
URL & First Time Visit & Last Time Visit & URL Counts & Value\\
\hline
https://web.facebook.com/ & 1521241972 & 1522351859 & 177 & 56640\\
http://localhost/phpmyadmin/ & 1518413861 & 1522075694 & 24 & 39312\\
https://mail.google.com/mail/u/ & 1516596003 & 1522352010 & 36 & 33264\\
https://github.com/shawon100& 1517215489 & 1522352266 & 37 & 27528\\
https://www.youtube.com/ & 1517229227 & 1521978502 & 24 & 14792\\
\hline
\end{tabular}}
\end{table}
If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.
We were trying to avoid using the IE specific
$window[0].document.body.clientHeight
And found that the following jQuery will not consistently yield the same value but eventually does at some point in our page load scenario which worked for us and maintained cross-browser support:
$(document).height()
bool vExist = false;
int vSelectValue = 1;
List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);
IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
vExist = true;
}
We copy the JRE's truststore and add our custom certificates to that truststore, then tell the application to use the custom truststore with a system property. This way we leave the default JRE truststore alone.
The downside is that when you update the JRE you don't get its new truststore automatically merged with your custom one.
You could maybe handle this scenario by having an installer or startup routine that verifies the truststore/jdk and checks for a mismatch or automatically updates the truststore. I don't know what happens if you update the truststore while the application is running.
This solution isn't 100% elegant or foolproof but it's simple, works, and requires no code.
Please verify that the required plug-ins are enabled in Settings | Plugins, most likely you've disabled several of them, that's why you don't see all the facet options.
For the step by step tutorial, see: Creating a simple Web application and deploying it to Tomcat.
var cats = ['Tom','Fluffy','Tom','Bella','Chloe','Tom','Chloe'];
var counts = {};
var compare = 0;
var mostFrequent;
(function(array){
for(var i = 0, len = array.length; i < len; i++){
var word = array[i];
if(counts[word] === undefined){
counts[word] = 1;
}else{
counts[word] = counts[word] + 1;
}
if(counts[word] > compare){
compare = counts[word];
mostFrequent = cats[i];
}
}
return mostFrequent;
})(cats);
I've used Quick Highlighter a lot. Works great for a huge list of languages.
"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)
for (let i = 0; i < someArray.length ; i++) {
let item = someArray[i];
}
I had hard times figuring it out myself and this post helped me to find the right answer for my case. When working with financial messaging as ISO-8583 the 3DES requirements are quite specific, so for my especial case the "DESede/CBC/PKCS5Padding" combinations wasn't solving the problem. After some comparative testing of my results against some 3DES calculators designed for the financial world I found the the value "DESede/ECB/Nopadding" is more suited for the the specific task.
Here is a demo implementation of my TripleDes class (using the Bouncy Castle provider)
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* @author Jose Luis Montes de Oca
*/
public class TripleDesCipher {
private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/Nopadding";
private static String ALGORITHM = "DESede";
private static String BOUNCY_CASTLE_PROVIDER = "BC";
private Cipher encrypter;
private Cipher decrypter;
public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
InvalidKeyException {
Security.addProvider(new BouncyCastleProvider());
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
decrypter.init(Cipher.DECRYPT_MODE, keySpec);
}
public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
return encrypter.doFinal(input);
}
public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
return decrypter.doFinal(input);
}
}
Be advised -- you will lose ALL Facebook Likes when doing this (provided you started collecting your Likes with an http
connection!
Instead use JavaScript
if (location.protocol !== 'https:') {
location.replace('https:${location.href.substring(location.protocol.length)}');
}
and put it last in the header.
Try moving the order by clause outside sub select and add the order by field in sub select
SELECT * FROM
(SELECT COUNT(1) ,refKlinik_id FROM Seanslar WHERE MONTH(tarihi) = 4 GROUP BY refKlinik_id)
as dorduncuay
ORDER BY refKlinik_id
You can say comboBox1.Text = comboBox1.Items[0].ToString();
You simply need to use simpleCart
It is a free and open-source javascript shopping cart that easily integrates with your current website.
You will get the full source code at github
ToAddress = "[email protected]"
ToAddress1 = "[email protected]"
ToAddress2 = "[email protected]"
MessageSubject = "It works!."
Set ol = CreateObject("Outlook.Application")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.RecipIents.Add(ToAddress)
newMail.RecipIents.Add(ToAddress1)
newMail.RecipIents.Add(ToAddress2)
newMail.Send
There are more than 90 implemented distribution functions in SciPy v1.6.0. You can test how some of them fit to your data using their fit()
method. Check the code below for more details:
import matplotlib.pyplot as plt
import numpy as np
import scipy
import scipy.stats
size = 30000
x = np.arange(size)
y = scipy.int_(np.round_(scipy.stats.vonmises.rvs(5,size=size)*47))
h = plt.hist(y, bins=range(48))
dist_names = ['gamma', 'beta', 'rayleigh', 'norm', 'pareto']
for dist_name in dist_names:
dist = getattr(scipy.stats, dist_name)
params = dist.fit(y)
arg = params[:-2]
loc = params[-2]
scale = params[-1]
if arg:
pdf_fitted = dist.pdf(x, *arg, loc=loc, scale=scale) * size
else:
pdf_fitted = dist.pdf(x, loc=loc, scale=loc) * size
plt.plot(pdf_fitted, label=dist_name)
plt.xlim(0,47)
plt.legend(loc='upper right')
plt.show()
References:
- Fitting distributions, goodness of fit, p-value. Is it possible to do this with Scipy (Python)?
- Distribution fitting with Scipy
And here a list with the names of all distribution functions available in Scipy 0.12.0 (VI):
dist_names = [ 'alpha', 'anglit', 'arcsine', 'beta', 'betaprime', 'bradford', 'burr', 'cauchy', 'chi', 'chi2', 'cosine', 'dgamma', 'dweibull', 'erlang', 'expon', 'exponweib', 'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'frechet_r', 'frechet_l', 'genlogistic', 'genpareto', 'genexpon', 'genextreme', 'gausshyper', 'gamma', 'gengamma', 'genhalflogistic', 'gilbrat', 'gompertz', 'gumbel_r', 'gumbel_l', 'halfcauchy', 'halflogistic', 'halfnorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb', 'johnsonsu', 'ksone', 'kstwobign', 'laplace', 'logistic', 'loggamma', 'loglaplace', 'lognorm', 'lomax', 'maxwell', 'mielke', 'nakagami', 'ncx2', 'ncf', 'nct', 'norm', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rdist', 'reciprocal', 'rayleigh', 'rice', 'recipinvgauss', 'semicircular', 't', 'triang', 'truncexpon', 'truncnorm', 'tukeylambda', 'uniform', 'vonmises', 'wald', 'weibull_min', 'weibull_max', 'wrapcauchy']
You could install Web Tool Platform on top of your current installation to help you learn about Java EE. Download the Web Tools Platform by using Eclipse Software Update (Instruction at http://download.eclipse.org/webtools/updates/). It has features to get you going with learning Java EE. You could learn more about Web Tools Platform at http://www.eclipse.org/webtools/
The simplest way imo:
(It can also be used with emails for example)
public static matchValues(
matchTo: string // name of the control to match to
): (AbstractControl) => ValidationErrors | null {
return (control: AbstractControl): ValidationErrors | null => {
return !!control.parent &&
!!control.parent.value &&
control.value === control.parent.controls[matchTo].value
? null
: { isMatching: false };
};
}
In your Component:
this.SignUpForm = this.formBuilder.group({
password: [undefined, [Validators.required]],
passwordConfirm: [undefined,
[
Validators.required,
matchValues('password'),
],
],
});
Follow up:
As others pointed out in the comments, if you fix the error by fixing the password
field the error won't go away, Because the validation triggers on passwordConfirm
input. This can be fixed by a number of ways. I think the best is:
this.SignUpForm .controls.password.valueChanges.subscribe(() => {
this.SignUpForm .controls.confirmPassword.updateValueAndValidity();
});
On password
change, revliadte confirmPassword
.
To run once, daily at 10PM you should do something like this:
0 22 * * *
Full size image: http://i.stack.imgur.com/BeXHD.jpg
Source: softpanorama.org
After installing ez_setup, you should have easy_install
available. To install pip
just do:
easy_install pip
As long as we're using jQuery (> v1.8), we can parse the incoming string with $.parseHTML().
$('.tooltip').tooltip({
content: function () {
var tooltipContent = $('<div />').html( $.parseHTML( $(this).attr('title') ) );
return tooltipContent;
},
});
We'll parse the incoming string's attribute for unpleasant things, then convert it back to jQuery-readable HTML. The beauty of this is that by the time it hits the parser the strings are already concatenates, so it doesn't matter if someone is trying to split the script tag into separate strings. If you're stuck using jQuery's tooltips, this appears to be a solid solution.
You can use this for objects
transform(array: any[], field: string): any[] {
return array.sort((a, b) => a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0);}
There's no need for LINQ here, just call Sort:
list.Sort();
Example code:
List<int> list = new List<int> { 5, 7, 3 };
list.Sort();
foreach (int x in list)
{
Console.WriteLine(x);
}
Result:
3
5
7
The button code should be moved to the PlaceholderFragment()
class. There you will call the layout fragment_main.xml
in the onCreateView
method. Like so
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button) view.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
return view;
}
angular.module('elnApp')
.directive('jqdatepicker', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
$(element).datepicker({
dateFormat: 'dd.mm.yy',
onSelect: function(date) {
ctrl.$setViewValue(date);
ctrl.$render();
scope.$apply();
}
});
}
};
});
You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException
. As the documentation says:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
Which is exactly what is going on here.
if (divisor == 0) {
throw new IllegalArgumentException("Argument 'divisor' is 0");
}
You really ought to get a framework in place via a repository and identifying your dependencies up front. Using the system scope is a common mistake people use, because they "don't care about the dependency management." The trouble is that doing this you end up with a perverted maven build that will not show maven in a normal condition. You would be better off following an approach like this.
The problem is that some versions of explorer don't support the window.open javascript function
Say what? Can you provide a reference for that statement? With respect, I think you must be mistaken. This works on IE6 and IE9, for instance.
Most modern browsers won't let your code use window.open
except in direct response to a user event, in order to keep spam pop-ups and such at bay; perhaps that's what you're thinking of. As long as you only use window.open
when responding to a user event, you should be fine using window.open
— with all versions of IE.
There is no way to use location
to open a new window. Just window.open
or, of course, the user clicking a link with target="_blank"
.
SELECT
p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, r.command,
p.program_name, text
FROM
sys.dm_exec_requests AS r,
master.dbo.sysprocesses AS p
CROSS APPLY sys.dm_exec_sql_text(p.sql_handle)
WHERE
p.status NOT IN ('sleeping', 'background')
AND r.session_id = p.spid
Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"
Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.
If System.IO.File.Exists(SavePath) Then
'The file exists
Else
'the file doesn't exist
End If
abc(?!def) will match abc not followed by def. So it'll match abce, abc, abck, etc. what if I want neither def nor xyz will it be abc(?!(def)(xyz)) ???
I had the same question and found a solution:
abc(?:(?!def))(?:(?!xyz))
These non-counting groups are combined by "AND", so it this should do the trick. Hope it helps.
If the file is local as your comment about SITE_PATH
suggest, it's pretty simple just execute the script and cache the result in a variable using the output control functions :
function print_xml_data_file()
{
include(XML_DATA_FILE_DIRECTORY . 'cms/data.php');
}
function get_xml_data()
{
ob_start();
print_xml_data_file();
$xml_file = ob_get_contents();
ob_end_clean();
return $xml_file;
}
If it's remote as lot of others said curl
is the way to go. If it isn't present try socket_create
or fsockopen
. If nothing work... change your hosting provider.
Your question doesn't have anything to do with PHP... just CSS.
Your CSS is correct, but your browser won't typically be able to open what you have put in for a URL. At a minimum, you'll need a file:
path. It would be best to reference the file by its relative path.
I have come to the conclusion that this is not possible without any plugins.
You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.
str=xpath.replaceAll("\\.", "/*/"); //replaces a literal . with /*/
declare @myColumn as nvarchar(128)
set @myColumn = 'myColumn'
if not exists (
select 1
from information_schema.columns columns
where columns.table_catalog = 'myDatabase'
and columns.table_schema = 'mySchema'
and columns.table_name = 'myTable'
and columns.column_name = @myColumn
)
begin
exec('alter table myDatabase.mySchema.myTable add'
+' ['+@myColumn+'] bigint null')
end
I do not really think so, what I can find is the word "this." causes the hibernate not to include any restrictions in its query, which means it got all the records lists. About the hibernate bug that was reported, I can see it's reported as fixed but I totally failed to download the Patch.
I wrote with parameters that are predefined
They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:
Alter Procedure [Test]
@StartDate AS varchar(6) = NULL,
@EndDate AS varchar(6) = NULL
AS
...
NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.
Now you can call it without passing any arguments e.g.
exec dbo.TEST
In ECMAScript 2015 (aka "ES6") you can declare default argument values in the function declaration:
function myFunc(requiredArg, optionalArg = 'defaultValue') {
// do stuff
}
More about them in this article on MDN.
This is currently only supported by Firefox, but as the standard has been completed, expect support to improve rapidly.
EDIT (2019-06-12):
Default parameters are now widely supported by modern browsers.
All versions of Internet Explorer do not support this feature. However, Chrome, Firefox, and Edge currently support it.
This is coming from JPA
. In a very simple way:
persist(entity)
should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).
merge(entity)
should be used, to put entity back to persistence context if the entity was detached and was changed.
I gave an answer there and I demonstrate with a jsfiddle. You can check for different devices and report it.
Basically I use a kind of event lock with some functions that serve it:
/*
* Event lock functions
* ====================
*/
function getEventLock(evt, key){
if(typeof(eventLock[key]) == 'undefined'){
eventLock[key] = {};
eventLock[key].primary = evt.type;
return true;
}
if(evt.type == eventLock[key].primary)
return true;
else
return false;
}
function primaryEventLock(evt, key){
eventLock[key].primary = evt.type;
}
Then, in my event handlers I start by a request to my lock:
/*
* Event handlers
* ==============
*/
$("#add").on("touchstart mousedown", addStart);
$("#add").on("touchend mouseup", addEnd);
function addStart(evt){
// race condition between 'mousedown' and 'touchstart'
if(!getEventLock(evt, 'add'))
return;
// some logic
now = new Date().getTime();
press = -defaults.pressDelay;
task();
// enable event lock and(?) event repetition
pids.add = setTimeout(closure, defaults.pressDelay);
function closure(){
// some logic(?): comment out to disable repetition
task();
// set primary input device
primaryEventLock(evt, 'add');
// enable event repetition
pids.add = setTimeout(closure, defaults.pressDelay);
}
}
function addEnd(evt){
clearTimeout(pids.add);
}
I have to stress that the problem is not to respond simply at a event but to NOT respond on both.
Finally, at jsfiddle there is a link to an updated version where I introduce minimal impact at existing code by adding just a simple call to my event lock library both at event start & end handlers along with 2 scope variables eventLock
and eventLockDelay
.
Just use replace()
var values = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
var substitutedString = "My Name is %NAME% and my age is %AGE%.".replace("%NAME%", $values["%NAME%"]).replace("%AGE%", $values["%AGE%"]);
Most commonly, you'd use:
import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding
Python provides other distributions if you need.
If you have numpy
imported already, you can used its equivalent:
import numpy as np
np.random.uniform(a, b) # range [a, b)
Again, if you need another distribution, numpy
provides the same distributions as python, as well as many additional ones.
What do you mean costs too much? Too much what?
SELECT MAX(Balance) AS MaxBalance, CustomerID FROM CUSTOMERS GROUP BY CustomerID
If your table is properly indexed (Balance) and there has got to be an index on the PK than I am not sure what you mean about costs too much or seems unreliable? There is nothing unreliable about an aggregate that you are using and telling it to do. In this case, MAX()
does exactly what you tell it to do - there's nothing magical about it.
Take a look at MAX()
and if you want to filter it use the HAVING
clause.
Solution is to change Delimiter.
Content of the csv file -> Note .. Also space and , in value
Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan
Col1;Col2;Col3
a,ap;noo,t;mi es
P,iet;G ,ijs;Ja ,n
$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';'
Answer:
Write-Host $csv
@{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}
It is possible to read a CSV file and use other Delimiter to separate each column.
It worked for my script :-)
The dispatcher-servlet.xml
file contains all of your configuration for Spring MVC
. So in it you will find beans such as ViewHandlerResolvers
, ConverterFactories
, Interceptors
and so forth. All of these beans are part of Spring MVC
which is a framework that structures how you handle web requests, providing useful features such as databinding, view resolution and request mapping.
The application-context.xml
can optionally be included when using Spring MVC
or any other framework for that matter. This gives you a container that may be used to configure other types of spring beans that provide support for things like data persistence. Basically, in this configuration file is where you pull in all of the other goodies Spring offers.
These configuration files are configured in the web.xml file as shown:
Dispatcher Config
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Application Config
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/application-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
To configure controllers, annotate them with @Controller
then include the following in the dispatcher-context.xml
file:
<mvc:annotation-driven/>
<context:component-scan base-package="package.with.controllers.**" />
it would be something like this
sqlplus -s /nolog <<-!
connect ${ORACLE_UID}/${ORACLE_PWD}@${ORACLE_DB};
whenever sqlerror exit sql.sqlcode;
set pagesize 0;
set linesize 150;
spool <query_output.dat> APPEND
@$<input_query.dat>
spool off;
exit;
!
here
ORACLE_UID=<user name>
ORACLE_PWD=<password>
ORACLE_DB=//<host>:<port>/<DB name>
The question "Why do we need to install gulp globally and locally?" can be broken down into the following two questions:
Why do I need to install gulp locally if I've already installed it globally?
Why do I need to install gulp globally if I've already installed it locally?
Several others have provided excellent answers to theses questions in isolation, but I thought it would be beneficial to consolidate the information in a unified answer.
Why do I need to install gulp locally if I've already installed it globally?
The rationale for installing gulp locally is comprised of several reasons:
Why do I need to install gulp globally if I've already installed it locally?
To avoid installing locally you can use npm link [package]
, but the link command as well as the install --global
command doesn't seem to support the --save-dev
option which means there doesn't appear to be an easy way to install gulp globally and then easily add whatever version that is to your local package.json file.
Ultimately, I believe it makes more sense to have the option of using global modules to avoid having to duplicate the installation of common tools across all your projects, especially in the case of development tools such as grunt, gulp, jshint, etc. Unfortunately it seems you end up fighting the tools a bit when you go against the grain.
When a dictionary is enumerated, it will yield KeyValuePair<TKey,TValue>
objects... so you just need to specify "Value" and "Key" for DataTextField
and DataValueField
respectively, to select the Value/Key properties.
Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as:
list.Add(cul.DisplayName, cod);
(And then changing the binding to use "Key" for DataTextField
and "Value" for DataValueField
, of course.)
In fact, I'd suggest that as it seems you really do want a list rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a List<KeyValuePair<string, string>>
:
string[] languageCodsList = service.LanguagesAvailable();
var list = new List<KeyValuePair<string, string>>();
foreach (string cod in languageCodsList)
{
CultureInfo cul = new CultureInfo(cod);
list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod));
}
Alternatively, use a list of plain CultureInfo
values. LINQ makes this really easy:
var cultures = service.LanguagesAvailable()
.Select(language => new CultureInfo(language));
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();
If you're not using LINQ, you can still use a normal foreach loop:
List<CultureInfo> cultures = new List<CultureInfo>();
foreach (string cod in service.LanguagesAvailable())
{
cultures.Add(new CultureInfo(cod));
}
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();
[[UIApplication sharedApplication] terminateWithSuccess];
It worked fine and automatically calls
- (void)applicationWillTerminateUIApplication *)application delegate.
to remove compile time warning add this code
@interface UIApplication(MyExtras)
- (void)terminateWithSuccess;
@end
I had this same problem for days. Keeping srand() out of the loop is a +. Also, dont assign rand() % 100 to any variable. Simply cout rand() % 100 in the loop. Try this:
srand (time(NULL));
(int t=0;t<10;t++)
{
cout << rand() % 100 << endl;
}
actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:
Just watch:
list = ['a', 'b', 'c']
dictionary = {}
counter = 0
for i in list:
dictionary[i] = counter
counter += 1
print(dictionary) # dictionary = {'a':0, 'b':1, 'c':2}
Now through the power of hashmaps you can pull the index your entries in constant time (aka a whole lot faster)
Just add profile to session configuration before client call.
boto3.session.Session(profile_name='YOUR_PROFILE_NAME').client('cloudwatch')
I have encountered this problem in Eclipse Luna EE. My solution was simply restart eclipse and it magically started loading servlet properly.
For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:
document.getElementById("iframe_id").contentWindow.location.href
If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.
See also answers to a similar question.
First, you need to compile your code with appropriate flags, enabling debug into code.
$ gcc -Wall -g -ggdb -o ex1 ex1.c
then just run you code with your favourite debugger
$ gdb ./ex1
show me the code.
(gdb) list
1 #include <stdio.h>
2 int main(void)
3 {
4 int i = 0;
5 for(i=0;i<7;++i)
6 printf("%d\n", i);
7
8 return 0;
9 }
break on lines 5 and looks if i == 5.
(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i
checking breakpoints
(gdb) info b
Num Type Disp Enb Address What
1 breakpoint keep y 0x00000000004004fb in main at ex1.c:5
breakpoint already hit 1 time
5 read watchpoint keep y i
stop only if i==5
running the program
(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i
Value = 5
0x0000000000400523 in main () at ex1.c:5
5 for(i=0;i<7;++i)
For those trying to get everything after the first occurance:
Something like "Nic K Cage"
to "K Cage"
.
You can use slice to get everything from a certain character. In this case from the first space:
const delim = " "
const name = "Nic K Cage"
const end = name.split(delim).slice(1).join(delim) // prints: "K Cage"
Or if OP's string had two hyphens:
const text = "sometext-20202-03"
// Option 1
const op1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const op2 = text.split('-').slice(1).join("-") // prints: 20202-03
I’m using the PyCharm IDE. I could get Pygame to work with IDLE but not with PyCharm. This video helped me install Pygame through PyCharm.
(It seems that PyCharm only recognizes a package; if you use its GUI.)
However, there were a few slight differences for me; because I’m using Windows instead of a Mac.
My “preferences” menu is found in: File->Settings…
Then, in the next screen, I expanded my project menu, and clicked Project Interpreter. Then I clicked the green plus icon to the right to get to the Available Packages screen.
We simply did:
import io
from pathlib import Path
def test_my_upload(self, accept_json):
"""Test my uploads endpoint for POST."""
data = {
"filePath[]": "/tmp/bin",
"manifest[]": (io.StringIO(str(Path(__file__).parent /
"path_to_file/npmlist.json")).read(),
'npmlist.json'),
}
headers = {
'a': 'A',
'b': 'B'
}
res = self.client.post(api_route_for('/test'),
data=data,
content_type='multipart/form-data',
headers=headers,
)
assert res.status_code == 200
pgrep -f process_name > any_file_name
sed -i 's/^/kill /' any_file_name
chmod 777 any_file_name
./any_file_name
for example 'pgrep -f firefox' will grep the PID of running 'firefox' and will save this PID to a file called 'any_file_name'. 'sed' command will add the 'kill' in the beginning of the PID number in 'any_file_name' file. Third line will make 'any_file_name' file executable. Now forth line will kill the PID available in the file 'any_file_name'. Writing the above four lines in a file and executing that file can do the control-C. Working absolutely fine for me.
(OK, I know you are asking for shrink-wrap, but maybe those home-grown solutions just weren't succinct enough for your liking. :-)
pdf = [(1, 0.1), (2, 0.05), (3, 0.05), (4, 0.2), (5, 0.4), (6, 0.2)]
cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf]
R = max(i for r in [random.random()] for i,c in cdf if c <= r)
I pseudo-confirmed that this works by eyeballing the output of this expression:
sorted(max(i for r in [random.random()] for i,c in cdf if c <= r)
for _ in range(1000))
All of
std::string s(1, c); std::cout << s << std::endl;
and
std::cout << std::string(1, c) << std::endl;
and
std::string s; s.push_back(c); std::cout << s << std::endl;
worked for me.
realpath
is probably best
But ...
The initial question was very confused to start with, with an example poorly related to the question as stated.
The selected answer actually answers the example given, and not at all the question in the title. The first command is that answer (is it really ? I doubt), and could do as well without the '/'. And I fail to see what the second command is doing.
Several issues are mixed :
changing a relative pathname into an absolute one, whatever it
denotes, possibly nothing.
(Typically, if you issue a command such as touch foo/bar
, the
pathname foo/bar
must exist for you, and possibly be used in
computation, before the file is actually created.)
there may be several absolute pathname that denote the same file (or potential file), notably because of symbolic links (symlinks) on the path, but possibly for other reasons (a device may be mounted twice as read-only). One may or may not want to resolve explicity such symlinks.
getting to the end of a chain of symbolic links to a non-symlink file or name. This may or may not yield an absolute path name, depending on how it is done. And one may, or may not want to resolve it into an absolute pathname.
The command readlink foo
without option gives an answer only if its
argument foo
is a symbolic link, and that answer is the value of that
symlink. No other link is followed. The answer may be a relative path:
whatever was the value of the symlink argument.
However, readlink
has options (-f -e or -m) that will work for all
files, and give one absolute pathname (the one with no symlinks) to
the file actually denoted by the argument.
This works fine for anything that is not a symlink, though one might
desire to use an absolute pathname without resolving the intermediate
symlinks on the path. This is done by the command realpath -s foo
In the case of a symlink argument, readlink
with its options will
again resolve all symlinks on the absolute path to the argument, but
that will also include all symlinks that may be encountered by
following the argument value. You may not want that if you desired an
absolute path to the argument symlink itself, rather than to whatever
it may link to. Again, if foo
is a symlink, realpath -s foo
will
get an absolute path without resolving symlinks, including the one
given as argument.
Without the -s
option, realpath
does pretty much the same as
readlink
, except for simply reading the value of a link, as well as several
other things. It is just not clear to me why readlink
has its
options, creating apparently an undesirable redundancy with
realpath
.
Exploring the web does not say much more, except that there may be some variations across systems.
Conclusion : realpath
is the best command to use, with the most
flexibility, at least for the use requested here.
Indeed you cannot save changes inside a foreach
loop in C# using Entity Framework.
context.SaveChanges()
method acts like a commit on a regular database system (RDMS).
Just make all changes (which Entity Framework will cache) and then save all of them at once calling SaveChanges()
after the loop (outside of it), like a database commit command.
This works if you can save all changes at once.
These solutions are very helpful during testing. Building on everyone else's answers I do this in Python 2.7.9 (without staticmethod I get a TypeError (unbound method...):
In [11]: auth = type('', (), {})
In [12]: auth.func = staticmethod(lambda i: i * 2)
In [13]: auth.func(2)
Out[13]: 4
The .success
syntax was correct up to Angular v1.4.3.
For versions up to Angular v.1.6, you have to use then
method. The then()
method takes two arguments: a success
and an error
callback which will be called with a response object.
Using the then()
method, attach a callback
function to the returned promise
.
Something like this:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){
},function (error){
});
}
See reference here.
Shortcut
methods are also available.
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
The data you get from the response is expected to be in JSON
format.
JSON is a great way of transporting data, and it is easy to use within AngularJS
The major difference between the 2 is that .then()
call returns a promise
(resolved with a value returned from a callback
) while .success()
is more traditional way of registering callbacks
and doesn't return a promise
.
I cheated problem using transition by steps, not smoothly
transition-timing-function: steps(10, end);
It is not a solving, it is a cheating and can not be applied everywhere.
I can't explain it, but it works for me. None of another answers helps me (OSX, Chrome 63, Non-Retina display).
this will work for sure..
RelativeLayout layout = new RelativeLayout(R.layout.your_layour);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
params.addRule(LinearLayout.CENTER_IN_PARENT);
textView.setLayoutParams(params);
textView.setGravity(Gravity.CENTER);
layout.addView(textView);
setcontentView(layout);
Of course you can use the StringTokenizer
class to split the String with '.' or '/', and check if the last word is "work".
What is the difference between char array vs char pointer in C?
C99 N1256 draft
There are two different uses of character string literals:
Initialize char[]
:
char c[] = "abc";
This is "more magic", and described at 6.7.8/14 "Initialization":
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
So this is just a shortcut for:
char c[] = {'a', 'b', 'c', '\0'};
Like any other regular array, c
can be modified.
Everywhere else: it generates an:
So when you write:
char *c = "abc";
This is similar to:
/* __unnamed is magic because modifying it gives UB. */
static char __unnamed[] = "abc";
char *c = __unnamed;
Note the implicit cast from char[]
to char *
, which is always legal.
Then if you modify c[0]
, you also modify __unnamed
, which is UB.
This is documented at 6.4.5 "String literals":
5 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence [...]
6 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
6.7.8/32 "Initialization" gives a direct example:
EXAMPLE 8: The declaration
char s[] = "abc", t[3] = "abc";
defines "plain" char array objects
s
andt
whose elements are initialized with character string literals.This declaration is identical to
char s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable. On the other hand, the declaration
char *p = "abc";
defines
p
with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
GCC 4.8 x86-64 ELF implementation
Program:
#include <stdio.h>
int main(void) {
char *s = "abc";
printf("%s\n", s);
return 0;
}
Compile and decompile:
gcc -ggdb -std=c99 -c main.c
objdump -Sr main.o
Output contains:
char *s = "abc";
8: 48 c7 45 f8 00 00 00 movq $0x0,-0x8(%rbp)
f: 00
c: R_X86_64_32S .rodata
Conclusion: GCC stores char*
it in .rodata
section, not in .text
.
If we do the same for char[]
:
char s[] = "abc";
we obtain:
17: c7 45 f0 61 62 63 00 movl $0x636261,-0x10(%rbp)
so it gets stored in the stack (relative to %rbp
).
Note however that the default linker script puts .rodata
and .text
in the same segment, which has execute but no write permission. This can be observed with:
readelf -l a.out
which contains:
Section to Segment mapping:
Segment Sections...
02 .text .rodata
Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two schemas instead - in that case you don't need anything special to query across them.
postgres_fdw
Use postgres_fdw
(foreign data wrapper) to connect to tables in any Postgres database - local or remote.
Note that there are foreign data wrappers for other popular data sources. At this time, only postgres_fdw
and file_fdw
are part of the official Postgres distribution.
Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called dblink
.
I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib.
Yes. Problem is in wrong notation. Use:
$this->sendRequest($uri)
Instead. Or
self::staticMethod()
for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And then install wget
with brew and also enable openressl
for TLS support
brew install wget --with-libressl
It worked perfectly for me.
please try to install the dependencie with pip, run this command:
sudo pip install -U setuptools
Here is some good overview of .NET impersonation concepts.
Basically you will be leveraging these classes that are out of the box in the .NET framework:
The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.
In Jupyter Lab 2.1.5, it is View -> Show Line Numbers.
Why not use MySQL LIMIT keyword?
SELECT [t2].[AnotherColumn], [t2].[SomeColumn]
FROM [Table] AS [t2]
WHERE (([t1].[SomeColumn] IS NULL) AND ([t2].[SomeColumn] IS NULL))
OR (([t1].[SomeColumn] IS NOT NULL) AND ([t2].[SomeColumn] IS NOT NULL)
AND ([t1].[SomeColumn] = [t2].[SomeColumn]))
ORDER BY [t2].[AnotherColumn]
LIMIT 1
On Xampp edit apache config
Although John Sansom's solution works, there's another way to do this, without having to use a potentially inefficient scalar valued UDF. In the SSRS report, on the parameters tab of the query definition, set the parameter value to
=join(Parameters!<your param name>.Value,",")
In your query, you can then reference the value like so:
where yourColumn in (@<your param name>)
If instead
[DisplayName("Something To Name")]
you use
[Display(Name = "Something To Name")]
Just do this:
private string GetDisplayName(Class1 class1)
{
string displayName = string.Empty;
string propertyName = class1.Name.GetType().Name;
CustomAttributeData displayAttribute = class1.GetType().GetProperty(propertyName).CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "DisplayAttribute");
if (displayAttribute != null)
{
displayName = displayAttribute.NamedArguments.FirstOrDefault().TypedValue.Value;
}
return displayName;
}
The mentioned package/classes are not present in the compiletime classpath. Basically, Java has no idea what you're talking about when you say to import this and that. It can't find them in the classpath.
It's part of Apache Commons FileUpload. Just download the JAR and drop it in /WEB-INF/lib
folder of the webapp project and this error should disappear. Don't forget to do the same for Apache Commons IO, that's where FileUpload depends on, otherwise you will get the same problem during runtime.
Unrelated to the concrete problem, I see that you're using Tomcat 7, which is a Servlet 3.0 compatible container. Do you know that you can just use the new request.getPart()
method to obtain the uploaded file without the need for the whole Commons FileUpload stuff? Just add @MultipartConfig
annotation to the servlet class so that you can use it. See also How to upload files to server using JSP/Servlet?
Thank you "Rob"....I had same problem with UICollectionView and your answer help me to solved my problem. Here is my code :
if ([Dict valueForKey:@"ImageURL"] != [NSNull null])
{
cell.coverImageView.image = nil;
cell.coverImageView.imageURL=nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if ([Dict valueForKey:@"ImageURL"] != [NSNull null] )
{
dispatch_async(dispatch_get_main_queue(), ^{
myCell *updateCell = (id)[collectionView cellForItemAtIndexPath:indexPath];
if (updateCell)
{
cell.coverImageView.image = nil;
cell.coverImageView.imageURL=nil;
cell.coverImageView.imageURL=[NSURL URLWithString:[Dict valueForKey:@"ImageURL"]];
}
else
{
cell.coverImageView.image = nil;
cell.coverImageView.imageURL=nil;
}
});
}
});
}
else
{
cell.coverImageView.image=[UIImage imageNamed:@"default_cover.png"];
}
https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.
The correct answer is "python collections do not have a foreach
". In native python we need to resort to the external for _element_ in _collection_
syntax which is not what the OP is after.
Python is in general quite weak for functionals programming. There are a few libraries to mitigate a bit. I helped author one of these infixpy
https://pypi.org/project/infixpy/
from infixpy import Seq
(Seq([1,2,3]).foreach(lambda x: print(x)))
1
2
3
Also see: Left to right application of operations on a list in Python 3
var seconds = 0;
setInterval(function () {
seconds++;
}, 1000);
There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.
Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.
You could also solve this by saving and comparing times.
EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.
An interesting collection library is https://github.com/mgesmundo/smart-collection. Allows you to watch arrays and add views to them as well. Not sure about the performance as I am testing it out myself. Will update this post soon.
After struggling with this thing for WAY too long, here is the super easy solution.
My controller was looking for
@RequestBody List<String> ids
and I had the request body as
{
"ids": [
"1234",
"5678"
]
}
and the solution was to change the body simply to
["1234", "5678"]
Yup. Just that easy.
JavaScript
var el= document.querySelector('body');
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));
function isEmptyTag(tag) {
return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
//return (tag.childElementCount !== 0) ? true : false ; // Not For IE
//return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
return (tag.children.length !== 0) ? true : false ; // Only Elements
}
try using any of this!
document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];
document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
?
I had to modify this slightly to be used on a Windows System. Here's the one-liner version for a windows box.
openssl.exe s_client -connect yoursitename.com:443 > CertInfo.txt && openssl x509 -text -in CertInfo.txt | find "Signature Algorithm" && del CertInfo.txt /F
Tested on Server 2012 R2 using http://iweb.dl.sourceforge.net/project/gnuwin32/openssl/0.9.8h-1/openssl-0.9.8h-1-bin.zip
I've been trying to get my ASP.NET MVC controller to parse some model that i submitted to it using Postman.
I needed the following to get it to work:
controller action
[HttpPost]
[PermitAllUsers]
[Route("Models")]
public JsonResult InsertOrUpdateModels(Model entities)
{
// ...
return Json(response, JsonRequestBehavior.AllowGet);
}
a Models class
public class Model
{
public string Test { get; set; }
// ...
}
headers for Postman's request, specifically, Content-Type
json in the request body
I just want to add my solution:
I use german umlauts like ö, ü, ä and got the same error.
@Jarek Zmudzinski just told you how it works, but here is mine:
Add this code to the top of your Controller: # encoding: UTF-8
(for example to use flash message with umlauts)
example of my Controller:
# encoding: UTF-8
class UserController < ApplicationController
Now you can use ö, ä ,ü, ß, "", etc.
There is a default text editor that will be used when Git needs you to type in a message. By default, Git uses your system’s default editor, which is generally Vi or Vim. In your case, it is Vim that Git has chosen. See How do I make Git use the editor of my choice for commits? for details of how to choose another editor. Meanwhile...
You'll want to enter a message before you leave Vim:
...will start a new line for you to type in.
To exit (g)Vim type:
It's worth getting to know Vim, as you can use it for editing text on almost any platform. I recommend the Vim Tutor
, I used it many years ago and have never looked back (barely a day goes by when I don't use Vim).
Here is the C++ way of doing it. Have tried to keep the algorithm as much easy as possible to understand:
// Assuming that `BinaryNode_t` has `getData()`, `getLeft()` and `getRight()`
class LowestCommonAncestor
{
typedef char type;
// Data members which would behave as place holders
const BinaryNode_t* m_pLCA;
type m_Node1, m_Node2;
static const unsigned int TOTAL_NODES = 2;
// The core function which actually finds the LCA; It returns the number of nodes found
// At any point of time if the number of nodes found are 2, then it updates the `m_pLCA` and once updated, we have found it!
unsigned int Search (const BinaryNode_t* const pNode)
{
if(pNode == 0)
return 0;
unsigned int found = 0;
found += (pNode->getData() == m_Node1);
found += (pNode->getData() == m_Node2);
found += Search(pNode->getLeft()); // below condition can be after this as well
found += Search(pNode->getRight());
if(found == TOTAL_NODES && m_pLCA == 0)
m_pLCA = pNode; // found !
return found;
}
public:
// Interface method which will be called externally by the client
const BinaryNode_t* Search (const BinaryNode_t* const pHead,
const type node1,
const type node2)
{
// Initialize the data members of the class
m_Node1 = node1;
m_Node2 = node2;
m_pLCA = 0;
// Find the LCA, populate to `m_pLCANode` and return
(void) Search(pHead);
return m_pLCA;
}
};
How to use it:
LowestCommonAncestor lca;
BinaryNode_t* pNode = lca.Search(pWhateverBinaryTreeNodeToBeginWith);
if(pNode != 0)
...
With ES6, you may deconstruct each object to create new one without named attributes:
const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html
but currently attr and prop are not so different and there are almost the same
but they prefer prop for some things
Summary of Preferred Usage
The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.
well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)
using (StreamWriter w = File.AppendText("myFile.txt"))
{
w.WriteLine("hello");
}
Use a backslash:
echo "\"" # Prints one " character.
You can include a different jade file into your template, that to from a different directory
views/
layout.jade
static/
page.jade
To include the layout file from views dir to static/page.jade
page.jade
extends ../views/layout
Yate (https://github.com/pasaran/yate) is specifically designed after XSLT, features JPath (a natural XPath equivalent for JS), compiles to JavaScript and has quite a history of production use. It’s practically undocumented, but reading through samples and tests should be enough.
If you don't want to modify the dataframe, you could use a custom formatter for that column.
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print df.to_string(formatters={'cost':'${:,.2f}'.format})
yields
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
There was a time when adding strings into an array and finalising the string by using join
was the fastest/best method. These days browsers have highly optimised string routines and it is recommended that +
and +=
methods are fastest/best
I hope this answer helps:
SELECT (CAST(id AS NVARCHAR)+','+name) AS COMBINED_COLUMN FROM TABLENAME;
When you install third-party extensions you need to make sure that all the compilation parameters match:
Common glitches includes:
php.ini
file (that's typical with bundles); the right path is shown in phpinfo()
.Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:
php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
If everything's right you should see sqlsrv
in the command output and/or phpinfo()
(depending on what SAPI you're configuring):
[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]
[int(i) for i in str(number)]
or, if do not want to use a list comprehension or you want to use a base different from 10
from __future__ import division # for compatibility of // between Python 2 and 3
def digits(number, base=10):
assert number >= 0
if number == 0:
return [0]
l = []
while number > 0:
l.append(number % base)
number = number // base
return l
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!
For this to work you need to:
1) login with the ajax request from which you expect cookies to be returned:
$.ajax("https://example.com/v2/login", {
method: 'POST',
data: {login_id: user, password: password},
crossDomain: true,
success: login_success,
error: login_error
});
2) Connect with xhrFields: { withCredentials: true }
in the next ajax request(s) to use the credentials saved by the browser
$.ajax("https://example.com/v2/whatever", {
method: 'GET',
xhrFields: { withCredentials: true },
crossDomain: true,
success: whatever_success,
error: whatever_error
});
The browser takes care of these cookies for you even though they are not readable from the headers
nor the document.cookie
TortoiseSVN contains a console svn client, but by default the corresponding option is not enabled during installation.
The svn.exe
executable is not standalone and it depends on some other files in the distribution but this should not be a problem in most cases.
Once installed you might need to add the folder containing svn.exe
to the system PATH
as described here so that it is available in your console. To check if it was already added by the installer open a new console and type echo %PATH%
. Use set
on its own to see all environmental variables.
It's rather simple. Private setters allow you to create read-only public or protected properties.
That's it. That's the only reason.
Yes, you can create a read-only property by only specifying the getter, but with auto-implmeneted properties you are required to specify both get and set, so if you want an auto-implemented property to be read-only, you must use private setters. There is no other way to do it.
It's true that Private setters were not created specificlly for auto-implemented read-only properties, but their use is a bit more esoteric for other reasons, largely centering around read-only properties and the use of reflection and serialization.
use \r\n
combination to append a new line in node js
var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
stream.once('open', function(fd) {
stream.write(msg+"\r\n");
});
The function itself looks fine to me. The problem could be that you aren't allocating enough space for your string to pad that many characters onto it. You could avoid this problem in the future by passing a size_of_string
argument to the function and make sure you don't pad the string when the length is about to be greater than the size.
1. Authorization
You have received access data like this:
Username: johndoe
Password: zznAQOoWyj8uuAgq
Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa
Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga
Which you can call in cURL like this:
curl -k -d "grant_type=password&username=Username&password=Password" \
-H "Authorization: Basic Base64(consumer-key:consumer-secret)" \
https://somedomain.test.com/token
or for this case it would be:
curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \
-H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \
https://somedomain.test.com/token
Answer would be something like:
{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
2. Calling API
Here is how you call some API that uses authentication from above. Limit
and offset
are just examples of 2 parameters that API could implement.
You need access_token
from above inserted after "Bearer "
.So here is how you call some API with authentication data from above:
curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"
Same thing from above implemented in Python. I've put text in comments so code could be copy-pasted.
# Authorization data
import base64
import requests
username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()
# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh
headersAuth = {
'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}
data = {
'grant_type': 'password',
'username': username,
'password': password
}
## Authentication request
response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()
# When you print that response you will get dictionary like this:
{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].
# Using authentication to make API calls
## Define header for making API calls that will hold authentication data
headersAPI = {
'accept': 'application/json',
'Authorization': 'Bearer '+j['access_token'],
}
### Usage of parameters defined in your API
params = (
('offset', '0'),
('limit', '20'),
)
# Making sample API call with authentication and API parameters data
response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()
Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.
The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:
e.g., given:
{
"store":
{
"book":
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle":
{
"color": "red",
"price": 19.95
}
}
}
And the expression: $.store.book[?(@.length-1)].title
, the tool returns a list of all titles.
I encountered this problem on my laptop. I found the solution for this problem.
Then do this
You forgot to put z as an bind variable.
The following EXECUTE command runs a PL/SQL statement that references a stored procedure:
SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')
Note that the value returned by the stored procedure is being return into :Z
Running python -h
, I see a command line option:
-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'
Here is the relevant doc.
Even simpler, use _.values
from underscore.js
https://underscorejs.org/#values
If you are interested in the mouse entering or leaving one of your components you can use the @HostListener
decorator:
import { Component, HostListener, OnInit } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {
@HostListener('mouseenter')
onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave')
onMouseLeave() {
this.highlight(null);
}
...
}
As explained in the link in @Brandon comment to OP (https://angular.io/docs/ts/latest/guide/attribute-directives.html)