If you really want to avoid putting something with a name (either an iteration variable as in the OP, or unwanted list or unwanted generator returning true the wanted amount of time) you could do it if you really wanted:
for type('', (), {}).x in range(somenumber):
dosomething()
The trick that's used is to create an anonymous class type('', (), {})
which results in a class with empty name, but NB that it is not inserted in the local or global namespace (even if a nonempty name was supplied). Then you use a member of that class as iteration variable which is unreachable since the class it's a member of is unreachable.
Later than my previous answer, but may be useful anyway; while gRaphaël Charting may be an outdated alternative, a more recent and nicer option may be http://chartjs.org - still without any Flash, with a MIT license, and a recently updated GitHub.
I've been using it myself since my last answer, so now I have some web apps with one and some with the other.
If you are starting a project anew, try with Chart.js first.
Yes just add the setters/getters with public modifier ;)
Swift will not allow you to initialise super class with out initialising the properties, reverse of Obj C. So you have to initialise all properties before calling "super.init".
Please go to http://blog.scottlogic.com/2014/11/20/swift-initialisation.html. It gives a nice explanation to your problem.
This function handels "HH:MM:SS" as well as "MM:SS" or "SS".
function hmsToSecondsOnly(str) {
var p = str.split(':'),
s = 0, m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
return s;
}
There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();
Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:
th:text="${'static_content - ' + you_variable}"
Check this cool version out. The idea is to implement both String and ErrorType protocols and use the error's rawValue.
enum UserValidationError: String, Error {
case noFirstNameProvided = "Please insert your first name."
case noLastNameProvided = "Please insert your last name."
case noAgeProvided = "Please insert your age."
case noEmailProvided = "Please insert your email."
}
Usage:
do {
try User.define(firstName,
lastName: lastName,
age: age,
email: email,
gender: gender,
location: location,
phone: phone)
}
catch let error as User.UserValidationError {
print(error.rawValue)
return
}
I had similar Issue where we have GenericResponse object containing list of values
ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
redisMatchedDriverUrl,
HttpMethod.POST,
requestEntity,
ResponseDTO.class
);
Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects
ObjectMapper mapper = new ObjectMapper();
List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });
For Jackson 2+ (com.fasterxml.jackson
), the methods are little bit different:
Iterator<Entry<String, JsonNode>> nodes = rootNode.get("foo").fields();
while (nodes.hasNext()) {
Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodes.next();
logger.info("key --> " + entry.getKey() + " value-->" + entry.getValue());
}
jQuery 3.0 removed .error
. Correct syntax is now
$(this).on('error', function(){
console.log('Image does not exist: ' + this.id);
});
The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)
QObject(self.pb, SIGNAL("clicked()"), self.button_clicked) def button_clicked(self): self.le.setText("shost")
I think this is what you want. I hope i got your question correctly :)
Swift 3: Chage ViewController withOut Segue and send AnyObject Use: Identity MainPageViewController on target ViewController
let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController") as! MainPageViewController
var mainPageNav = UINavigationController(rootViewController: mainPage)
self.present(mainPageNav, animated: true, completion: nil)
or if you want to Change View Controller and send Data
let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "MainPageViewController") as! MainPageViewController
let dataToSend = "**Any String**" or var ObjectToSend:**AnyObject**
mainPage.getData = dataToSend
var mainPageNav = UINavigationController(rootViewController: mainPage)
self.present(mainPageNav, animated: true, completion: nil)
A definition from another perspective:
Apache Camel is an integration framework. It consists of some Java libraries, which helps you implementing integration problems on the Java platform. What this means and how it differs from APIs on the one side and an Enterprise Service Bus (ESB) on the other side is described in my article "When to use Apache Camel".
I had the same issue using webpack4, i was missing the file .babelrc in the root folder:
{
"presets":["env", "react"],
"plugins": [
"syntax-dynamic-import"
]
}
From package.json :
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
Maybe check Hibernate Validator 4.0, the Reference Implementation of the JSR 303: Bean Validation.
This is an example of an annotated class:
public class Address {
@NotNull
private String line1;
private String line2;
private String zip;
private String state;
@Length(max = 20)
@NotNull
private String country;
@Range(min = -2, max = 50, message = "Floor out of range")
public int floor;
...
}
For an introduction, see Getting started with JSR 303 (Bean Validation) – part 1 and part 2 or the "Getting started" section of the reference guide which is part of the Hibernate Validator distribution.
An improvement on the top answer for the following reasons:
Code should be as self-explanatory as possible.
Enumerating over an array using for...in... should be avoided.
for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As JavaScript is loosely typed and the for...in... can be handed any arbitrary object to handle; it's safer to validate the property we're looking for is available.
var os = require('os'),
interfaces = os.networkInterfaces(),
address,
addresses = [],
i,
l,
interfaceId,
interfaceArray;
for (interfaceId in interfaces) {
if (interfaces.hasOwnProperty(interfaceId)) {
interfaceArray = interfaces[interfaceId];
l = interfaceArray.length;
for (i = 0; i < l; i += 1) {
address = interfaceArray[i];
if (address.family === 'IPv4' && !address.internal) {
addresses.push(address.address);
}
}
}
}
console.log(addresses);
What you are getting is the result of the toString() method of the Object class or, more precisely, the identityHashCode() as uzay95 has pointed out.
"When we create an object in java with new keyword, we are getting a memory address from the OS."
It is important to realize that everything you do in Java is handled by the Java Virtual Machine. It is the JVM that is giving this information. What actually happens in the RAM of the host operating system depends entirely on the implementation of the JRE.
Keep a look out for SQL Server to support the 'INSERT ALL' Statement. Oracle has it already, it looks like this (SQL Cookbook):
insert all
when loc in ('NEW YORK', 'BOSTON') THEN
into dept_east(deptno, dname, loc) values(deptno, dname, loc)
when loc in ('CHICAGO') THEN
into dept_mid(deptno, dname, loc) values(deptno, dname, loc)
else
into dept_west(deptno, dname, loc) values(deptno, dname, loc)
select deptno, dname, loc
from dept
On top of everything that's been said (
https://stackoverflow.com/a/4416666/172109
),
which is correct, TFS isn't just a VCS. One major feature that TFS provides is natively integrated bug tracking functionality. Changesets are linked to issues and could be tracked. Various policies for check-ins are supported, as well as integration with Windows domain, which is what people who run TFS have. Tightly integrated GUI with Visual Studio is another selling point, which appeals to less than average mouse and click developer and his manager.
Hence comparing Git to TFS isn't a proper question to ask. Correct, though impractical, question is to compare Git with just VCS functionality of TFS. At that, Git blows TFS out of the water. However, any serious team needs other tools and this is where TFS provides one stop destination.
As you see, that's actually a natural error ..
A typical construct for reading from an Unpickler object would be like this ..
try:
data = unpickler.load()
except EOFError:
data = list() # or whatever you want
EOFError is simply raised, because it was reading an empty file, it just meant End of File ..
Append adds the entire data at once. The whole data will be added to the newly created index. On the other hand, extend
, as it name suggests, extends the current array.
For example
list1 = [123, 456, 678]
list2 = [111, 222]
With append
we get:
result = [123, 456, 678, [111, 222]]
While on extend
we get:
result = [123, 456, 678, 111, 222]
None of the above worked for me. My app was working fine in previous than Lollipop. But when I tested it on Lollipop the above error came up. It refused to install. I didn't have any previous versions installed so all the above solutions are invalid in my case. But thanks to this SO solution now it is running fine. Just like most developers I followed Google's misleading tutorial and I added the permissions by copy and paste like this:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.google.android.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
This would work with older versions < Lollipop. So now I changed to:
<uses-permission android:name="com.mycompany.myappname.c2dm.permission.RECEIVE" />
<permission android:name="com.mycompany.myappname.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
This is actually coming very late, but I thought I should share,
in index.html
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
in 1.js
fn1 = function() {
alert("external fn clicked");
}
in 2.js
fn1()
Yes, a static class can have static constructor, and the use of this constructor is initialization of static member.
static class Employee1
{
static int EmpNo;
static Employee1()
{
EmpNo = 10;
// perform initialization here
}
public static void Add()
{
}
public static void Add1()
{
}
}
and static constructor get called only once when you have access any type member of static class with class name Class1
Suppose you are accessing the first EmployeeName field then constructor get called this time, after that it will not get called, even if you will access same type member.
Employee1.EmployeeName = "kumod";
Employee1.Add();
Employee1.Add();
Fun fact,
You can use *
to check array membership in a case
expressions.
case element
when *array
...
else
...
end
Notice the little *
in the when clause, this checks for membership in the array.
All the usual magic behavior of the splat operator applies, so for example if array
is not actually an array but a single element it will match that element.
You need the return so the true/false gets passed up to the form's submit event (which looks for this and prevents submission if it gets a false).
Lets look at some standard JS:
function testReturn() { return false; }
If you just call that within any other code (be it an onclick handler or in JS elsewhere) it will get back false, but you need to do something with that value.
...
testReturn()
...
In that example the return value is coming back, but nothing is happening with it. You're basically saying execute this function, and I don't care what it returns. In contrast if you do this:
...
var wasSuccessful = testReturn();
...
then you've done something with the return value.
The same applies to onclick handlers. If you just call the function without the return in the onsubmit, then you're saying "execute this, but don't prevent the event if it return false." It's a way of saying execute this code when the form is submitted, but don't let it stop the event.
Once you add the return, you're saying that what you're calling should determine if the event (submit) should continue.
This logic applies to many of the onXXXX events in HTML (onclick, onsubmit, onfocus, etc).
Got to this question because I was looking for a way to select multiple words with mouse click on VS Code, which should be achieved by using alt+click
, but this keybinding wasn't working (I think it is something related to my OS, Ubuntu).
For anyone looking for something similar, try changing the key to ctrl+click
.
Go to Selection
> Switch to Ctrl+Click for Multi Cursor
If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.
Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.
Even without importing swing, you can get the call in one, all be it long, string. Otherwise just use the swing import and simple call:
JOptionPane.showMessageDialog(null, "Thank you for using Java", "Yay, java", JOptionPane.PLAIN_MESSAGE);
Easy enough.
In the current version of Web API, the usage of multiple complex objects (like your Content
and Config
complex objects) within the Web API method signature is not allowed. I'm betting good money that config
(your second parameter) is always coming back as NULL. This is because only one complex object can be parsed from the body for one request. For performance reasons, the Web API request body is only allowed to be accessed and parsed once. So after the scan and parsing occurs of the request body for the "content" parameter, all subsequent body parses will end in "NULL". So basically:
[FromBody]
.[FromUri]
.Below is a useful extract from Mike Stall's excellent blog article (oldie but goldie!). You'll want to pay attention to item 4:
Here are the basic rules to determine whether a parameter is read with model binding or a formatter:
- If the parameter has no attribute on it, then the decision is made purely on the parameter's .NET type. "Simple types" use model binding. Complex types use the formatters. A "simple type" includes: primitives,
TimeSpan
,DateTime
,Guid
,Decimal
,String
, or something with aTypeConverter
that converts from strings.- You can use a
[FromBody]
attribute to specify that a parameter should be from the body.- You can use a
[ModelBinder]
attribute on the parameter or the parameter's type to specify that a parameter should be model bound. This attribute also lets you configure the model binder.[FromUri]
is a derived instance of[ModelBinder]
that specifically configures a model binder to only look in the URI.- The body can only be read once. So if you have 2 complex types in the signature, at least one of them must have a
[ModelBinder]
attribute on it.It was a key design goal for these rules to be static and predictable.
A key difference between MVC and Web API is that MVC buffers the content (e.g. request body). This means that MVC's parameter binding can repeatedly search through the body to look for pieces of the parameters. Whereas in Web API, the request body (an
HttpContent
) may be a read-only, infinite, non-buffered, non-rewindable stream.
You can read the rest of this incredibly useful article on your own so, to cut a long story short, what you're trying to do is not currently possible in that way (meaning, you have to get creative). What follows is not a solution, but a workaround and only one possibility; there are other ways.
(Disclaimer: I've not used it myself, I'm just aware of the theory!)
One possible "solution" is to use the JObject
object. This objects provides a concrete type specifically designed for working with JSON.
You simply need to adjust the signature to accept just one complex object from the body, the JObject
, let's call it stuff
. Then, you manually need to parse properties of the JSON object and use generics to hydrate the concrete types.
For example, below is a quick'n'dirty example to give you an idea:
public void StartProcessiong([FromBody]JObject stuff)
{
// Extract your concrete objects from the json object.
var content = stuff["content"].ToObject<Content>();
var config = stuff["config"].ToObject<Config>();
. . . // Now do your thing!
}
I did say there are other ways, for example you can simply wrap your two objects in a super-object of your own creation and pass that to your action method. Or you can simply eliminate the need for two complex parameters in the request body by supplying one of them in the URI. Or ... well, you get the point.
Let me just reiterate I've not tried any of this myself, although it should all work in theory.
Had the same problem . Fixed it by installing Microsoft Foundation Classes for C++.
When you push to a remote and you use the --set-upstream
flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.
Adding a remote tracking branch means that git then knows what you want to do when you git fetch
, git pull
or git push
in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.
You could achieve the same thing with git branch --set-upstream-to
or git checkout --track
. See the git help pages on tracking branches for more information.
here is some code for more robust imcrop ( a bit like in matlab )
def imcrop(img, bbox):
x1,y1,x2,y2 = bbox
if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
return img[y1:y2, x1:x2, :]
def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
img = np.pad(img, ((np.abs(np.minimum(0, y1)), np.maximum(y2 - img.shape[0], 0)),
(np.abs(np.minimum(0, x1)), np.maximum(x2 - img.shape[1], 0)), (0,0)), mode="constant")
y1 += np.abs(np.minimum(0, y1))
y2 += np.abs(np.minimum(0, y1))
x1 += np.abs(np.minimum(0, x1))
x2 += np.abs(np.minimum(0, x1))
return img, x1, x2, y1, y2
This is the most foolproof way to get your rails app working with postgres in the development environment in Ubuntu 13.10.
1) Create rails app with postgres YAML and 'pg' gem in the Gemfile:
$ rails new my_application -d postgresql
2) Give it some CRUD functionality. If you're just seeing if postgres works, create a scaffold:
$ rails g scaffold cats name:string age:integer colour:string
3) As of rails 4.0.1
the -d postgresql
option generates a YAML that doesn't include a host parameter. I found I needed this. Edit the development section and create the following parameters:
encoding: UTF-8
host: localhost
database: my_application_development
username: thisismynewusername
password: thisismynewpassword
Note the database
parameter is for a database that doesn't exit yet, and the username
and password
are credentials for a role that doesn't exist either. We'll create those later on!
This is how config/database.yml
should look (no shame in copypasting :D ):
development:
adapter: postgresql
pool: 5
# these are our new parameters
encoding: UTF-8
database: my_application_development
host: localhost
username: thisismynewusername
password: thisismynewpassword
test:
# this won't work
adapter: postgresql
encoding: unicode
database: my_application_test
pool: 5
username: my_application
password:
production:
# this won't work
adapter: postgresql
encoding: unicode
database: my_application_production
pool: 5
username: my_application
password:
4) Start the postgres shell with this command:
$ psql
4a) You may get this error if your current user (as in your computer user) doesn't have a corresponding administration postgres role.
psql: FATAL: role "your_username" does not exist
Now I've only installed postgres once, so I may be wrong here, but I think postgres automatically creates an administration role with the same credentials as the user you installed postgres as.
4b) So this means you need to change to the user that installed postgres to use the psql command and start the shell:
$ sudo su postgres
And then run
$ psql
5) You'll know you're in the postgres shell because your terminal will look like this:
$ psql
psql (9.1.10)
Type "help" for help.
postgres=#
6) Using the postgresql syntax, let's create the user we specified in config/database.yml
's development section:
postgres=# CREATE ROLE thisismynewusername WITH LOGIN PASSWORD 'thisismynewpassword';
Now, there's some subtleties here so let's go over them.
You should see this in your terminal:
postgres=#
CREATE ROLE
postgres=#
That means, "ROLE CREATED", but postgres' alerts seem to adopt the same imperative conventions of git hub.
7) Now, still in the postgres shell, we need to create the database with the name we set in the YAML. Make the user we created in step 6 its owner:
postgres=# CREATE DATABASE my_application_development OWNER thisismynewusername;
You'll know if you were successful because you'll get the output:
CREATE DATABASE
8) Quit the postgres shell:
\q
9) Now the moment of truth:
$ RAILS_ENV=development rake db:migrate
If you get this:
== CreateCats: migrating =================================================
-- create_table(:cats)
-> 0.0028s
== CreateCats: migrated (0.0028s) ========================================
Congratulations, postgres is working perfectly with your app.
9a) On my local machine, I kept getting a permission error. I can't remember it exactly, but it was an error along the lines of
Can't access the files. Change permissions to 666.
Though I'd advise thinking very carefully about recursively setting write privaledges on a production machine, locally, I gave my whole app read write privileges like this:
9b) Climb up one directory level:
$ cd ..
9c) Set the permissions of the my_application directory and all its contents to 666:
$ chmod -R 0666 my_application
9d) And run the migration again:
$ RAILS_ENV=development rake db:migrate
== CreateCats: migrating =================================================
-- create_table(:cats)
-> 0.0028s
== CreateCats: migrated (0.0028s) ========================================
Some tips and tricks if you muck up
Try these before restarting all of these steps:
The mynewusername user doesn't have privileges to CRUD to the my_app_development
database? Drop the database and create it again with mynewusername as the owner:
1) Start the postgres shell:
$ psql
2) Drop the my_app_development
database. Be careful! Drop means utterly delete!
postgres=# DROP DATABASE my_app_development;
3) Recreate another my_app_development
and make mynewusername the owner:
postgres=# CREATE DATABASE my_application_development OWNER mynewusername;
4) Quit the shell:
postgres=# \q
The mynewusername
user can't log into the database? Think you wrote the wrong password in the YAML and can't quite remember the password you entered using the postgres shell? Simply alter the role with the YAML password:
1) Open up your YAML, and copy the password to your clipboard:
development:
adapter: postgresql
pool: 5
# these are our new parameters
encoding: UTF-8
database: my_application_development
host: localhost
username: thisismynewusername
password: musthavebeenverydrunkwheniwrotethis
2) Start the postgres shell:
$ psql
3) Update mynewusername
's password. Paste in the password, and remember to put single quotes around it:
postgres=# ALTER ROLE mynewusername PASSWORD `musthavebeenverydrunkwheniwrotethis`;
4) Quit the shell:
postgres=# \q
Trying to connect to localhost via a database viewer such as Dbeaver, and don't know what your postgres user's password is? Change it like this:
1) Run passwd
as a superuser:
$ sudo passwd postgres
2) Enter your accounts password for sudo
(nothing to do with postgres):
[sudo] password for starkers: myaccountpassword
3) Create the postgres account's new passwod:
Enter new UNIX password: databasesarefun
Retype new UNIX password: databasesarefun
passwd: password updated successfully
Getting this error message?:
Run `$ bin/rake db:create db:migrate` to create your database
$ rake db:create db:migrate
PG::InsufficientPrivilege: ERROR: permission denied to create database
4) You need to give your user the ability to create databases. From the psql shell:
ALTER ROLE thisismynewusername WITH CREATEDB
To list files based on size in asending order.
find ./ -size +1000M -exec ls -tlrh {} \; |awk -F" " '{print $5,$9}' | sort -n\
@vnr you can retrieve all the sort keys associated with a partition key by just using the query using partion key. No need of scan. The point here is partition key is compulsory in a query . Sort key are used only to get range of data
DeZign for Databases should be able to do this just fine.
Strings in Python are immutable meaning you cannot replace parts of them.
You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.
You could for instance write a function:
def replace_str_index(text,index=0,replacement=''):
return '%s%s%s'%(text[:index],replacement,text[index+1:])
And then for instance call it with:
new_string = replace_str_index(old_string,middle)
If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.
For instance:
replace_str_index('hello?bye',5)
will return 'hellobye'
; and:
replace_str_index('hello?bye',5,'good')
will return 'hellogoodbye'
.
You should be able to adjust the width using the .modal-dialog
class selector (in conjunction with media queries or whatever strategy you're using for responsive design):
.modal-dialog {
width: 400px;
}
Try this...
if(string1.toLowerCase() == string2.toLowerCase()){
return true;
}
Also, it's not a loop, it's a block of code. Loops are generally repeated (although they can possibly execute only once), whereas a block of code never repeats.
I read your note about not using toLowerCase, but can't see why it would be a problem.
Working Example to Put Your File on Root ...........see its very simple
#!/bin/sh
HOST='ftp.users.qwest.net'
USER='yourid'
PASSWD='yourpw'
FILE='file.txt'
ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
put $FILE
quit
END_SCRIPT
exit 0
On Mavericks, this script helped me:
bash <(curl -Ls http://git.io/eUx7rg)
And then I reset my password according with https://stackoverflow.com/a/25883967/221781
For anyone who comes across this issue in the future, I had to add
perspective: 1px;
to the element that I was applying the border radius to. Final working code:
.ele-with-border-radius {
border-radius: 15px;
overflow: hidden;
perspective: 1px;
}
I'm late but I need to say for those who need an object, using only html, there's a way. In some server side frameworks like PHP you can write the follow code:
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="name[first]" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="name[last]" id="lname"></p>
<input value="Submit" type="submit">
</form>
So, we need setup the name of the input as object[property]
for got an object. In the above example, we got a data with the follow JSON:
{
"name": {
"first": "some data",
"last": "some data"
}
}
You could also check using the age()
function
select * from mytable where age( mydate, now() ) > '1 year';
age()
wil return an interval.
For example age( '2015-09-22', now() )
will return -1 years -7 days -10:56:18.274131
Implementing window.onbeforeprint and window.onafterprint
The window.close() call after the window.print() is not working in Chrome v 78.0.3904.70
To approach this I'm using Adam's answer with a simple modification:
function print() {
(function () {
let afterPrintCounter = !!window.chrome ? 0 : 1;
let beforePrintCounter = !!window.chrome ? 0 : 1;
var beforePrint = function () {
beforePrintCounter++;
if (beforePrintCounter === 2) {
console.log('Functionality to run before printing.');
}
};
var afterPrint = function () {
afterPrintCounter++;
if (afterPrintCounter === 2) {
console.log('Functionality to run after printing.');
//window.close();
}
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
//window.print(); //To print the page when it is loaded
}
I'm calling it in here:
<body onload="print();">
This works for me. Note that I use a counter for both functions, so that I can handle this event in different browsers (fires twice in Chrome, and one time in Mozilla). For detecting the browser you can refer to this answer
next(iter(your_list), None)
If your_list
can be None
:
next(iter(your_list or []), None)
def get_first(iterable, default=None):
if iterable:
for item in iterable:
return item
return default
Example:
x = get_first(get_first_list())
if x:
...
y = get_first(get_second_list())
if y:
...
Another option is to inline the above function:
for x in get_first_list() or []:
# process x
break # process at most one item
for y in get_second_list() or []:
# process y
break
To avoid break
you could write:
for x in yield_first(get_first_list()):
x # process x
for y in yield_first(get_second_list()):
y # process y
Where:
def yield_first(iterable):
for item in iterable or []:
yield item
return
A common misunderstanding among starters is that they think that the call of a forward()
, sendRedirect()
, or sendError()
would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:
protected void doXxx() {
if (someCondition) {
sendRedirect();
}
forward(); // This is STILL invoked when someCondition is true!
}
This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit()
of course). When the someCondition
in above example is true
and you're thus calling forward()
after sendRedirect()
or sendError()
on the same request/response, then the chance is big that you will get the exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
If the if
statement calls a forward()
and you're afterwards calling sendRedirect()
or sendError()
, then below exception will be thrown:
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
To fix this, you need either to add a return;
statement afterwards
protected void doXxx() {
if (someCondition) {
sendRedirect();
return;
}
forward();
}
... or to introduce an else block.
protected void doXxx() {
if (someCondition) {
sendRedirect();
} else {
forward();
}
}
To naildown the root cause in your code, just search for any line which calls a forward()
, sendRedirect()
or sendError()
without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.
In case of sendError()
, if your sole purpose is to set the response status, use setStatus()
instead.
Another probable cause is that the servlet writes to the response while a forward()
will be called, or has been called in the very same method.
protected void doXxx() {
out.write("some string");
// ...
forward(); // Fail!
}
The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward()
will fail the same way:
java.lang.IllegalStateException: Cannot forward after response has been committed
Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string")
and then print it in JSP like so ${data}
. See also our Servlets wiki page to learn how to use Servlets the right way.
Another probable cause is that the servlet writes a file download to the response after which e.g. a forward()
is called.
protected void doXxx() {
out.write(bytes);
// ...
forward(); // Fail!
}
This is technically not possible. You need to remove the forward()
call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page.
Yet another probable cause is that the forward()
, sendRedirect()
or sendError()
methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>
, a practice which was officially discouraged since 2001. For example:
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
<% sendRedirect(); %>
...
</body>
</html>
The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...")
as soon as it's encountered. This is thus essentially the same problem as explained in previous section.
Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.
Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?
Try this:
#include <stdio.h>
#include <unistd.h>
#include <string.h> /* for strncpy */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
int
main()
{
int fd;
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;
/* I want IP address attached to "eth0" */
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
/* display result */
printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
return 0;
}
The code sample is taken from here.
If you are working with RelativeLayout
, try using this property inside your TextView
tag :
android:layout_centerInParent= true
Dictionary:
dict = {'a':'a','b':'b','c':'c'}
array of dictionary
arr = (dict,dict,dict)
arr
({'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'})
You might also try fixing the hosts file.
Keep the vhost file with the fully qualified domain and add the hostname in the hosts file /etc/hosts (debian)
ip.ip.ip.ip name name.domain.com
After restarting apache2, the error should be gone.
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence in order to be done correctly.
In computer memory or storage, a race condition may occur if commands to read and write a large amount of data are received at almost the same instant, and the machine attempts to overwrite some or all of the old data while that old data is still being read. The result may be one or more of the following: a computer crash, an "illegal operation," notification and shutdown of the program, errors reading the old data, or errors writing the new data.
In this way we can make it use the values to the pass the information between the controller to other page with TEMP DATA
Use this one to change only font size not the name of the font
label1.Font = new System.Drawing.Font(label1.Font.Name, 24F);
See the docs about querying.
It would be:
$or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)
TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
rowTextView.setText(text);
layout.addView(rowTextView);
This is how I'm using this:
private List<Tag> tags = new ArrayList<>();
if(tags.isEmpty()){
Gson gson = new Gson();
Type listType = new TypeToken<List<Tag>>() {
}.getType();
tags = gson.fromJson(tour.getTagsJSONArray(), listType);
}
if (flowLayout != null) {
if(!tags.isEmpty()) {
Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
flowLayout.removeAllViews();
for (Tag tag : tags) {
FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
rowTextView.setText(tag.getLabel());
rowTextView.setLayoutParams(lparams);
flowLayout.addView(rowTextView);
}
}
Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
}
And this is my custom TextView named tag:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textAllCaps="true"
fontPath="@string/font_light"
android:background="@drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">
this is my tag_shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>
efect:
In other place I'm adding textviews with language names from dialog with listview:
You can limit the number of files uploaded by changing in dropezone.js
Dropzone.prototype.defaultOptions = { maxFiles: 10, }
Use SET STATISTICS TIME ON
above your query.
Below near result tab you can see a message tab. There you can see the time.
To take 6footunder's comment and turn it into an answer, HttpContent
is abstract so you need to use one of the derived classes:
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
You can also make use of FilesystemIterator
. It requires even less code then DirectoryIterator
, and automatically removes .
and ..
.
// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');
$entries = array();
foreach ($fileSystemIterator as $fileInfo){
$entries[] = $fileInfo->getFilename();
}
var_dump($entries);
//OUTPUT
object(FilesystemIterator)[1]
array (size=14)
0 => string 'aa[1].jpg' (length=9)
1 => string 'Chrysanthemum.jpg' (length=17)
2 => string 'Desert.jpg' (length=10)
3 => string 'giphy_billclinton_sad.gif' (length=25)
4 => string 'giphy_shut_your.gif' (length=19)
5 => string 'Hydrangeas.jpg' (length=14)
6 => string 'Jellyfish.jpg' (length=13)
7 => string 'Koala.jpg' (length=9)
8 => string 'Lighthouse.jpg' (length=14)
9 => string 'Penguins.jpg' (length=12)
10 => string 'pnggrad16rgb.png' (length=16)
11 => string 'pnggrad16rgba.png' (length=17)
12 => string 'pnggradHDrgba.png' (length=17)
13 => string 'Tulips.jpg' (length=10)
The table names are case-sensitive so you should use lower-case nat instead of upper-case NAT. For example;
iptables -t nat -A POSTROUTING -s 192.168.1.1/24 -o eth0 -j MASQUERADE
Blowfish is not a hashing algorithm. It's an encryption algorithm. What that means is that you can encrypt something using blowfish, and then later on you can decrypt it back to plain text.
SHA512 is a hashing algorithm. That means that (in theory) once you hash the input you can't get the original input back again.
They're 2 different things, designed to be used for different tasks. There is no 'correct' answer to "is blowfish better than SHA512?" You might as well ask "are apples better than kangaroos?"
If you want to read some more on the topic here's some links:
Specify NR
if you want to capture output from selected rows:
awk 'NR==1{print $1}' /etc/*release
An alternative (ugly) way of achieving the same would be:
awk '{print $1; exit}'
An efficient way of getting the first string from a specific line, say line 42, in the output would be:
awk 'NR==42{print $1; exit}'
This whitelist approach (ie, allowing only the chars present in valid_chars) will work if there aren't limits on the formatting of the files or combination of valid chars that are illegal (like ".."), for example, what you say would allow a filename named " . txt" which I think is not valid on Windows. As this is the most simple approach I'd try to remove whitespace from the valid_chars and prepend a known valid string in case of error, any other approach will have to know about what is allowed where to cope with Windows file naming limitations and thus be a lot more complex.
>>> import string
>>> valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
>>> valid_chars
'-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
>>> filename = "This Is a (valid) - filename%$&$ .txt"
>>> ''.join(c for c in filename if c in valid_chars)
'This Is a (valid) - filename .txt'
In addition to previous answers, in case of you need to validate a JSON format like "{}", you can use the following code:
const validateJSON = (str) => {
try {
const json = JSON.parse(str);
if (Object.prototype.toString.call(json).slice(8,-1) !== 'Object') {
return false;
}
} catch (e) {
return false;
}
return true;
}
Examples of usage:
validateJSON('{}')
true
validateJSON('[]')
false
validateJSON('')
false
validateJSON('2134')
false
validateJSON('{ "Id": 1, "Name": "Coke" }')
true
You're right that the SD Card directory is /sdcard
but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory()
to get the directory:
File sdDir = Environment.getExternalStorageDirectory();
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Enter the command
which python
//output:
/usr/bin/python
cd /usr/bin
ls -l
Here you can see something like this
lrwxrwxrwx 1 root root 9 Mar 7 17:04 python -> python2.7
your default python2.7 is soft linked to the text 'python'
So remove the softlink python
sudo rm -r python
then retry the above command
ls -l
you can see the softlink is removed
-rwxr-xr-x 1 root root 3670448 Nov 12 20:01 python2.7
Then create a new softlink for python3.6
ln -s /usr/bin/python3.6 python
Then try the command python
in terminal
//output:
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type help
, copyright
, credits
or license
for more information.
As struct are value types and you can create the memory very easily which stores into stack.Struct can be easily accessible and after the scope of the work it's easily deallocated from the stack memory through pop from the top of the stack. On the other hand class is a reference type which stores in heap and changes made in one class object will impact to other object as they are tightly coupled and reference type.All members of a structure are public whereas all the members of a class are private.
The disadvantages of struct is that it can't be inherited .
var parent = context.Parent.FirstOrDefault(x => x.Id == modelParent.Id);
if (parent != null)
{
parent.Childs = modelParent.Childs;
}
I'm using Excel 2003 -
The problem with using conditional formatting here is that you can't reference another worksheet or workbook in your conditions. What you can to do is set some column on sheet 1 equal to the appropriate column on sheet 2 (in your example =Sheet2!B6). I used Column F in my example below. Then you can use conditional formatting. Select the cell at Sheet 1, row , column 1 and then go to the conditional formatting menu. Choose "Formula Is" from the drop down and set the condition to "=$F$6=4". Click on the format button and then choose the Patterns tab. Choose the color you want and you're done.
You can use the format painter tool to apply conditional formatting to other cells, but be aware that by default Excel uses absolute references in the conditions. If you want them to be relative you'll need to remove the dollar signs from the condition.
You can have up to 3 conditions applied to a cell (use the add >> button at the bottom of the Conditional formatting dialog) so if the last row is fixed (for example, you know that it will always be row 10) you can use it as a condition to set the background color to none. Assuming that the last value you care about is in row 10 then (still assuming that you've set column F on sheet1 to the corresponding cells on sheet 2) then set the 1st condition to Formula Is =$F$10="" and the pattern to None. Make it the first condition and it will override any following conflicting statements.
To keep the color and prevent an underline on the link:
legend.green-color a{
color:green;
text-decoration: none;
}
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
Yikes these answers aren't great, even the top post upticked. Here y'go, cross-browser and cleaner int/string conversion. Plus my advice is don't use a variable name 'date' with code like date = Date(...)
where you're relying heavily on language case sensitivity (it works, but risky when you're working with server/browser code in different languages with different rules). So assuming the javascript Date in a var current_date
:
mins = ('0'+current_date.getMinutes()).slice(-2);
The technique is take the rightmost 2 characters (slice(-2))
of "0" prepended onto the string value of getMinutes()
. So:
"0"+"12" -> "012".slice(-2) -> "12"
and
"0"+"1" -> "01".slice(-2) -> "01"
Important:
I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.
First remember below two rules:
Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL}
not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT}
- Protocol is an important part of a socket's definition.
OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.
Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP}
and socket2{SRC-B, 100, DEST-X,80, TCP}
. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.
To answer the original question of the post:
Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT
. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.
To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.
A bit more for completeness:
Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.
Server Types - single & multiple:
When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).
Suggested Books and rest of the two volumes if you can.
A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')
Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.
Changing the current directory of the script process is trivial. I think the question is actually how to change the current directory of the command window from which a python script is invoked, which is very difficult. A Bat script in Windows or a Bash script in a Bash shell can do this with an ordinary cd command because the shell itself is the interpreter. In both Windows and Linux Python is a program and no program can directly change its parent's environment. However the combination of a simple shell script with a Python script doing most of the hard stuff can achieve the desired result. For example, to make an extended cd command with traversal history for backward/forward/select revisit, I wrote a relatively complex Python script invoked by a simple bat script. The traversal list is stored in a file, with the target directory on the first line. When the python script returns, the bat script reads the first line of the file and makes it the argument to cd. The complete bat script (minus comments for brevity) is:
if _%1 == _. goto cdDone
if _%1 == _? goto help
if /i _%1 NEQ _-H goto doCd
:help
echo d.bat and dSup.py 2016.03.05. Extended chdir.
echo -C = clear traversal list.
echo -B or nothing = backward (to previous dir).
echo -F or - = forward (to next dir).
echo -R = remove current from list and return to previous.
echo -S = select from list.
echo -H, -h, ? = help.
echo . = make window title current directory.
echo Anything else = target directory.
goto done
:doCd
%~dp0dSup.py %1
for /F %%d in ( %~dp0dSupList ) do (
cd %%d
if errorlevel 1 ( %~dp0dSup.py -R )
goto cdDone
)
:cdDone
title %CD%
:done
The python script, dSup.py is:
import sys, os, msvcrt
def indexNoCase ( slist, s ) :
for idx in range( len( slist )) :
if slist[idx].upper() == s.upper() :
return idx
raise ValueError
# .........main process ...................
if len( sys.argv ) < 2 :
cmd = 1 # No argument defaults to -B, the most common operation
elif sys.argv[1][0] == '-':
if len(sys.argv[1]) == 1 :
cmd = 2 # '-' alone defaults to -F, second most common operation.
else :
cmd = 'CBFRS'.find( sys.argv[1][1:2].upper())
else :
cmd = -1
dir = os.path.abspath( sys.argv[1] ) + '\n'
# cmd is -1 = path, 0 = C, 1 = B, 2 = F, 3 = R, 4 = S
fo = open( os.path.dirname( sys.argv[0] ) + '\\dSupList', mode = 'a+t' )
fo.seek( 0 )
dlist = fo.readlines( -1 )
if len( dlist ) == 0 :
dlist.append( os.getcwd() + '\n' ) # Prime new directory list with current.
if cmd == 1 : # B: move backward, i.e. to previous
target = dlist.pop(0)
dlist.append( target )
elif cmd == 2 : # F: move forward, i.e. to next
target = dlist.pop( len( dlist ) - 1 )
dlist.insert( 0, target )
elif cmd == 3 : # R: remove current from list. This forces cd to previous, a
# desireable side-effect
dlist.pop( 0 )
elif cmd == 4 : # S: select from list
# The current directory (dlist[0]) is included essentially as ESC.
for idx in range( len( dlist )) :
print( '(' + str( idx ) + ')', dlist[ idx ][:-1])
while True :
inp = msvcrt.getche()
if inp.isdigit() :
inp = int( inp )
if inp < len( dlist ) :
print( '' ) # Print the newline we didn't get from getche.
break
print( ' is out of range' )
# Select 0 means the current directory and the list is not changed. Otherwise
# the selected directory is moved to the top of the list. This can be done by
# either rotating the whole list until the selection is at the head or pop it
# and insert it to 0. It isn't obvious which would be better for the user but
# since pop-insert is simpler, it is used.
if inp > 0 :
dlist.insert( 0, dlist.pop( inp ))
elif cmd == -1 : # -1: dir is the requested new directory.
# If it is already in the list then remove it before inserting it at the head.
# This takes care of both the common case of it having been recently visited
# and the less common case of user mistakenly requesting current, in which
# case it is already at the head. Deleting and putting it back is a trivial
# inefficiency.
try:
dlist.pop( indexNoCase( dlist, dir ))
except ValueError :
pass
dlist = dlist[:9] # Control list length by removing older dirs (should be
# no more than one).
dlist.insert( 0, dir )
fo.truncate( 0 )
if cmd != 0 : # C: clear the list
fo.writelines( dlist )
fo.close()
exit(0)
Install Homebrew first :
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then run this : brew install gdb
.fa-search{
color:#fff;
}
you write that code in css and it would change the color to white or any color you want, you specify it
Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Of course, you can run the program as java Hello
and you will see the message; however, the command will also fail with a message stating:
Exception in thread "main" java.lang.NoSuchMethodError: main
[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0)
immediately after printing the message.
As of JDK6 onward, you no longer see the message from the static
initializer block; details here.
How about something like this: http://jsfiddle.net/EgLKV/3/
Its done by using position:absolute
and z-index
to place the text over the image.
#container {_x000D_
height: 400px;_x000D_
width: 400px;_x000D_
position: relative;_x000D_
}_x000D_
#image {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
}_x000D_
#text {_x000D_
z-index: 100;_x000D_
position: absolute;_x000D_
color: white;_x000D_
font-size: 24px;_x000D_
font-weight: bold;_x000D_
left: 150px;_x000D_
top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
<img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
<p id="text">_x000D_
Hello World!_x000D_
</p>_x000D_
</div>
_x000D_
I cleaned my main App Project AND the Android Library Project which it uses. Solved the issue
Have the same problem with white screen during transition from one fragment to another. Have navigation and animations set in action in navigation.xml.
Background in all fragments the same but white blank screen. So i set navOptions in fragment during executing transition
//Transition options
val options = navOptions {
anim {
enter = R.anim.slide_in_right
exit = R.anim.slide_out_left
popEnter = R.anim.slide_in_left
popExit = R.anim.slide_out_right
}
}
.......................
this.findNavController().navigate(SampleFragmentDirections.actionSampleFragmentToChartFragment(it),
options)
It worked for me. No white screen between transistion. Magic )
Other alternatives for summing the columns are
numpy.einsum('ij->j', a)
and
numpy.dot(a.T, numpy.ones(a.shape[0]))
If the number of rows and columns is in the same order of magnitude, all of the possibilities are roughly equally fast:
If there are only a few columns, however, both the einsum
and the dot
solution significantly outperform numpy's sum
(note the log-scale):
Code to reproduce the plots:
import numpy
import perfplot
def numpy_sum(a):
return numpy.sum(a, axis=1)
def einsum(a):
return numpy.einsum('ij->i', a)
def dot_ones(a):
return numpy.dot(a, numpy.ones(a.shape[1]))
perfplot.save(
"out1.png",
# setup=lambda n: numpy.random.rand(n, n),
setup=lambda n: numpy.random.rand(n, 3),
n_range=[2**k for k in range(15)],
kernels=[numpy_sum, einsum, dot_ones],
logx=True,
logy=True,
xlabel='len(a)',
)
For people like me who get confused while using cmake
, the FindCUDA.cmake
script overrides some of the stuff from nvcc.profile
. You can specify the nvcc
host compiler by setting CUDA_HOST_COMPILER
as per http://public.kitware.com/Bug/view.php?id=13674.
m/ /g
just give space in / /
, and it will work. Or use \S
— it will replace all the special characters like tab, newlines, spaces, and so on.
In Linux:
1) find where is sqlplus located,
[oracle@LINUX db_1]$ `which sqlplus`
/app/oracle/product/11.2.0/db_1/bin/sqlplus
2) Determine the file type,
[oracle@LINUX db_1]$ file /app/oracle/product/11.2.0/db_1/bin/sqlplus
/app/oracle/product/11.2.0/db_1/bin/sqlplus: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs). For GNU/Linux 2.6.18, not stripped.
Use WEEKDAY()
instead of DAYOFWEEK()
, it begins on Monday.
If you need to start at index 1, use or WEEKDAY() + 1
.
There are two options:
This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.
As described in “Adding Images, Fonts, and Files”, you need to have a CSS file imported from JS. For example, by default src/index.js
imports src/index.css
:
import './index.css';
A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in src/fonts/MyFont.woff
, your index.css
might include this:
@font-face {
font-family: 'MyFont';
src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
}
Notice how we’re using a relative path starting with ./
. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.
Normally this should be enough.
public
FolderIf for some reason you prefer not to use the build pipeline, and instead do it the “classic way”, you can use the public
folder and put your fonts there.
The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.
If you want to do it this way, put the fonts somewhere into the public
folder, for example, into public/fonts/MyFont.woff
. If you follow this approach, you should put CSS files into public
folder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file like public/index.css
. You would have to manually add <link>
to this stylesheet from public/index.html
:
<link rel="stylesheet" href="%PUBLIC_URL%/index.css">
And inside of it, you would use the regular CSS notation:
@font-face {
font-family: 'MyFont';
src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}
Notice how I’m using fonts/MyFont.woff
as the path. This is because index.css
is in the public
folder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set your homepage
field to http://myuser.github.io/myproject
, it will be served from /myproject
). However fonts
are also in the public
folder, so they will be served from fonts
relatively (either http://mywebsite.com/fonts
or http://myuser.github.io/myproject/fonts
). Therefore we use the relative path.
Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our index.css
file doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.
Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.
The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.
Ruby prior to 1.9 had a TCP-based ping.rb
, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.
I am facing same issue and it's get resolved. At my end reason is i install node and CLI using other user profile and now i am running ng command from other user login. Since node and cli installed using other user login node is not finding anything on C:\Users\<user name>\AppData\Roaming
this path and that's why i am getting this error.
I run npm install -g @angular/cli
command and restart my machine. Every thing is working fine.
According to the jQuery docs, calling toggle()
without parameters will toggle visibility.
$('#play-pause').click(function(){
$('#video-over').toggle();
});
actually during the installation process.it will prompt u to enter the password..At the last step of installation, a window will appear showing cloning database files..After copying,there will be a option..like password managament..there we hav to set our password..and user name will be default..
<html>
<head>
<!-- jQuery JS Includes -->
<script type="text/javascript" src="jquery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery/ui/ui.core.js"></script>
<script type="text/javascript" src="jquery/ui/ui.datepicker.js"></script>
<!-- jQuery CSS Includes -->
<link type="text/css" href="jquery/themes/base/ui.core.css" rel="stylesheet" />
<link type="text/css" href="jquery/themes/base/ui.datepicker.css" rel="stylesheet" />
<link type="text/css" href="jquery/themes/base/ui.theme.css" rel="stylesheet" />
<!-- Setup Datepicker -->
<script type="text/javascript"><!--
$(function() {
$('input').filter('.datepicker').datepicker({
changeMonth: true,
changeYear: true,
showOn: 'button',
buttonImage: 'jquery/images/calendar.gif',
buttonImageOnly: true
});
});
--></script>
</head>
<body>
<!-- Each input field needs a unique id, but all need to be datepicker -->
<p>Date 1: <input id="one" class="datepicker" type="text" readonly="true"></p>
<p>Date 2: <input id="two" class="datepicker" type="text" readonly="true"></p>
<p>Date 3: <input id="three" class="datepicker" type="text" readonly="true"></p>
</body>
</html>
getent group <groupname>;
It is portable across both Linux and Solaris, and it works with local group/password files, NIS, and LDAP configurations.
Bootstrap 3 introduces responsive tables:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
Bootstrap 4 is similar, but with more control via some new classes:
...responsive across all viewports ... with
.table-responsive
. Or, pick a maximum breakpoint with which to have a responsive table up to by using.table-responsive{-sm|-md|-lg|-xl}
.
Credit to Jason Bradley for providing an example:
How about exporting the variable, but only inside the subshell?:
(export FOO=bar && somecommand someargs | somecommand2)
Keith has a point, to unconditionally execute the commands, do this:
(export FOO=bar; somecommand someargs | somecommand2)
function stringToBool($string){
return ( mb_strtoupper( trim( $string)) === mb_strtoupper ("true")) ? TRUE : FALSE;
}
or
function stringToBool($string) {
return filter_var($string, FILTER_VALIDATE_BOOLEAN);
}
I hope the above answer works for elastic search <7.0 but in 7.0 we cannot specify doc type and it is no longer supported. And in that case if we specify doc type we get similar error.
I you are making use of Elastic search 7.0 and Nest C# lastest version(6.6). There are some breaking changes with ES 7.0 which is causing this issue. This is because we cannot specify doc type and in the version 6.6 of NEST they are using doctype. So in order to solve that untill NEST 7.0 is released, we need to download their beta package
Please go through this link for fixing it
https://xyzcoder.github.io/elasticsearch/nest/2019/04/12/es-70-and-nest-mapping-error.html
EDIT: NEST 7.0 is now released. NEST 7.0 works with Elastic 7.0. See the release notes here for details.
You can do so:
var N = 10;
Array.apply(null, {length: N}).map(Number.call, Number)
result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
or with random values:
Array.apply(null, {length: N}).map(Function.call, Math.random)
result: [0.7082694901619107, 0.9572225909214467, 0.8586748542729765, 0.8653848143294454, 0.008339877473190427, 0.9911756622605026, 0.8133423360995948, 0.8377588465809822, 0.5577575915958732, 0.16363654541783035]
First, note that Number.call(undefined, N)
is equivalent to Number(N)
, which just returns N
. We'll use that fact later.
Array.apply(null, [undefined, undefined, undefined])
is equivalent to Array(undefined, undefined, undefined)
, which produces a three-element array and assigns undefined
to each element.
How can you generalize that to N elements? Consider how Array()
works, which goes something like this:
function Array() {
if ( arguments.length == 1 &&
'number' === typeof arguments[0] &&
arguments[0] >= 0 && arguments &&
arguments[0] < 1 << 32 ) {
return [ … ]; // array of length arguments[0], generated by native code
}
var a = [];
for (var i = 0; i < arguments.length; i++) {
a.push(arguments[i]);
}
return a;
}
Since ECMAScript 5, Function.prototype.apply(thisArg, argsArray)
also accepts a duck-typed array-like object as its second parameter. If we invoke Array.apply(null, { length: N })
, then it will execute
function Array() {
var a = [];
for (var i = 0; i < /* arguments.length = */ N; i++) {
a.push(/* arguments[i] = */ undefined);
}
return a;
}
Now we have an N-element array, with each element set to undefined
. When we call .map(callback, thisArg)
on it, each element will be set to the result of callback.call(thisArg, element, index, array)
. Therefore, [undefined, undefined, …, undefined].map(Number.call, Number)
would map each element to (Number.call).call(Number, undefined, index, array)
, which is the same as Number.call(undefined, index, array)
, which, as we observed earlier, evaluates to index
. That completes the array whose elements are the same as their index.
Why go through the trouble of Array.apply(null, {length: N})
instead of just Array(N)
? After all, both expressions would result an an N-element array of undefined elements. The difference is that in the former expression, each element is explicitly set to undefined, whereas in the latter, each element was never set. According to the documentation of .map()
:
callback
is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
Therefore, Array(N)
is insufficient; Array(N).map(Number.call, Number)
would result in an uninitialized array of length N.
Since this technique relies on behaviour of Function.prototype.apply()
specified in ECMAScript 5, it will not work in pre-ECMAScript 5 browsers such as Chrome 14 and Internet Explorer 9.
unique and random are mutually exclusive. perhaps you want this?
import random
def uniqueid():
seed = random.getrandbits(32)
while True:
yield seed
seed += 1
Usage:
unique_sequence = uniqueid()
id1 = next(unique_sequence)
id2 = next(unique_sequence)
id3 = next(unique_sequence)
ids = list(itertools.islice(unique_sequence, 1000))
no two returned id is the same (Unique) and this is based on a randomized seed value
Not tested, but something like this:
var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
(now.getUTCMonth() + 1).toString() +
"/" + now.getUTCDate() + " " + now.getUTCHours() +
":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();
Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."
Another option is git merge --squash <feature branch>
then finally do a git commit
.
From Git merge
--squash
--no-squash
Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit or move the
HEAD
, nor record$GIT_DIR/MERGE_HEAD
to cause the nextgit commit
command to create a merge commit. This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).
While the OP is the original author of the database, and likely created a simple data model, I had experienced a similar behavior on a more complicated system. In my scenario the main .mdb file was on a network share location with read/write access by the user. The .mdb file referenced tables in another .mdb file in a different network location - where the user did not have proper access.
For others viewing this post to solve similar problems, verify the linked tables path and access.
To verify linked tables...(assuming Access 2010)
For Linux and MacOS users :
OIDs basically give you a built-in id for every row, contained in a system column (as opposed to a user-space column). That's handy for tables where you don't have a primary key, have duplicate rows, etc. For example, if you have a table with two identical rows, and you want to delete the oldest of the two, you could do that using the oid column.
OIDs are implemented using 4-byte unsigned integers. They are not unique–OID counter will wrap around at 2³²-1. OID are also used to identify data types (see /usr/include/postgresql/server/catalog/pg_type_d.h
).
In my experience, the feature is generally unused in most postgres-backed applications (probably in part because they're non-standard), and their use is essentially deprecated:
In PostgreSQL 8.1 default_with_oids is off by default; in prior versions of PostgreSQL, it was on by default.
The use of OIDs in user tables is considered deprecated, so most installations should leave this variable disabled. Applications that require OIDs for a particular table should specify WITH OIDS when creating the table. This variable can be enabled for compatibility with old applications that do not follow this behavior.
You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.
You can then import project to your workspace, copy paste project to your new workspace folder, then
File?Import?Existing project in to workspace?select project.
I just discovered that tabulate has a HTML option and is rather simple to use.
Quite similar to Wayne Werner's answer:
from IPython.display import HTML, display
import tabulate
table = [["Sun",696000,1989100000],
["Earth",6371,5973.6],
["Moon",1737,73.5],
["Mars",3390,641.85]]
display(HTML(tabulate.tabulate(table, tablefmt='html')))
Still looking for something simple to use to create more complex table layouts like with latex syntax and formatting to merge cells and do variable substitution in a notebook:
Allow references to Python variables in Markdown cells #2958
To get the number of seconds from the Javascript epoch use:
date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
you have parse that Json
string using JSON.parse()
..
}).done(function(data){
obj = JSON.parse(data);
alert(obj.jobtitel);
});
Addressing Steven's comment to Sam Dufel's answer
Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?
This should do the trick:
/c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/
See this page for all the different variations of 'cats' that this matches.
You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.
I looked the above answers and found out that they are not good for my project because of licensing problems with GPL.
And I found out this: PyID3Lib, while that particular python binding release date is old, it uses the ID3Lib, which itself is up to date.
Notable to mention is that both are LGPL, and are good to go.
Use the System.Web.Helpers.Crypto
NuGet package from Microsoft. It automatically adds salt to the hash.
You hash a password like this: var hash = Crypto.HashPassword("foo");
You verify a password like this: var verified = Crypto.VerifyHashedPassword(hash, "foo");
With unsigned numbers of type unsigned int
or larger, in the absence of type conversions, a-b
is defined as yielding the unsigned number which, when added to b
, will yield a
. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).
Note that unsigned numbers smaller than unsigned int
may get promoted to type int
before the subtraction, the behavior of a-b
will depend upon the size of int
.
I was also looking for a simple multi select for my company. I wanted something simple, highly customizable and with no big dependencies others than jQuery.
I didn't found one fitting my needs so I decided to code my own.
I use it in production.
Here's some demos and documentation: loudev.com
If you want to contribute, check the github repository
You can use:
$time = strtotime("10:09") + 3600;
echo date('H:i', $time);
Or date_add
: http://www.php.net/manual/en/datetime.add.php
A quick googling on "perl high resolution timers" gave a reference to Time::HiRes. Maybe that it what you want.
public static long getPID() {
String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
if (processName != null && processName.length() > 0) {
try {
return Long.parseLong(processName.split("@")[0]);
}
catch (Exception e) {
return 0;
}
}
return 0;
}
+1 the recommendation for Joda-time. If you plan on doing anything more than a simple Hello World example, I suggest reading this:
In addition to above-said examples, it is an alternate.
^[\\w\\s]*$
Where \w
is for words and \s
is for white spaces
Try installing whole SSH package pack:
sudo apt-get install ssh
I had ssh
command on my Ubuntu but got the error as you have. After full installation all was resolved.
Pure4J supports what you are after, in two ways.
First, it provides an @ImmutableValue
annotation, so that you can annotate a class to say that it is immutable. There is a maven plugin to allow you to check that your code actually is immutable (use of final
etc.).
Second, it provides the persistent collections from Clojure, (with added generics) and ensures that elements added to the collections are immutable. Performance of these is apparently pretty good. Collections are all immutable, but implement java collections interfaces (and generics) for inspection. Mutation returns new collections.
Disclaimer: I'm the developer of this
I prefer inline-block, although float is also useful. Table-cell isn't rendered correctly by old IEs (neither does inline-block, but there's the zoom: 1; *display: inline
hack that I use frequently). If you have children that have a smaller height than their parent, floats will bring them to the top, whereas inline-block will screw up sometimes.
Most of the time, the browser will interpret everything correctly, unless, of course, it's IE. You always have to check to make sure that IE doesn't suck-- for example, the table-cell concept.
In all reality, yes, it boils down to personal preference.
One technique you could use to get rid of white space would be to set a font-size
of 0 to the parent, then give the font-size
back to the children, although that's a hassle, and gross.
For those of you running OS X, here is what worked for me:
brew install openssl
env ARCHFLAGS="-arch x86_64" LDFLAGS="-L/usr/local/opt/openssl/lib" CFLAGS="-I/usr/local/opt/openssl/include"
pip install cryptography
(Running 10.9 Mavericks)
You may also want to try merging the flags and pip commands to the following per the comment below:
brew install openssl
env ARCHFLAGS="-arch x86_64" LDFLAGS="-L/usr/local/opt/openssl/lib" CFLAGS="-I/usr/local/opt/openssl/include" pip install cryptography
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
In my case the only way I could keep using GetGroups() without any expcetion was adding the user (USER_WITH_PERMISSION) to the group which has permission to read the AD (Active Directory). It's extremely essential to construct the PrincipalContext passing this user and password.
var pc = new PrincipalContext(ContextType.Domain, domain, "USER_WITH_PERMISSION", "PASS");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
var groups = user.GetGroups();
Steps you may follow inside Active Directory to get it working:
- Into Active Directory create a group (or take one) and under secutiry tab add "Windows Authorization Access Group"
- Click on "Advanced" button
- Select "Windows Authorization Access Group" and click on "View"
- Check "Read tokenGroupsGlobalAndUniversal"
- Locate the desired user and add to the group you created (taken) from the first step
In Ubuntu 16.04.3 LTS, the next command works for me:
exit
Then I've login again.
The main difference is that the connection can be made via Unix Domain Socket, as stated here: localhost vs. 127.0.0.1
Inside of VBS you can access parameters with
Wscript.Arguments(0)
Wscript.Arguments(1)
and so on. The number of parameter:
Wscript.Arguments.Count
Create your own conversion function that applies the needed math, and invoke those instead. http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
If you just need to resync
windows time, open an elevated command prompt and type:
w32tm /resync
C:\WINDOWS\system32>w32tm /resync
Sending resync command to local computer
The command completed successfully.
Here .persist() only will insert the record.If we use .merge() it will check is there any record exist with the current ID, If it exists, it will update otherwise it will insert a new record.
2 options that you can investigate:
plt.imshow
displays the image on the axes, but if you need to display multiple images you use show()
to finish the figure. The next example shows two figures:
import numpy as np
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
plt.imshow(X_train[1])
plt.show()
In Google Colab, if you comment out the show()
method from previous example just a single image will display (the later one connected with X_train[1]
).
Here is the content from the help:
plt.show(*args, **kw)
Display a figure.
When running in ipython with its pylab mode, display all
figures and return to the ipython prompt.
In non-interactive mode, display all figures and block until
the figures have been closed; in interactive mode it has no
effect unless figures were created prior to a change from
non-interactive to interactive mode (not recommended). In
that case it displays the figures but does not block.
A single experimental keyword argument, *block*, may be
set to True or False to override the blocking behavior
described above.
plt.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
Display an image on the axes.
Parameters
----------
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
Display the image in `X` to current axes. `X` may be an
array or a PIL image. If `X` is an array, it
can have the following shapes and types:
- MxN -- values to be mapped (float or int)
- MxNx3 -- RGB (float or uint8)
- MxNx4 -- RGBA (float or uint8)
The value for each component of MxNx3 and MxNx4 float arrays
should be in the range 0.0 to 1.0. MxN arrays are mapped
to colors based on the `norm` (mapping scalar to scalar)
and the `cmap` (mapping the normed scalar to a color).
If you want to merge the filters (eg. CSV and Excel files), use this formula:
OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";
Or if you want to see XML or PDF files in one time use this:
of.Filter = @" XML or PDF |*.xml;*.pdf";
Two things you can do:
git checkout -b sillyname
git commit -am "silly message"
git checkout -
or
git stash -u
git branch sillyname stash@{0}
(git checkout -
<-- the dash is a shortcut for the previous branch you were on )
(git stash -u
<-- the -u
means that it also takes unstaged changes )
While I would recommend against this.
But you can use shutdown as client if the target machine has remote shutdown enabled and is in the same workgroup.
Example:
shutdown.exe /s /m \\<target-computer-name> /t 00
replacing <target-computer-name>
with the URI for the target machine,
Otherwise, if you want to trigger this through Apache, you'll need to configure the batch script as a CGI script by putting AddHandler cgi-script .bat
and Options +ExecCGI
into either a local .htaccess
file or in the main configuration for your Apache install.
Then you can just call the .bat
file containing the shutdown.exe
command from your browser.
Yes, the sorting is different.
Items in the ORDER BY
list are applied in order.
Later items only order peers left from the preceding step.
Why don't you just try?
You can use anycache to do the job for you. It considers all the details:
pickle
module to handle lambda
and all the nice
python features.Assuming you have a function myfunc
which creates the instance:
from anycache import anycache
class Company(object):
def __init__(self, name, value):
self.name = name
self.value = value
@anycache(cachedir='/path/to/your/cache')
def myfunc(name, value)
return Company(name, value)
Anycache calls myfunc
at the first time and pickles the result to a
file in cachedir
using an unique identifier (depending on the function name and its arguments) as filename.
On any consecutive run, the pickled object is loaded.
If the cachedir
is preserved between python runs, the pickled object is taken from the previous python run.
For any further details see the documentation
Suppose we have a df_data data frame as below
> df_data
ID MONTH-YEAR VALUE
1 110 JAN.2012 1000
2 111 JAN.2012 2000
3 121 FEB.2012 3000
4 131 FEB.2012 4000
5 141 MAR.2012 5000
To count number of rows in df_data grouped by MONTH-YEAR column, you can use:
> summary(df_data$`MONTH-YEAR`)
FEB.2012 JAN.2012 MAR.2012
2 2 1
summary function will create a table from the factor argument, then create a vector for the result (line 7 & 8)
EDIT: I noticed a few downvotes and took another look at this Q&A. Most people seem to miss that the OP asked for fields to be dynamically selected based on the caller-provided list of fields. You can't do this with the statically-defined json struct tag.
If what you want is to always skip a field to json-encode, then of course use json:"-"
to ignore the field (also note that this is not required if your field is unexported - those fields are always ignored by the json encoder). But that is not the OP's question.
To quote the comment on the json:"-"
answer:
This [the
json:"-"
answer] is the answer most people ending up here from searching would want, but it's not the answer to the question.
I'd use a map[string]interface{} instead of a struct in this case. You can easily remove fields by calling the delete
built-in on the map for the fields to remove.
That is, if you can't query only for the requested fields in the first place.
You can check the existence of a symlink and that it is not broken with:
[ -L ${my_link} ] && [ -e ${my_link} ]
So, the complete solution is:
if [ -L ${my_link} ] ; then
if [ -e ${my_link} ] ; then
echo "Good link"
else
echo "Broken link"
fi
elif [ -e ${my_link} ] ; then
echo "Not a link"
else
echo "Missing"
fi
-L
tests whether there is a symlink, broken or not. By combining with -e
you can test whether the link is valid (links to a directory or file), not just whether it exists.
A really simple option that works with any website where you can upload Javascript is www.multilingualizer.com
It lets you put all text for all languages onto one page and then hides the languages the user doesn't need to see. Works well.
This will give you one last document for a collection
db.collectionName.findOne({}, {sort:{$natural:-1}})
$natural:-1
means order opposite of the one that records are inserted in.
Edit: For all the downvoters, above is a Mongoose syntax,
mongo CLI syntax is: db.collectionName.find({}).sort({$natural:-1}).limit(1)
Try this:
<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table</title>
<style>
th, td, p, input {
font:14px Verdana;
}
tr{
align: right
}
table, th, td
{
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<div id="showData"></div>
</body>
<script>
function CreateTableFromJSON() {
var obj = {[{"city":"AMBALA","cStatus":"Y"},
{"city":"ASANKHURD","cStatus":"Y"},
{"city":"ASSANDH","cStatus":"Y"}]}
var table = document.createElement('table');
var tr = table.insertRow(-1);
function iterate(obj,table,tr){
for(var props in obj){
if(obj.hasOwnProperty(props)){
if(typeof obj[props]=='object')
{
var trNext = table.insertRow(-1);
var tabCellHead = trNext.insertCell(-1);
var tabCell = trNext.insertCell(-1);
var table_in = document.createElement('table');
var tr_in;
var th = document.createElement("th");
th.innerHTML = props;
tabCellHead.appendChild(th);
tabCell.appendChild(table_in)
iterate(obj[props],table_in,tr_in);
}
else
{
if(tr === undefined)
{
tr = table.insertRow(-1);
}
var tabCell = tr.insertCell(-1);
console.log(props+' * '+obj[props]);
tabCell.innerHTML = obj[props];
}
}
}
}
iterate(obj,table,tr);
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>
At the command prompt try:
mysql -u root -p
give the password when prompted.
Came across this issue after I merged a pull request on Bitbucket.
Had to do
git fetch
and that was it.
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
Could you try this one:
create or replace
procedure point_triangle
IS
BEGIN
FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P where P.TEAM = 'IND' group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.S);
END LOOP;
END;
I used a list in my controller class to set data into grid view. The code works fine for me:
public ActionResult ExpExcl()
{
List<PersonModel> person= new List<PersonModel>
{
new PersonModel() {FirstName= "Jenny", LastName="Mathew", Age= 23},
new PersonModel() {FirstName= "Paul", LastName="Meehan", Age=25}
};
var grid= new GridView();
grid.DataSource= person;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition","attachement; filename=data.xls");
Response.ContentType="application/excel";
StringWriter sw= new StringWriter();
HtmlTextWriter htw= new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View();
}
A solution that worked for me is using the hidden input field in the template
<input type="hidden" id="myVar" name="variable" value="{{ variable }}">
Then getting the value in javascript this way,
var myVar = document.getElementById("myVar").value;
Sounds like mssql jdbc is buffering the entire resultset for you. You can add a connect string parameter saying selectMode=cursor or responseBuffering=adaptive. If you are on version 2.0+ of the 2005 mssql jdbc driver then response buffering should default to adaptive.
Generally, this keyword is used inside a class, generally with in the member functions to access non-static members of a class(variables or functions) for the current object.
Let's take an example to understand the usage of $this.
<?php
class Hero {
// first name of hero
private $name;
// public function to set value for name (setter method)
public function setName($name) {
$this->name = $name;
}
// public function to get value of name (getter method)
public function getName() {
return $this->name;
}
}
// creating class object
$stark = new Hero();
// calling the public function to set fname
$stark->setName("IRON MAN");
// getting the value of the name variable
echo "I Am " . $stark->getName();
?>
OUTPUT: I am IRON MAN
NOTE: A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created.
I had a problem with implementing the code until I found some website (I can't find it again right now) that explained that you need to include the package name in the name of the intent.putExtra.
It would pull up the application, but it wouldn't recognize any barcodes, and when I changed it from.
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
to
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
It worked great. Just a tip for any other novice Android programmers.
I'd start by using glob:
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
im=Image.open(filename)
image_list.append(im)
then do what you need to do with your list of images (image_list).
I found one more answer when there is a constraint layout inside the scroll view then we need to put
android:fillViewport="true"
to the scroll view
and
android:layout_height="0dp"
in the constraint layout
Example:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="0dp">
// Rest of the views
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
Callback can be very helpful in Java.
Using Callback you can notify another Class of an asynchronous action that has completed with success or error.
Simple use this to strip the text :
echo strlen($string) >= 500 ?
substr($string, 0, 490) . ' <a href="link/to/the/entire/text.htm">[Read more]</a>' :
$string;
Edit and finally :
function split_words($string, $nb_caracs, $separator){
$string = strip_tags(html_entity_decode($string));
if( strlen($string) <= $nb_caracs ){
$final_string = $string;
} else {
$final_string = "";
$words = explode(" ", $string);
foreach( $words as $value ){
if( strlen($final_string . " " . $value) < $nb_caracs ){
if( !empty($final_string) ) $final_string .= " ";
$final_string .= $value;
} else {
break;
}
}
$final_string .= $separator;
}
return $final_string;
}
Here separator is the href link to read more ;)
You should add the target="_blank"
and rel="noopener noreferrer"
in the anchor tag.
For example:
<a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>
Adding rel="noopener noreferrer"
is not mandatory, but it's a recommended security measure. More information can be found in the links below.
Source:
Judging by your other post: How to Get the inner text of a span in PHP. You're quite new to web programming, and need to learn about the differences between code on the client (JavaScript) and code on the server (PHP).
As for the correct approach to grabbing the span text from the client I recommend Johns answer.
These are a good place to get started.
JavaScript: https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript
PHP: https://stackoverflow.com/questions/772349/what-is-a-good-online-tutorial-for-php
Also I recommend using jQuery (Once you've got some JavaScript practice) it will eliminate most of the cross-browser compatability issues that you're going to have. But don't use it as a crutch to learn on, it's good to understand JavaScript too. http://jquery.com/
if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi
where ${var+x}
is a parameter expansion which evaluates to nothing if var
is unset, and substitutes the string x
otherwise.
Quotes can be omitted (so we can say ${var+x}
instead of "${var+x}"
) because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to x
(which contains no word breaks so it needs no quotes), or to nothing (which results in [ -z ]
, which conveniently evaluates to the same value (true) that [ -z "" ]
does as well)).
However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to the first author of this quotes explanation who is also a major Bash coder), it would sometimes be better to write the solution with quotes as [ -z "${var+x}" ]
, at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.
if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi
This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if var=''
, then the above solution will output "var is blank".
The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.
The distinction may not be essential in every scenario though. In those cases [ -z "$var" ]
will be just fine.
Move the -h and specify that mydir is a directory
attrib /S /D /L -H mydir\*.*
A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.
When your program only have daemon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.
You can specify that a Thread
is a daemon one by using setDaemon
method, they usually don't exit, neither they are interrupted.. they just stop when application stops.
I'm a lazy programmer. I don't use DOM because it seems like extra typing. To me, the less code the better. Here's how I would add "bar" without replacing "foo":
function start(){
var innermyspan = document.getElementById("myspan").innerHTML;
document.getElementById("myspan").innerHTML=innermyspan+"bar";
}
According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:
{% if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') ) %}
<li>some text</li>
{% endif %}
Edit: Using line_statement_prefix = '#'
* the code would look like this:
# if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') )
<li>some text</li>
# endif
*Here's an example of how you'd specify the line_statement_prefix
in the Environment
:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml']),
line_statement_prefix='#'
)
Or using Flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
You're missing an ending anchor.
if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
// ...
}
EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:
if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
// ...
}
It's very similar to
char array[] = {'O', 'n', 'e', ' ', /*etc*/ ' ', 'm', 'u', 's', 'i', 'c', '\0'};
but gives you read-only memory.
For a discussion of the difference between a char[]
and a char *
, see comp.lang.c FAQ 1.32.
From the ToolBar to go
Project> Properties>Java Build Path > Add External Jars
.
Locate the File on the local disk or web Directory and Click Open.
This will automatically add the required Jar files to the Library.
I did it a slightly different way using a function within created().
created() {
window.addEventListener('click', (e) => {
if (!this.$el.contains(e.target)){
this.showMobileNav = false
}
})
},
This way, if someone clicks outside of the element, then in my case, the mobile nav is hidden.
Hope this helps!
Why do you want your string to be initialized at all? You don't have to initialize a variable when you declare one, and IMO, you should only do so when the value you are assigning is valid in the context of the code block.
I see this a lot:
string name = null; // or String.Empty
if (condition)
{
name = "foo";
}
else
{
name = "bar";
}
return name;
Not initializing to null would be just as effective. Furthermore, most often you want a value to be assigned. By initializing to null, you can potentially miss code paths that don't assign a value. Like so:
string name = null; // or String.Empty
if (condition)
{
name = "foo";
}
else if (othercondition)
{
name = "bar";
}
return name; //returns null when condition and othercondition are false
When you don't initialize to null, the compiler will generate an error saying that not all code paths assign a value. Of course, this is a very simple example...
Matthijs
If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:
[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];
cmd >>file.txt 2>&1
Bash executes the redirects from left to right as follows:
>>file.txt
: Open file.txt
in append mode and redirect stdout
there.2>&1
: Redirect stderr
to "where stdout
is currently going". In this case, that is a file opened in append mode. In other words, the &1
reuses the file descriptor which stdout
currently uses.I use to always add a new target on my solutions for achieving this.
<Target Name="clean_folders">
<RemoveDir Directories=".\ProjectName\bin" />
<RemoveDir Directories=".\ProjectName\obj" />
<RemoveDir Directories="$(ProjectVarName)\bin" />
<RemoveDir Directories="$(ProjectVarName)\obj" />
</Target>
And you can call it from command line
msbuild /t:clean_folders
This can be your batch file.
msbuild /t:clean_folders
PAUSE
$(document).ready(function() {
window.setInterval(function() {
var timeLeft = $("#timeLeft").html();
if(eval(timeLeft) == 0) {
window.location= ("http://www.technicalkeeda.com");
} else {
$("#timeLeft").html(eval(timeLeft)- eval(1));
}
}, 1000);
});
public static T[] Concat<T>(this T[] first, params T[][] arrays)
{
int length = first.Length;
foreach (T[] array in arrays)
{
length += array.Length;
}
T[] result = new T[length];
length = first.Length;
Array.Copy(first, 0, result, 0, first.Length);
foreach (T[] array in arrays)
{
Array.Copy(array, 0, result, length, array.Length);
length += array.Length;
}
return result;
}
I have tried every method mentioned above and nothing worked, except installing jupyter in the new environment.
to activate the new environment
conda activate new_env
replace 'new_env' with your environment name.
next install jupyter 'pip install jupyter'
you can also install jupyter by going to anaconda navigator and selecting the right environment, and installing jupyter notebook from Home tab
I have had this issue before, and solve it using the following config.
[http "https://your.domain"]
sslCAInfo=/path/to/your/domain/priviate-certificate
Since git 2.3.1, you can put https://your.domain
after http to indicate the following certificate is only for it.
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false}
property for window.addEventListener
, which is recommended as the only working solution, for example here.
In the end, after many tries, I found a way that works for me in both Firefox and Chrome:
window.addEventListener('keydown', (e) => {
if (e.target.localName != 'input') { // if you need to filter <input> elements
switch (e.keyCode) {
case 37: // left
case 39: // right
e.preventDefault();
break;
case 38: // up
case 40: // down
e.preventDefault();
break;
default:
break;
}
}
}, {
capture: true, // this disables arrow key scrolling in modern Chrome
passive: false // this is optional, my code works without it
});
Quote for EventTarget.addEventListener()
from MDN
options Optional
An options object specifies characteristics about the event listener. The available options are:capture
ABoolean
indicating that events of this type will be dispatched to the registeredlistener
before being dispatched to anyEventTarget
beneath it in the DOM tree.
once
...
passive
ABoolean
that, if true, indicates that the function specified bylistener
will never callpreventDefault()
. If a passive listener does callpreventDefault()
, the user agent will do nothing other than generate a console warning. ...
One more example for lists:
// constructs the elements in place.
emplace_back("element");
// creates a new object and then copies (or moves) that object.
push_back(ExplicitDataType{"element"});
I can't comment on the above answer, but be careful with @Pavel Chuchuva's answer. That formula will not return a result if both coordinates are the same. In that case, distance is null, and so that row won't be returned with that formula as is.
I'm not a MySQL expert, but this seems to be working for me:
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
FROM markers HAVING distance < 25 OR distance IS NULL ORDER BY distance LIMIT 0 , 20;
Just remove the .val(). Like:
if ( $('html').attr('lang') == 'fr-FR' ) {
// do this
} else {
// do that
}
Ok well this might work for you, a function that takes a path and returns an array of file names in the folder. You could use an if statement to get just the excel files when looping through the array.
Function listfiles(ByVal sPath As String)
Dim vaArray As Variant
Dim i As Integer
Dim oFile As Object
Dim oFSO As Object
Dim oFolder As Object
Dim oFiles As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files
If oFiles.Count = 0 Then Exit Function
ReDim vaArray(1 To oFiles.Count)
i = 1
For Each oFile In oFiles
vaArray(i) = oFile.Name
i = i + 1
Next
listfiles = vaArray
End Function
It would be nice if we could just access the files in the files object by index number but that seems to be broken in VBA for whatever reason (bug?).
You can dynamically add and delete table rows like this in the image using jQuery..
Here is html part...
<form id='students' method='post' name='students' action='index.php'>
<table border="1" cellspacing="0">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
<th>S. No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Tamil</th>
<th>English</th>
<th>Computer</th>
<th>Total</th>
</tr>
<tr>
<td><input type='checkbox' class='case'/></td>
<td>1.</td>
<td><input type='text' id='first_name' name='first_name[]'/></td>
<td><input type='text' id='last_name' name='last_name[]'/></td>
<td><input type='text' id='tamil' name='tamil[]'/></td>
<td><input type='text' id='english' name='english[]'/> </td>
<td><input type='text' id='computer' name='computer[]'/></td>
<td><input type='text' id='total' name='total[]'/> </td>
</tr>
</table>
<button type="button" class='delete'>- Delete</button>
<button type="button" class='addmore'>+ Add More</button>
<p>
<input type='submit' name='submit' value='submit' class='but'/></p>
</form>
Next need to include jquery...
<script src='jquery-1.9.1.min.js'></script>
Finally script which adds the table rows...
<script>
var i=2;
$(".addmore").on('click',function(){
var data="<tr><td><input type='checkbox' class='case'/></td><td>"+i+".</td>";
data +="<td><input type='text' id='first_name"+i+"' name='first_name[]'/></td> <td><input type='text' id='last_name"+i+"' name='last_name[]'/></td><td><input type='text' id='tamil"+i+"' name='tamil[]'/></td><td><input type='text' id='english"+i+"' name='english[]'/></td><td><input type='text' id='computer"+i+"' name='computer[]'/></td><td><input type='text' id='total"+i+"' name='total[]'/></td></tr>";
$('table').append(data);
i++;
});
</script>
Also refer demo & tutorial for this dynamically add & remove table rows
You can try this link
try
{
var IEVAlue = 9000; // can be: 9999 , 9000, 8888, 8000, 7000
var targetApplication = Processes.getCurrentProcessName() + ".exe";
var localMachine = Registry.LocalMachine;
var parentKeyLocation = @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl";
var keyName = "FEATURE_BROWSER_EMULATION";
"opening up Key: {0} at {1}".info(keyName, parentKeyLocation);
var subKey = localMachine.getOrCreateSubKey(parentKeyLocation,keyName,true);
subKey.SetValue(targetApplication, IEVAlue,RegistryValueKind.DWord);
return "all done, now try it on a new process".info();
}
catch(Exception ex)
{
ex.log();
"NOTE: you need to run this under no UAC".info();
}
Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:
Make sure you study this thread, as overriding a signed tag is not as easy:
git tag
man page seriously advised against a simple git tag -f B
to replace a tag name "A
"don't try to recreate a signed tag with git tag -f
(see the thread extract below)
(it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):
Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:
- in the tag object itself as a contents of 'tag' header (you can see it in output of "
git show <tag>
" and also in output of "git cat-file -p <tag>
", where<tag>
is heavyweight tag, e.g.v1.6.3
ingit.git
repository),- and also is default name of tag reference (reference in "
refs/tags/*
" namespace) pointing to a tag object.
Note that the tag reference (appropriate reference in the "refs/tags/*
" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3
', other can have in 'refs/tags/sub/v0.1.3
' for example.So when you create signed tag '
A
', you have the following situation (assuming that it points at some commit)
35805ce <--- 5b7b4ead <=== refs/tags/A
(commit) tag A
(tag)
Please also note that "
git tag -f A A
" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.If you do "
git tag -f -s A A
": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of-s
/-a
/-m
options is used to force annotated tag (creation of tag object), you will get the following situation
35805ce <--- 5b7b4ea <--- ada8ddc <=== refs/tags/A
(commit) tag A tag A
(tag) (tag)
Note also that "
git show A
" would show the whole chain down to the non-tag object...
You have to use image
.listStyle {
list-style: none;
background: url(bullet.jpg) no-repeat left center;
padding-left: 40px;
}
Difference between "querySelector" and "querySelectorAll"
//querySelector returns single element_x000D_
let listsingle = document.querySelector('li');_x000D_
console.log(listsingle);_x000D_
_x000D_
_x000D_
//querySelectorAll returns lit/array of elements_x000D_
let list = document.querySelectorAll('li');_x000D_
console.log(list);_x000D_
_x000D_
_x000D_
//Note : output will be visible in Console
_x000D_
<ul>_x000D_
<li class="test">ffff</li>_x000D_
<li class="test">vvvv</li>_x000D_
<li>dddd</li>_x000D_
<li class="test">ddff</li>_x000D_
</ul>
_x000D_
Selecting text as said from somebody, may the selection appear momentarily.
In Windows Forms applications
there is no other solutions for the problem, but today I found a bad, working, way to solve: you can put a PictureBox
in overlapping to the RichtextBox
with the screenshot of if, during the selection and the changing color or font, making it after reappear all, when the operation is complete.
Code is here...
//The PictureBox has to be invisible before this, at creation
//tb variable is your RichTextBox
//inputPreview variable is your PictureBox
using (Graphics g = inputPreview.CreateGraphics())
{
Point loc = tb.PointToScreen(new Point(0, 0));
g.CopyFromScreen(loc, loc, tb.Size);
Point pt = tb.GetPositionFromCharIndex(tb.TextLength);
g.FillRectangle(new SolidBrush(Color.Red), new Rectangle(pt.X, 0, 100, tb.Height));
}
inputPreview.Invalidate();
inputPreview.Show();
//Your code here (example: tb.Select(...); tb.SelectionColor = ...;)
inputPreview.Hide();
Better is to use WPF; this solution isn't perfect, but for Winform it works.
The query you want to show as an example is:
SELECT * FROM temp WHERE mydate > '2009-06-29 16:00:44';
04:00:00 is 4AM, so all the results you're displaying come after that, which is correct.
If you want to show everything after 4PM, you need to use the correct (24hr) notation in your query.
To make things a bit clearer, try this:
SELECT mydate, DATE_FORMAT(mydate, '%r') FROM temp;
That will show you the date, and its 12hr time.
Here is my simple and working function to generate a Bitmap! I Use ZXing1.3.jar only! I've also set Correction Level to High!
PS: x and y are reversed, it's normal, because bitMatrix reverse x and y. This code works perfectly with a square image.
public static Bitmap generateQrCode(String myCodeText) throws WriterException {
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage
QRCodeWriter qrCodeWriter = new QRCodeWriter();
int size = 256;
ByteMatrix bitMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
int width = bitMatrix.width();
Bitmap bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < width; y++) {
bmp.setPixel(y, x, bitMatrix.get(x, y)==0 ? Color.BLACK : Color.WHITE);
}
}
return bmp;
}
EDIT
It's faster to use bitmap.setPixels(...) with a pixel int array instead of bitmap.setPixel one by one:
BitMatrix bitMatrix = writer.encode(inputValue, BarcodeFormat.QR_CODE, size, size);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
}
}
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
To have them centered correctly and only for the items inside the wrapper .center-wrapper use this. ( all options combined should work cross browser ) if not please post a reply here!
.center-wrapper .ui-btn-text {
overflow: hidden;
text-align: center;
text-overflow: ellipsis;
white-space: nowrap;
text-align: center;
margin: 0 auto;
}
First step, you have to set your autofocus
attribute on form input.
<input name="full_name" autofocus/>
And then you have to add declaration to set autofocus of your input after your modal is shown.
Try this code :
$(document).on('ready', function(){
// Set modal form input to autofocus when autofocus attribute is set
$('.modal').on('shown.bs.modal', function () {
$(this).find($.attr('autofocus')).focus();
});
});
First you are linking the file that is here:
<script src="../Script/login.js">
Which would lead the website to a file in the Folder Script
, but then in the second paragraph you are saying that the folder name is
and also i have onother folder named scripts that contains the the following login.js file
So, this won't work! Because you are not accessing the correct file. To do that please write the code as
<script src="/script/login.js"></script>
Try removing the ..
from the beginning of the code too.
This way, you'll reach the js file where the function would run!
Just to make sure:
Just to make sure that the files are attached the HTML DOM, then please open Developer Tools (F12) and in the network workspace note each request that the browser makes to the server. This way you will learn which files were loaded and which weren't, and also why they were not!
Good luck.