Aside from @see
, a more general way of refering to another class and possibly method of that class is {@link somepackage.SomeClass#someMethod(paramTypes)}
. This has the benefit of being usable in the middle of a javadoc description.
From the javadoc documentation (description of the @link tag):
This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text.
Typing /**
+ then pressing Enter above a method signature will create Javadoc stubs for you.
Navigate to http://www.oracle.com/technetwork/java/javase/downloads/index.html
Under Addition Resources and Under Java SE 8 Documentation
Click Download button
Under Java SE Development Kit 8 Documentation > Java SE Development Kit 8u77 Documentation
Accept the License Agreement and click on the download zip file
Unzip the downloaded file Start the API docs from jdk-8u77-docs-all\docs\api\index.html
Navigate to http://docs.oracle.com/javase/
From Release dropdown select either of Java SE 7/6/5
In corresponding JAVA SE page and under Downloads left side menu Click JDK 7/6/5 Documentation or Java SE Documentation
Now in next page select the appropriate Java SE Development Kit 7uXX Documentation.
Accept License Agreement and click on Download zip file
Unzip the file and Start the API docs from
jdk-7uXX-docs-all\docs\api\index.html
Quick and in some cases error-prone solution:
Find Regexp: (?sm)(.*?)([^\n]*\b(class|interface|enum)\b.*)
Replace: $1/**\n * \n * @author <a href="mailto:[email protected]">John Smith</a>\n */\n$2
This will add the header to the first encountered class/interface/enum in the file. Class should have no existing header yet.
I would like to add some insight into other answers
In my case
-Xdoclint:none
Didn't work.
Let start with that, in my project, I didn't really need javadoc at all. Only some necessary plugins had got a build time dependency on it.
So, the most simple way solve my problem was:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
You can use eclipse style of JavaDoc comment generation through "Fix doc comment". Open "Preference" -> "Keymap" and assign "Fix doc comment" action to a key that you want.
If the source jars are in the local repository and you are using Eclipses maven support the sources are getting automatically attached. You can run mvn dependency:sources
to download all source jars for a given project. Not sure how to do the same with the documentation though.
One more option, not exactly what you asked, but can be useful:
Go to Settings
-> Editor
-> File and code templates
-> Includes
tab (on the right). There is a template header for the new files, you can use the username here:
/**
* @author myname
*/
For system username use:
/**
* @author ${USER}
*/
its simple go to the folder where your all java code is saved say E:/javaFolder and then javadoc *.java
example
E:\javaFolder> javadoc *.java
ANT for example - source code browsable online: http://svn.apache.org/viewvc/ant/core/trunk/src/main/org/apache/tools/ant/DefaultLogger.java?view=co
To choose other files start from: http://svn.apache.org/viewvc/ant/core/trunk/src/main/org/apache/tools/ant/?pathrev=761528
You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the
tag (that you are looking for). The corresponding example from the documentation is as follows
For example, here is a comment that refers to the getComponentAt(int, int) method:
Use the {@link #getComponentAt(int, int) getComponentAt} method.
The package.class
part can be ommited if the referred method is in the current class.
Other useful links about JavaDoc are:
For me the /**<NEWLINE>
or Shift-Alt-J (or ?-?-J on a Mac) approach works best.
I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.
IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details.
Javadocs don't offer any special tools for external links, so you should just use standard html:
See <a href="http://groversmill.com/">Grover's Mill</a> for a history of the
Martian invasion.
or
@see <a href="http://groversmill.com/">Grover's Mill</a> for a history of
the Martian invasion.
Don't use {@link ...}
or {@linkplain ...}
because these are for links to the javadocs of other classes and methods.
For the Java programming language, there is no difference between the two. Java has two types of comments: traditional comments (/* ... */
) and end-of-line comments (// ...
). See the Java Language Specification. So, for the Java programming language, both /* ... */
and /** ... */
are instances of traditional comments, and they are both treated exactly the same by the Java compiler, i.e., they are ignored (or more correctly: they are treated as white space).
However, as a Java programmer, you do not only use a Java compiler. You use a an entire tool chain, which includes e.g. the compiler, an IDE, a build system, etc. And some of these tools interpret things differently than the Java compiler. In particular, /** ... */
comments are interpreted by the Javadoc tool, which is included in the Java platform and generates documentation. The Javadoc tool will scan the Java source file and interpret the parts between /** ... */
as documentation.
This is similar to tags like FIXME
and TODO
: if you include a comment like // TODO: fix this
or // FIXME: do that
, most IDEs will highlight such comments so that you don't forget about them. But for Java, they are just comments.
Use View
| Quick Documentation or the corresponding keyboard shortcut (by default: Ctrl+Q on Windows/Linux and Ctrl+J on macOS or F1 in the recent IDE versions). See the documentation for more information.
It's also possible to enable automatic JavaDoc popup on explicit (invoked by a shortcut) code completion in Settings
| Editor
| General
| Code completion
(Autopopup documentation):
Yet another way to see the quick doc is on mouse move:
I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete
Using Java SE 1.6, it looks like all UPPERCASE PRE identifiers is the best way to do this in Javadoc:
/**
* <PRE>
* insert code as you would anywhere else
* </PRE>
*/
is the simplest way to do this.
An Example from a javadoc I got from a java.awt.Event method:
/**
* <PRE>
* int onmask = SHIFT_DOWN_MASK | BUTTON1_DOWN_MASK;
* int offmask = CTRL_DOWN_MASK;
* if ((event.getModifiersEx() & (onmask | offmask)) == onmask) {
* ...
* }
* </PRE>
*/
This produces output that looks exactly like the regular code, with the regular code spacings and new lines intact.
There are already useful answers to this question above, however there is one more possibility which I don't see being addressed here.
We should consider that the java is installed correctly (that's why eclipse could have been launched in the first place), and the JDK is also added correctly to the eclipse. So the issue might be for some reason (e.g. migration of eclipse to another OS) the path for javadoc is not right which you can easily check and modify in the javadoc wizard page. Here is detailed instructions:
Project->Generate Javadoc...
javadoc command
path is correct as illustrated in below screenshot:Project > Generate Javadoc....
In the Javadoc command: field, browse to find javadoc.exe (usually at [path_to_jdk_directory]\bin\javadoc.exe).
Check the box next to the project/package/file for which you are creating the Javadoc.
In the Destination: field, browse to find the desired destination (for example, the root directory of the current project).
Click Finish.
You should now be able to find the newly generated Javadoc in the destination folder. Open index.html.
This trick worked for me in Eclipse Luna (4.4.2): For a jar file I am using (htsjdk), I packed the source in a separate jar file (named htsjdk-2.0.1-src.jar; I could do this since htsjdk is open source) and stored it in the lib-src folder of my project. In my own Java source I selected an element I was using from the jar and hit F3 (Open declaration). Eclipse opened the class file and showed the button "Attach source". I clicked the button and pointed to the src jar file I had just put into the lib-src folder. Now I get the Javadoc when hovering over anything I’m using from the jar.
As far as I can tell after reading the docs for javadoc there is no such feature.
Don't use <code>foo</code>
as recommended in other answers; you can use {@code foo}
. This is especially good to know when you refer to a generic type such as {@code Iterator<String>}
-- sure looks nicer than <code>Iterator<String></code>
, doesn't it!
@funroll is absolutely right. Here you can see what you will need Make sure function runs on main thread only. If you do not want deal with threads you can do like this for example: create NSUserDefaults and in ViewDidLoad cheking condition was pressed button in another View or not (in another View set in NSUserDefaults needed information) and depending on the conditions set needed title for your UIButton, so [yourButton setTitle: @"Title" forState: UIControlStateNormal];
With macOS 10.15 and Homebrew 2.1.6 I was getting this error with Python 3.7. I just needed to run:
python3 -m ensurepip
Now python3 -m pip
works for me.
I'v solved putting this code after page load:
<script>
var randomicAtomic = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
$('input[type=text]').attr('autocomplete',randomicAtomic);
</script>
Well, for me this is the expected result; adding six months to Jan. 1st July.
mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01 |
+--------------------------------------------+
One very important thing is that like other Graph API request, you won't get the JSON data in response, rather the call returns a HTTP REDIRECT to the URL of the profile pic. So, if you want to fetch the URL, you either need to read the response HTTP header or you can use FQLs.
There might be neater methods, but the following could be one approach:
SELECT t.fk,
(
SELECT t1.Field1
FROM `table` t1
WHERE t1.fk = t.fk AND t1.Field1 IS NOT NULL
LIMIT 1
) Field1,
(
SELECT t2.Field2
FROM `table` t2
WHERE t2.fk = t.fk AND t2.Field2 IS NOT NULL
LIMIT 1
) Field2
FROM `table` t
WHERE t.fk = 3
GROUP BY t.fk;
Test Case:
CREATE TABLE `table` (fk int, Field1 varchar(10), Field2 varchar(10));
INSERT INTO `table` VALUES (3, 'ABC', NULL);
INSERT INTO `table` VALUES (3, NULL, 'DEF');
INSERT INTO `table` VALUES (4, 'GHI', NULL);
INSERT INTO `table` VALUES (4, NULL, 'JKL');
INSERT INTO `table` VALUES (5, NULL, 'MNO');
Result:
+------+--------+--------+
| fk | Field1 | Field2 |
+------+--------+--------+
| 3 | ABC | DEF |
+------+--------+--------+
1 row in set (0.01 sec)
Running the same query without the WHERE t.fk = 3
clause, it would return the following result-set:
+------+--------+--------+
| fk | Field1 | Field2 |
+------+--------+--------+
| 3 | ABC | DEF |
| 4 | GHI | JKL |
| 5 | NULL | MNO |
+------+--------+--------+
3 rows in set (0.01 sec)
String id = UUID.randomUUID().toString();
See Android Developer blog article for using UUID class to get uuid
Well in order to do this, you are not limited with the Class
abstraction of ES6. Accessing the parent constructor's prototype methods is possible through the __proto__
property (I am pretty sure there will be fellow JS coders to complain that it's depreciated) which is depreciated but at the same time discovered that it is actually an essential tool for sub-classing needs (especially for the Array sub-classing needs though). So while the __proto__
property is still available in all major JS engines that i know, ES6 introduced the Object.getPrototypeOf()
functionality on top of it. The super()
tool in the Class
abstraction is a syntactical sugar of this.
So in case you don't have access to the parent constructor's name and don't want to use the Class
abstraction you may still do as follows;
function ChildObject(name) {
// call the parent's constructor
ParentObject.call(this, name);
this.myMethod = function(arg) {
//this.__proto__.__proto__.myMethod.call(this,arg);
Object.getPrototypeOf(Object.getPrototypeOf(this)).myMethod.call(this,arg);
}
}
The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.
You have to store the value of sorted(list) in a variable explicitly.
Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.
The Facebook API limit isn't really documented, but apparently it's something like: 600 calls per 600 seconds, per token & per IP. As the site is restricted, quoting the relevant part:
After some testing and discussion with the Facebook platform team, there is no official limit I'm aware of or can find in the documentation. However, I've found 600 calls per 600 seconds, per token & per IP to be about where they stop you. I've also seen some application based rate limiting but don't have any numbers.
As a general rule, one call per second should not get rate limited. On the surface this seems very restrictive but remember you can batch certain calls and use the subscription API to get changes.
As you can access the Graph API on the client side via the Javascript SDK; I think if you travel your request for photos from the client, you won't hit any application limit
as it's the user (each one with unique id) who's fetching data, not your application server (unique ID).
This may mean a huge refactor if everything you do go through a server. But it seems like the best solution if you have so many request (as it'll give a breath to your server).
Else, you can try batch
request, but I guess you're already going this way if you have big traffic.
If nothing of this works, according to the Facebook Platform Policy you should contact them.
If you exceed, or plan to exceed, any of the following thresholds please contact us as you may be subject to additional terms: (>5M MAU) or (>100M API calls per day) or (>50M impressions per day).
One interesting approach is to cast CString
to CStringA
inside a string
constructor. Unlike std::string s((LPCTSTR)cs);
this will work even if _UNICODE
is defined. However, if that is the case, this will perform conversion from Unicode to ANSI, so it is unsafe for higher Unicode values beyond the ASCII character set. Such conversion is subject to the _CSTRING_DISABLE_NARROW_WIDE_CONVERSION
preprocessor definition. https://msdn.microsoft.com/en-us/library/5bzxfsea.aspx
CString s1("SomeString");
string s2((CStringA)s1);
This is an alternative answer for the case where tqdm_notebook doesn't work for you.
from time import sleep
from tqdm import tqdm
values = range(3)
with tqdm(total=len(values)) as pbar:
for i in values:
pbar.write('processed: %d' %i)
pbar.update(1)
sleep(1)
The output would look something like this (progress would show up red):
0%| | 0/3 [00:00<?, ?it/s]
processed: 1
67%|¦¦¦¦¦¦? | 2/3 [00:01<00:00, 1.99it/s]
processed: 2
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00, 1.53it/s]
processed: 3
The problem is that the output to stdout and stderr are processed asynchronously and separately in terms of new lines.
If say Jupyter receives on stderr the first line and then the "processed" output on stdout. Then once it receives an output on stderr to update the progress, it wouldn't go back and update the first line as it would only update the last line. Instead it will have to write a new line.
One workaround would be to output both to stdout instead:
import sys
from time import sleep
from tqdm import tqdm
values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
for i in values:
pbar.write('processed: %d' % (1 + i))
pbar.update(1)
sleep(1)
The output will change to (no more red):
processed: 1 | 0/3 [00:00<?, ?it/s]
processed: 2 | 0/3 [00:00<?, ?it/s]
processed: 3 | 2/3 [00:01<00:00, 1.99it/s]
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00, 1.53it/s]
Here we can see that Jupyter doesn't seem to clear until the end of the line. We could add another workaround for that by adding spaces. Such as:
import sys
from time import sleep
from tqdm import tqdm
values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
for i in values:
pbar.write('processed: %d%s' % (1 + i, ' ' * 50))
pbar.update(1)
sleep(1)
Which gives us:
processed: 1
processed: 2
processed: 3
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00, 1.53it/s]
It might in general be more straight forward not to have two outputs but update the description instead, e.g.:
import sys
from time import sleep
from tqdm import tqdm
values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
for i in values:
pbar.set_description('processed: %d' % (1 + i))
pbar.update(1)
sleep(1)
With the output (description updated while it's processing):
processed: 3: 100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00, 1.53it/s]
You can mostly get it to work fine with plain tqdm. But if tqdm_notebook works for you, just use that (but then you'd probably not read that far).
HTML
<a href="demoLink" id="myLink"> myLink </a>
<button onclick="fireLink(event)"> Call My Link </button>
JS
// click event listener of the link element --------------
document.getElementById('myLink').addEventListener("click", callLink);
function callLink(e) {
// code to fire
}
// function invoked by the button element ----------------
function fireLink(event) {
document.getElementById('myLink').click(); // script calls the "click" event of the link element
}
Pass bitmap to the saveImage Method, It will save your bitmap in the name of a saveBitmap, inside created test folder.
private void saveImage(Bitmap data) {
File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
if(!createFolder.exists())
createFolder.mkdir();
File saveImage = new File(createFolder,"saveBitmap.jpg");
try {
OutputStream outputStream = new FileOutputStream(saveImage);
data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and use this:
saveImage(bitmap);
*scanf()
family of functions return the number of values converted. So you should check to make sure sscanf()
returns 1 in your case. EOF
is returned for "input failure", which means that ssacnf()
will never return EOF
.
For sscanf()
, the function has to parse the format string, and then decode an integer. atoi()
doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.
You should use strtol()
or strtoul()
functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.
If you want an int
, you can always use strtol()
, and then check the returned value to see if it lies between INT_MIN
and INT_MAX
.
Point to Eclipse Juno Site, If not available add the site "Juno - http://download.eclipse.org/releases/juno"
Select and expand general purpose tools
A fail safe solution would be:
Referenced from https://stackoverflow.com/a/2273328/2062851
function getLastPathSegment($url) {
$path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
$pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
$pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash
if (substr($path, -1) !== '/') {
array_pop($pathTokens);
}
return end($pathTokens); // get the last segment
}
echo getLastPathSegment($_SERVER['REQUEST_URI']); //9393903
I think that this loop-based version might be the fastest factorial function.
function factorial(n, r = 1) {
while (n > 0) r *= n--;
return r;
}
// Default parameters `r = 1`,
// was introduced in ES6
And here is my reasoning:
for
loops and while
loops have similar performance, a for
loop without an initialization-expression and final-expression looks odd; probably better to write for(; n > 0;)
as while(n > 0)
n
and r
are used, so in theory less parameters means less time spent allocating memoryn
is zero - I've heard theories that computers are better at checking binary numbers (0 and 1) than they are at checking other integersThe first answer covers it.
Im guessing that somewhere down the line you may decide to store your info in a different class/structure. In that case you probably wouldn't want the results going in to an array from the split() method.
You didn't ask for it, but I'm bored, so here is an example, hope it's helpful.
This might be the class you write to represent a single person:
class Person {
public String firstName;
public String lastName;
public int id;
public int age;
public Person(String firstName, String lastName, int id, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.age = age;
}
// Add 'get' and 'set' method if you want to make the attributes private rather than public.
}
Then, the version of the parsing code you originally posted would look something like this: (This stores them in a LinkedList, you could use something else like a Hashtable, etc..)
try
{
String ruta="entrada.al";
BufferedReader reader = new BufferedReader(new FileReader(ruta));
LinkedList<Person> list = new LinkedList<Person>();
String line = null;
while ((line=reader.readLine())!=null)
{
if (!(line.equals("%")))
{
StringTokenizer st = new StringTokenizer(line, "*");
if (st.countTokens() == 4)
list.add(new Person(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken)));
else
// whatever you want to do to account for an invalid entry
// in your file. (not 4 '*' delimiters on a line). Or you
// could write the 'if' clause differently to account for it
}
}
reader.close();
}
There may be a simpler option, but you can use VLOOKUP to check if a value appears in a list (and VLOOKUP is a powerful formula to get to grips with anyway).
So for A1, you can set a conditional format using the following formula:
=NOT(ISNA(VLOOKUP(A1,$B:$B,1,FALSE)))
Copy and Paste Special > Formats to copy that conditional format to the other cells in column A.
What the above formula is doing:
Check your php error log which might be a separate file from your apache error log.
Find it by going to phpinfo()
and check for error_log attribute.
If it is not set. Set it: https://stackoverflow.com/a/12835262/445131
Maybe your post_max_size is too small for what you're trying to post, or one of the other max memory settings is too low.
if you just need a timestamp in unix /epoch time, this one line works:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
and depends only on datetime
works in python2 and python3
I'm late to the game but I just realize this: ax
can be replaced with plt.gca()
for those who are not using axes and just subplots.
Echoing @Mad Physicist answer, using the package PercentFormatter
it would be:
import matplotlib.ticker as mtick
plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(1))
#if you already have ticks in the 0 to 1 range. Otherwise see their answer
The single pipe, |, is one of the bitwise operators.
From Wikipedia:
In the C programming language family, the bitwise OR operator is "|" (pipe). Again, this operator must not be confused with its Boolean "logical or" counterpart, which treats its operands as Boolean values, and is written "||" (two pipes).
This is my solution which perfectly works starting from API 15. This solution keeps all default button click effects, like material RippleEffect
. I have not tested it on lower APIs, but it should work.
All you need to do, is:
1) Create a style which changes only colorAccent
:
<style name="Facebook.Button" parent="ThemeOverlay.AppCompat">
<item name="colorAccent">@color/com_facebook_blue</item>
</style>
I recommend using
ThemeOverlay.AppCompat
or your mainAppTheme
as parent, to keep the rest of your styles.
2) Add these two lines to your button
widget:
style="@style/Widget.AppCompat.Button.Colored"
android:theme="@style/Facebook.Button"
Sometimes your new
colorAccent
isn't showing in Android Studio Preview, but when you launch your app on the phone, the color will be changed.
<Button
android:id="@+id/sign_in_with_facebook"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/sign_in_facebook"
android:textColor="@android:color/white"
android:theme="@style/Facebook.Button" />
If you are mainly interested in implementing logic to the setter only:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
// [...]
export class MyClass implements OnChanges {
@Input() allowDay: boolean;
ngOnChanges(changes: SimpleChanges): void {
if(changes['allowDay']) {
this.updatePeriodTypes();
}
}
}
The import of SimpleChanges
is not needed if it doesn't matter which input property was changed or if you have only one input property.
otherwise:
private _allowDay: boolean;
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
get allowDay(): boolean {
// other logic
return this._allowDay;
}
I also had this problem. I think there is a bug in the way Flutter caches images. My guess is that when you first attempted to load pizza0.png
, it wasn't available, and Flutter has cached this failed result. Then, even after adding the correct image, Flutter still assumes it isn't available.
This is all guess-work, based on the fact that I had the same problem, and calling this once on app start fixed the problem for me:
imageCache.clear();
This clears the image cache, meaning that Flutter will then attempt to load the images fresh rather than search the cache.
PS I've also found that you need to call this whenever you change any existing images, for the same reason - Flutter will load the old cached version. The alternative is to rename the image.
script: it contains set of "scripting language" instructions which controls, runs other system programs, applications also it can be scheduled.
Program: it contains set of instructions, which performs certain task upon compilation of the program with the compiler.
Integrated Security=true;
doesn't work in all SQL providers, it throws an exception when used with the OleDb
provider.
So basically Integrated Security=SSPI;
is preferred since works with both SQLClient
& OleDB
provider.
Here's the full set of syntaxes according to MSDN - Connection String Syntax (ADO.NET)
I figured out what's going on.
When I load a page through a server side action (a url visit), and view the html returned from that action inside a Webview, that first action/page runs inside that Webview. However, when you click on any link that are action commands in your web app, these actions start a new browser. That is why cookie info gets lost because the first cookie information you set for Webview is gone, we have a seperate program here.
You have to intercept clicks on Webview so that browsing never leaves the app, everything stays inside the same Webview.
WebView webview = new WebView(this);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url); //this is controversial - see comments and other answers
return true;
}
});
setContentView(webview);
webview.loadUrl([MY URL]);
This fixes the problem.
If you click at the icon on the upper left corner, a drop-down menu will appear, and you can find the option to copy/paste from there.
//Vehicle is a function. But by naming conventions
//(first letter is uppercase), it is also an object
//constructor function ("class").
function Vehicle(numWheels) {
this.numWheels = numWheels;
}
//We can create new instances and check their types.
myRoadster = new Vehicle(4);
alert(myRoadster instanceof Vehicle);
I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.
import numpy as np
import random
import cv2
def sp_noise(image,prob):
'''
Add salt and pepper noise to image
prob: Probability of the noise
'''
output = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
if rdn < prob:
output[i][j] = 0
elif rdn > thres:
output[i][j] = 255
else:
output[i][j] = image[i][j]
return output
image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)
Here's a complete example of jHackTheRipper's answer for the TL;DR crowd. :-) In this case, I wanted to run g++-4.5 on an Ubuntu system that defaults to 4.6. As root
:
apt-get install g++-4.5
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 100
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.5 50
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 100
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.5 50
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.6 100
update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-4.5 50
update-alternatives --set g++ /usr/bin/g++-4.5
update-alternatives --set gcc /usr/bin/gcc-4.5
update-alternatives --set cpp-bin /usr/bin/cpp-4.5
Here, 4.6 is still the default (aka "auto mode"), but I explicitly switch to 4.5 temporarily (manual mode). To go back to 4.6:
update-alternatives --auto g++
update-alternatives --auto gcc
update-alternatives --auto cpp-bin
(Note the use of cpp-bin
instead of just cpp
. Ubuntu already has a cpp
alternative with a master link of /lib/cpp
. Renaming that link would remove the /lib/cpp
link, which could break scripts.)
Well, it's worth noting that they don't mean the same thing at all.
If the DEBUG symbol isn't defined, then in the first case the SetPrivateValue
itself won't be called... whereas in the second case it will exist, but any callers who are compiled without the DEBUG symbol will have those calls omitted.
If the code and all its callers are in the same assembly this difference is less important - but it means that in the first case you also need to have #if DEBUG
around the calling code as well.
Personally I'd recommend the second approach - but you do need to keep the difference between them clear in your head.
LINQ itself must be doing some serious optimization around the Count() method somehow.
Does this surprise you? I imagine that for IList
implementations, Count
simply reads the number of elements directly while Any
has to query the IEnumerable.GetEnumerator
method, create an instance and call MoveNext
at least once.
/EDIT @Matt:
I can only assume that the Count() extension method for IEnumerable is doing something like this:
Yes, of course it does. This is what I meant. Actually, it uses ICollection
instead of IList
but the result is the same.
getListView().smoothScrollToPositionFromTop(position,offset,duration);
Parameters
position -> Position to scroll to
offset ---->Desired distance in pixels of position from the top of the view when scrolling is finished
duration-> Number of milliseconds to use for the scroll
Note: From API 11.
HandlerExploit's answer was what I was looking for, but My listview is quite lengthy and also with alphabet scroller. Then I found that the same function can take other parameters as well :)
Edit:(From AFDs suggestion)
To position the current selection:
int h1 = mListView.getHeight();
int h2 = listViewRow.getHeight();
mListView.smoothScrollToPositionFromTop(position, h1/2 - h2/2, duration);
rsplit
should be up to the task:
In [1]: 'http://www.test.com/page/TEST2'.rsplit('/', 1)[1]
Out[1]: 'TEST2'
I had the same problem. You want to look the connection object supplied by the entity manager:
$conn = $em->getConnection();
You can then query/execute directly against it:
$statement = $conn->query('select foo from bar');
$num_rows_effected = $conn->exec('update bar set foo=1');
See the docs for the connection object at http://www.doctrine-project.org/api/dbal/2.0/doctrine/dbal/connection.html
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
The installer from the git homepage installs into /usr/local/git
by default. However, if you install XCode4, it will install a git version in /usr/bin
. To ensure you can easily upgrade from the website and use the latest git version, edit either your profile information to place /usr/local/git/bin
before /usr/bin
in the $PATH or edit /etc/paths
and insert /usr/local/git/bin
as the first entry.
It may help to someone at-least changing the order in /etc/paths worked for me.
Search and destroy (or move cautiously) any my.ini files (windows or program files), which is affecting the mysql service failure. also check port 3306 is used by using either netstat or portqry tool. this should help. Also if there is a file system issue you can run check disk.
You can use slice with no arguments to copy an array:
var foo,
bar;
foo = [3,1,2];
bar = foo.slice().sort();
You can primarily use Zoredache solution, but If you don't want to overwrite the output file you should write tee with -a option as follow :
ls -lR / | tee -a output.file
Execute command as www-data user: docker exec -t --user www-data container bash -c "ls -la"
Because you are doing integer division.
As @Noldorin says, if both operators are integers, then integer division is used.
The result 0.33333333 can't be represented as an integer, therefore only the integer part (0) is assigned to the result.
If any of the operators is a double
/ float
, then floating point arithmetic will take place. But you'll have the same problem if you do that:
int n = 1.0 / 3.0;
A simple way if you want to scroll down specific element
Call this function whenever you want to scroll down.
function scrollDown() {_x000D_
document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight_x000D_
}
_x000D_
ul{_x000D_
height: 100px;_x000D_
width: 200px;_x000D_
overflow-y: scroll;_x000D_
border: 1px solid #000;_x000D_
}
_x000D_
<ul id='scroll'>_x000D_
<li>Top Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Bottom Here</li>_x000D_
<li style="color: red">Bottom Here</li>_x000D_
</ul>_x000D_
_x000D_
<br />_x000D_
_x000D_
<button onclick='scrollDown()'>Scroll Down</button>
_x000D_
Something like this should do the trick (However, read after the snippet for more info)
CREATE PROCEDURE GetFilteredData()
BEGIN
DECLARE bDone INT;
DECLARE var1 CHAR(16); -- or approriate type
DECLARE Var2 INT;
DECLARE Var3 VARCHAR(50);
DECLARE curs CURSOR FOR SELECT something FROM somewhere WHERE some stuff;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TEMPORARY TABLE IF EXISTS tblResults;
CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
--Fld1 type,
--Fld2 type,
--...
);
OPEN curs;
SET bDone = 0;
REPEAT
FETCH curs INTO var1,, b;
IF whatever_filtering_desired
-- here for whatever_transformation_may_be_desired
INSERT INTO tblResults VALUES (var1, var2, var3 ...);
END IF;
UNTIL bDone END REPEAT;
CLOSE curs;
SELECT * FROM tblResults;
END
A few things to consider...
Concerning the snippet above:
More generally: trying to avoid needing a cursor.
I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.
Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.
With versions of cut
I know of, no, this is not possible. cut
is primarily useful for parsing files where the separator is not whitespace (for example /etc/passwd
) and that have a fixed number of fields. Two separators in a row mean an empty field, and that goes for whitespace too.
I would use SimpleDateFormat. Someone correct me if there is an easier way to make a monthed calendar though, I do this in code now and I'm not so sure.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public String formatMonth(int month, Locale locale) {
DateFormat formatter = new SimpleDateFormat("MMMM", locale);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, month-1);
return formatter.format(calendar.getTime());
}
-Covert .jar file to .zip (In windows just change the extension) -Unzip the .zip folder -You will get complete .java files
Take a look at this example from The Linux Documentation Project:
3.6 Sample: stderr and stdout 2 file
This will place every output of a program to a file. This is suitable sometimes for cron entries, if you want a command to pass in absolute silence.
rm -f $(find / -name core) &> /dev/null
That said, you can use this simple redirection:
/path/to/command &>/dev/null
Webkit seems to use internally display: table-row-group
for the tbody
tag.
There is currently a bug with setting height to it: https://github.com/w3c/csswg-drafts/issues/476
Let's hope it will be solved soon.
A few variants of Andrew Arnott's answer:
If you want to wait for an existing task and find out whether it completed or timed out, but don't want to cancel it if the timeout occurs:
public static async Task<bool> TimedOutAsync(this Task task, int timeoutMilliseconds)
{
if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
if (timeoutMilliseconds == 0) {
return !task.IsCompleted; // timed out if not completed
}
var cts = new CancellationTokenSource();
if (await Task.WhenAny( task, Task.Delay(timeoutMilliseconds, cts.Token)) == task) {
cts.Cancel(); // task completed, get rid of timer
await task; // test for exceptions or task cancellation
return false; // did not timeout
} else {
return true; // did timeout
}
}
If you want to start a work task and cancel the work if the timeout occurs:
public static async Task<T> CancelAfterAsync<T>( this Func<CancellationToken,Task<T>> actionAsync, int timeoutMilliseconds)
{
if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
var taskCts = new CancellationTokenSource();
var timerCts = new CancellationTokenSource();
Task<T> task = actionAsync(taskCts.Token);
if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
timerCts.Cancel(); // task completed, get rid of timer
} else {
taskCts.Cancel(); // timer completed, get rid of task
}
return await task; // test for exceptions or task cancellation
}
If you have a task already created that you want to cancel if a timeout occurs:
public static async Task<T> CancelAfterAsync<T>(this Task<T> task, int timeoutMilliseconds, CancellationTokenSource taskCts)
{
if (timeoutMilliseconds < 0 || (timeoutMilliseconds > 0 && timeoutMilliseconds < 100)) { throw new ArgumentOutOfRangeException(); }
var timerCts = new CancellationTokenSource();
if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, timerCts.Token)) == task) {
timerCts.Cancel(); // task completed, get rid of timer
} else {
taskCts.Cancel(); // timer completed, get rid of task
}
return await task; // test for exceptions or task cancellation
}
Another comment, these versions will cancel the timer if the timeout does not occur, so multiple calls will not cause timers to pile up.
sjb
env VAR=value myScript args ...
Regular expressions work well if needing to find a range of starting characters. The following finds all employee names starting with A, B, C or D and adds the “UPPER” call in case a name is in the database with a starting lowercase letter. My query works in Oracle (I did not test other DB's). The following would return for example:
Adams
adams
Dean
dean
This query also ignores case in the ORDER BY via the "lower" call:
SELECT employee_name
FROM employees
WHERE REGEXP_LIKE(UPPER(TRIM(employee_name)), '^[A-D]')
ORDER BY lower(employee_name)
You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance
before trying to spy on the method.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const instance = app.instance()
const spy = jest.spyOn(instance, 'myClickFunc')
instance.forceUpdate();
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html
Maybe you can use a work around and try something like:
import datetime
#import mysql
import MySQLdb
conn = MySQLdb.connect(host = '127.0.0.1',user = 'someUser', passwd = 'foobar',db = 'foobardb')
cursor = conn.cursor()
I had the same problem too. Then i realized that in the MainPageServlet the urlPatterns parameter in @WebServlet annotation contained "/", because i wanted to forward to the MainPage if the user entered the section www.site.com/ . When i tried to open the css file from the browser, the url was www.site.com/css/desktop.css, but the page content was THE PAGE MainPage.jsp. So, i removed the "/" urlPattern and now i can use CSS files in my jsp file using one of the most common solutions (${pageContext.request.contextPath}/css/desktop.css
).
Make sure your servlet doesn't contain the "/" urlPattern.
I hope this worked for u too,
- Axel Montini
try this:
ffmpeg -i "path to file" -f null /dev/null 2>&1 | grep 'frame=' | cut -f 2 -d ' '
Here's an alternative to pandas library using Python's built-in csv module.
import csv
from pprint import pprint
with open('foo.csv', 'rb') as f:
reader = csv.reader(f)
headers = reader.next()
column = {h:[] for h in headers}
for row in reader:
for h, v in zip(headers, row):
column[h].append(v)
pprint(column) # Pretty printer
will print
{'Date': ['2012-06-11',
'2012-06-12',
'2012-06-13',
'2012-06-14',
'2012-06-15',
'2012-06-16',
'2012-06-17'],
'factor_1': ['1.255', '1.258', '1.249', '1.253', '1.258', '1.263', '1.264'],
'factor_2': ['1.548', '1.554', '1.552', '1.556', '1.552', '1.558', '1.572'],
'price': ['1600.20',
'1610.02',
'1618.07',
'1624.40',
'1626.15',
'1626.15',
'1626.15']}
Easy, \n
needs to be in the string.
I have just tested in Postgres 9.1 a solution which is close to Oracle ROWNUM:
select row_number() over() as id, t.*
from information_schema.tables t;
This is a sample code to take two inputs seperated by split command and delimiter as ","
>>> var1, var2 = input("enter two numbers:").split(',')
>>>enter two numbers:2,3
>>> var1
'2'
>>> var2
'3'
Other variations of delimiters that can be used are as below :
var1, var2 = input("enter two numbers:").split(',')
var1, var2 = input("enter two numbers:").split(';')
var1, var2 = input("enter two numbers:").split('/')
var1, var2 = input("enter two numbers:").split(' ')
var1, var2 = input("enter two numbers:").split('~')
I just created a jQuery function to load an image using jQuerys Deferred Object which makes it very easy to react on load/error event:
$.fn.extend({
loadImg: function(url, timeout) {
// init deferred object
var defer = $.Deferred(),
$img = this,
img = $img.get(0),
timer = null;
// define load and error events BEFORE setting the src
// otherwise IE might fire the event before listening to it
$img.load(function(e) {
var that = this;
// defer this check in order to let IE catch the right image size
window.setTimeout(function() {
// make sure the width and height are > 0
((that.width > 0 && that.height > 0) ?
defer.resolveWith :
defer.rejectWith)($img);
}, 1);
}).error(function(e) {
defer.rejectWith($img);
});
// start loading the image
img.src = url;
// check if it's already in the cache
if (img.complete) {
defer.resolveWith($img);
} else if (0 !== timeout) {
// add a timeout, by default 15 seconds
timer = window.setTimeout(function() {
defer.rejectWith($img);
}, timeout || 15000);
}
// return the promise of the deferred object
return defer.promise().always(function() {
// stop the timeout timer
window.clearTimeout(timer);
timer = null;
// unbind the load and error event
this.off("load error");
});
}
});
Usage:
var image = $('<img />').loadImg('http://www.google.com/intl/en_com/images/srpr/logo3w.png')
.done(function() {
alert('image loaded');
$('body').append(this);
}).fail(function(){
alert('image failed');
});
See it working at: http://jsfiddle.net/roberkules/AdWZj/
i tried everything/....but only this thing worked for me:
To fix this, I went to help - Install New Software... - from the "work with" drop-down box I selected http://dl-ssl.google.com/android/eclipse/ - I then check marked "Developer Tools" and hit the Next button. I then followed the prompts and it basically did a re-install. It took less than 5 minutes. That resolved the error.
Now Im back up and running, and I got the lastest version of Eclipse.
Thanks a lot Nadir
There is a static method System.IO.File.WriteAllBytes
INSERT INTO Test([col1],[col2]) (
SELECT
a.Name AS [col1],
b.sub AS [col2]
FROM IdTable b
INNER JOIN Nametable a ON b.no = a.no
)
I needed to have a button handler that created a form post to another application within the client's browser. I landed on this question but didn't see an answer that suited my scenario. This is what I came up with:
protected void Button1_Click(object sender, EventArgs e)
{
var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
<input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" />
<input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" />
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
Response.Write(formPostText);
}
If fptr
is NULL
, then you don't have an open file. Therefore, you can't freopen
it, you should just fopen
it.
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}
Another recursive solution, that works for arrays/lists and objects, or a mixture of both:
function deepSearchByKey(object, originalKey, matches = []) {
if(object != null) {
if(Array.isArray(object)) {
for(let arrayItem of object) {
deepSearchByKey(arrayItem, originalKey, matches);
}
} else if(typeof object == 'object') {
for(let key of Object.keys(object)) {
if(key == originalKey) {
matches.push(object);
} else {
deepSearchByKey(object[key], originalKey, matches);
}
}
}
}
return matches;
}
usage:
let result = deepSearchByKey(arrayOrObject, 'key'); // returns an array with the objects containing the key
I found this to be more cross-browser compatible:
$(document).keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('You pressed a "enter" key in somewhere');
}
});
Demo :
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Based on your question:
<connectionStrings>
<add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Refer links:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
Retrive connection string from web.config file:
write the below code in your file where you want;
string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;
SqlConnection con = new SqlConnection(connstring);
or you can go in your way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Note:
The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)
Try Winhttrack
...offline browser utility.
It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.
WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...
The column widths set to fit its content I have used the bellow statement, It resolved my issue.
First Step :
RadGridViewName.AutoSize = true;
Second Step :
// This mode fit in the header text and column data for all visible rows.
this.grdSpec.MasterTemplate.BestFitColumns();
Third Step :
for (int i = 0; i < grdSpec.Columns.Count; i++)
{
// The column width adjusts to fit the contents all cells in the control.
grdSpec.Columns[i].AutoSizeMode = BestFitColumnMode.AllCells;
}
It's ES6 Spread_operator
and Destructuring_assignment
.
<div {...this.props}>
Content Here
</div>
It's equal to Class Component
const person = {
name: "xgqfrms",
age: 23,
country: "China"
};
class TestDemo extends React.Component {
render() {
const {name, age, country} = {...this.props};
// const {name, age, country} = this.props;
return (
<div>
<h3> Person Information: </h3>
<ul>
<li>name={name}</li>
<li>age={age}</li>
<li>country={country}</li>
</ul>
</div>
);
}
}
ReactDOM.render(
<TestDemo {...person}/>
, mountNode
);
or Function component
const props = {
name: "xgqfrms",
age: 23,
country: "China"
};
const Test = (props) => {
return(
<div
name={props.name}
age={props.age}
country={props.country}>
Content Here
<ul>
<li>name={props.name}</li>
<li>age={props.age}</li>
<li>country={props.country}</li>
</ul>
</div>
);
};
ReactDOM.render(
<div>
<Test {...props}/>
<hr/>
<Test
name={props.name}
age={props.age}
country={props.country}
/>
</div>
, mountNode
);
What is the best practice on where the logic for the @foreach should be at?
Nowhere, just get rid of it. You could use editor or display templates.
So for example:
@foreach (var item in Model.Foos)
{
<div>@item.Bar</div>
}
could perfectly fine be replaced by a display template:
@Html.DisplayFor(x => x.Foos)
and then you will define the corresponding display template (if you don't like the default one). So you would define a reusable template ~/Views/Shared/DisplayTemplates/Foo.cshtml
which will automatically be rendered by the framework for each element of the Foos collection (IEnumerable<Foo> Foos { get; set; }
):
@model Foo
<div>@Model.Bar</div>
Obviously exactly the same conventions apply for editor templates which should be used in case you want to show some input fields allowing you to edit the view model in contrast to just displaying it as readonly.
Attempting to debug in RubyMine using Ubuntu 18.04, Ruby 2.6.*, Rails 5, & RubyMine 2019.1.1, I ran into the same issue.
To resolve the issue, I uncommented the mini_racer
line from my Gemfile
and then ran bundle
:
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
Change to:
# See https://github.com/rails/execjs#readme for more supported runtimes
gem 'mini_racer', platforms: :ruby
I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
End Sub
You can stream download too which will consume significantly less resource. example:
$readableStream = fopen('test.zip', 'rb');
$writableStream = fopen('php://output', 'wb');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.zip"');
stream_copy_to_stream($readableStream, $writableStream);
ob_flush();
flush();
In the above example, I am downloading a test.zip (which was actually the android studio zip on my local machine).
php://output is a write-only stream (generally used by echo or print).
after that, you just need to set the required headers and call stream_copy_to_stream(source, destination).
stream_copy_to_stream() method acts as a pipe which takes the input from the source stream (read stream) and pipes it to the destination stream (write stream) and it also avoid the issue of allowed memory exhausted so you can actually download files that are bigger than your PHP memory_limit
.
you can always use new stdClass()
. Example code:
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
Also as of PHP 5.4 you can get same output with:
$object = (object) ['property' => 'Here we go'];
Python doesn't have a built-in equivalent to enum
, and other answers have ideas for implementing your own (you may also be interested in the over the top version in the Python cookbook).
However, in situations where an enum
would be called for in C, I usually end up just using simple strings: because of the way objects/attributes are implemented, (C)Python is optimized to work very fast with short strings anyway, so there wouldn't really be any performance benefit to using integers. To guard against typos / invalid values you can insert checks in selected places.
ANIMALS = ['cat', 'dog', 'python']
def take_for_a_walk(animal):
assert animal in ANIMALS
...
(One disadvantage compared to using a class is that you lose the benefit of autocomplete)
You can do it with dynamic_cast
(at least for polymorphic types).
Actually, on second thought--you can't tell if it is SPECIFICALLY a particular type with dynamic_cast
--but you can tell if it is that type or any subclass thereof.
template <class DstType, class SrcType>
bool IsType(const SrcType* src)
{
return dynamic_cast<const DstType*>(src) != nullptr;
}
I did this before using the MSXML library and then using the XMLHttpRequest object, see here.
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
Here you have a very good tutorial, that explains, how to use the new grid classes in Bootstrap 3.
It also covers mixins etc.
Alternatively, if using javax.net.ssl.trustStore for specifying the location of your truststore does not work ( as it did in my case for two way authentication ), you can also use SSLContextBuilder as shown in the example below. This example also includes how to create a httpclient as well to show how the SSL builder would work.
SSLContextBuilder sslcontextbuilder = SSLContexts.custom();
sslcontextbuilder.loadTrustMaterial(
new File("C:\\path to\\truststore.jks"), //path to jks file
"password".toCharArray(), //enters in the truststore password for use
new TrustSelfSignedStrategy() //will trust own CA and all self-signed certs
);
SSLContext sslcontext = sslcontextbuilder.build(); //load trust store
SSLConnectionSocketFactory sslsockfac = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsockfac).build(); //sets up a httpclient for use with ssl socket factory
try {
HttpGet httpget = new HttpGet("https://localhost:8443"); //I had a tomcat server running on localhost which required the client to have their trust cert
System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
In case you have a local variable with the same name, you might want to use the globals()
function.
globals()['your_global_var'] = 42
As stated already within another answer it is not recommended to catch a NullPointerException. However you definitely could catch it, like the following example shows.
public class Testclass{
public static void main(String[] args) {
try {
doSomething();
} catch (NullPointerException e) {
System.out.print("Caught the NullPointerException");
}
}
public static void doSomething() {
String nullString = null;
nullString.endsWith("test");
}
}
Although a NPE can be caught you definitely shouldn't do that but fix the initial issue, which is the Check_Circular method.
You've correctly diagnosed your problem, so good job. Once you call into your search code, the for loop just keeps right on going.
I'm a big fan of https://github.com/caolan/async, and it serves me well. Basically with it you'd end up with something like:
var async = require('async')
async.eachSeries(Object.keys(config), function (key, next){
search(config[key].query, function(err, result) { // <----- I added an err here
if (err) return next(err) // <---- don't keep going if there was an error
var json = JSON.stringify({
"result": result
});
results[key] = {
"result": result
}
next() /* <---- critical piece. This is how the forEach knows to continue to
the next loop. Must be called inside search's callback so that
it doesn't loop prematurely.*/
})
}, function(err) {
console.log('iterating done');
});
I hope that helps!
Drag a tooltip control from the toolbox onto your form. You don't really need to give it any properties other than a name. Then, in the properties of the control you wish to have a tooltip on, look for a new property with the name of the tooltip control you just added. It will by default give you a tooltip when the cursor hovers the control.
Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex
attribute on the canvas element (as suggested by hobberwickey).
You can't focus a canvas element. A simple work around this, would be to make your "own" focus.
var lastDownTarget, canvas;
window.onload = function() {
canvas = document.getElementById('canvas');
document.addEventListener('mousedown', function(event) {
lastDownTarget = event.target;
alert('mousedown');
}, false);
document.addEventListener('keydown', function(event) {
if(lastDownTarget == canvas) {
alert('keydown');
}
}, false);
}
java.util.Date.from( // Transfer the moment in UTC, truncating any microseconds or nanoseconds to milliseconds.
Instant.now() ; // Capture current moment in UTC, with resolution as fine as nanoseconds.
)
Though there was no point in that code above. Both java.util.Date
and Instant
represent a moment in UTC, always in UTC. Code above has same effect as:
new java.util.Date() // Capture current moment in UTC.
No benefit here to using ZonedDateTime
. If you already have a ZonedDateTime
, adjust to UTC by extracting a Instant
.
java.util.Date.from( // Truncates any micros/nanos.
myZonedDateTime.toInstant() // Adjust to UTC. Same moment, same point on the timeline, different wall-clock time.
)
The Answer by ssoltanid correctly addresses your specific question, how to convert a new-school java.time object (ZonedDateTime
) to an old-school java.util.Date
object. Extract the Instant
from the ZonedDateTime and pass to java.util.Date.from()
.
Note that you will suffer data loss, as Instant
tracks nanoseconds since epoch while java.util.Date
tracks milliseconds since epoch.
Your Question and comments raise other issues.
Your servers should have their host OS set to UTC as a best practice generally. The JVM picks up on this host OS setting as its default time zone, in the Java implementations that I'm aware of.
But you should never rely on the JVM’s current default time zone. Rather than pick up the host setting, a flag passed when launching a JVM can set another time zone. Even worse: Any code in any thread of any app at any moment can make a call to java.util.TimeZone::setDefault
to change that default at runtime!
Timestamp
TypeAny decent database and driver should automatically handle adjusting a passed date-time to UTC for storage. I do not use Cassandra, but it does seem to have some rudimentary support for date-time. The documentation says its Timestamp
type is a count of milliseconds from the same epoch (first moment of 1970 in UTC).
Furthermore, Cassandra accepts string inputs in the ISO 8601 standard formats. Fortunately, java.time uses ISO 8601 formats as its defaults for parsing/generating strings. The Instant
class’ toString
implementation will do nicely.
But first we need to reduce the nanosecond precision of ZonedDateTime to milliseconds. One way is to create a fresh Instant using milliseconds. Fortunately, java.time has some handy methods for converting to and from milliseconds.
Here is some example code in Java 8 Update 60.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
…
Instant instant = zdt.toInstant();
Instant instantTruncatedToMilliseconds = Instant.ofEpochMilli( instant.toEpochMilli() );
String fodderForCassandra = instantTruncatedToMilliseconds.toString(); // Example: 2015-08-18T06:36:40.321Z
Or according to this Cassandra Java driver doc, you can pass a java.util.Date
instance (not to be confused with java.sqlDate
). So you could make a j.u.Date from that instantTruncatedToMilliseconds
in the code above.
java.util.Date dateForCassandra = java.util.Date.from( instantTruncatedToMilliseconds );
If doing this often, you could make a one-liner.
java.util.Date dateForCassandra = java.util.Date.from( zdt.toInstant() );
But it would be neater to create a little utility method.
static public java.util.Date toJavaUtilDateFromZonedDateTime ( ZonedDateTime zdt ) {
Instant instant = zdt.toInstant();
// Data-loss, going from nanosecond resolution to milliseconds.
java.util.Date utilDate = java.util.Date.from( instant ) ;
return utilDate;
}
Notice the difference in all this code than in the Question. The Question’s code was trying to adjust the time zone of the ZonedDateTime instance to UTC. But that is not necessary. Conceptually:
ZonedDateTime = Instant + ZoneId
We just extract the Instant part, which is already in UTC (basically in UTC, read the class doc for precise details).
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
As others have pointed out, there are many web frameworks for Python.
But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:
Rename your script to index.cgi
. You also need to execute chmod +x index.cgi
to give it execution privileges.
Add these 2 lines in the beginning of the file:
#!/usr/bin/python print('Content-type: text/html\r\n\r')
After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.
Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python
might work instead.
http://rusanu.com/2006/01/30/how-long-should-i-expect-alter-databse-set-enable_broker-to-run/
alter database [<dbname>] set enable_broker with rollback immediate;
You can use Oracle's SQL Developer tool to do that (My Oracle DB version is 11). While creating a table choose Advanced option and click on the Identity Column tab at the bottom and from there choose Column Sequence. This will generate a AUTO_INCREMENT column (Corresponding Trigger and Squence) for you.
This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror
condition image URL, e.g. you might want to programatically set the url
parameter in CSS.
The trick is that image loading is asynchronous by nature so the onerror
doesn't happen sunchronously, i.e. if you call returnPhotoURL
it immediately returns undefined
bcs the asynchronous method of loading/handling the image load just began.
So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:
returnPhotoURL().then(function(value){
doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
});
function returnPhotoURL(){
return new Promise(function(resolve, reject){
var img = new Image();
//if the user does not have a photoURL let's try and get one from gravatar
if (!firebase.auth().currentUser.photoURL) {
//first we have to see if user han an email
if(firebase.auth().currentUser.email){
//set sign-in-button background image to gravatar url
img.addEventListener('load', function() {
resolve (getGravatar(firebase.auth().currentUser.email, 48));
}, false);
img.addEventListener('error', function() {
resolve ('//rack.pub/media/fallbackImage.png');
}, false);
img.src = getGravatar(firebase.auth().currentUser.email, 48);
} else {
resolve ('//rack.pub/media/fallbackImage.png');
}
} else {
img.addEventListener('load', function() {
resolve (firebase.auth().currentUser.photoURL);
}, false);
img.addEventListener('error', function() {
resolve ('https://rack.pub/media/fallbackImage.png');
}, false);
img.src = firebase.auth().currentUser.photoURL;
}
});
}
The following is nasty, but serves to demonstrate how you can treat functions like any other kind of object.
var foo = function () { alert('default function'); }
function pickAFunction(a_or_b) {
var funcs = {
a: function () {
alert('a');
},
b: function () {
alert('b');
}
};
foo = funcs[a_or_b];
}
foo();
pickAFunction('a');
foo();
pickAFunction('b');
foo();
A maybe not-so-elegant method, which I think is just a variation of what some other people have said, is to just hardcode it. Many journals have a template that in some way allows for table footnotes, so I try to keep things pretty basic. Although, there really are some incredible packages already out there, and I think this thread does a good job of pointing that out.
\documentclass{article}
\begin{document}
\begin{table}[!th]
\renewcommand{\arraystretch}{1.3} % adds row cushion
\caption{Data, level$^a$, and sources$^b$}
\vspace{4mm}
\centering
\begin{tabular}{|l|l|c|c|}
\hline
\textbf{Data} & \textbf{Description} & \textbf{Level} & \textbf{Source} \\
\hline
\hline
Data1 & Description. . . . . . . . . . . . . . . . . . & cnty & USGS \\
\hline
Data2 & Description. . . . . . . . . . . . . . . . . . & MSA & USGS \\
\hline
Data3 & Description. . . . . . . . . . . . . . . . . . & cnty & Census \\
\hline
\end{tabular}
\end{table}
\footnotesize{$^a$ The smallest spatial unit is county, $^b$ more details in appendix A}\\
\end{document}
opt
is new for ruby 1.9. The various options are documented in IO.new
: www.ruby-doc.org/core/IO.html
SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into.
If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it will append the new data by default but you can adjust that (edit mappings) so it will delete all existing data.
I use this all the time and it works fairly well.
Suppose I have Hashmap with key datatype as KeyDataType and value datatype as ValueDataType
HashMap<KeyDataType,ValueDataType> list;
Add all items you needed to it. Now you can retrive all hashmap keys to a list by.
KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
So, now you got your all keys in an array mkeys[]
you can now retrieve any value by calling
list.get(mkeys[position]);
It is going to be prettier if you format the seconds output like:
echo "Process took ". number_format(microtime(true) - $start, 2). " seconds.";
will print
Process took 6.45 seconds.
This is much better than
Process took 6.4518549156189 seconds.
This function creates a temporary form, then send data using jQuery :
function postToIframe(data,url,target){
$('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
$.each(data,function(n,v){
$('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
});
$('#postToIframe').submit().remove();
}
target is the 'name' attr of the target iFrame, and data is a JS object :
data={last_name:'Smith',first_name:'John'}
There was the very easy way to list your data :
server.get('/userlist' , function (req , res) {
User.find({}).then(function (users) {
res.send(users);
});
});
As already said, only one element can have a specific ID. Use classes instead. Here is jQuery-free version to remove the nodes:
var form = document.getElementById('your-form-id');
var spans = form.getElementsByTagName('span');
for(var i = spans.length; i--;) {
var span = spans[i];
if(span.className.match(/\btheclass\b/)) {
span.parentNode.removeChild(span);
}
}
getElementsByTagName
is the most cross-browser-compatible method that can be used here. getElementsByClassName
would be much better, but is not supported by Internet Explorer <= IE 8.
java.awt.Desktop
is the class you're looking for.
import java.awt.Desktop;
import java.net.URI;
// ...
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("http://www.example.com"));
}
xargs fails with with backslashes, quotes. It needs to be something like
ls -1 |tr \\n \\0 |xargs -0 -iTHIS echo "THIS is a file."
xargs -0 option:
-0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
ls -1
terminates the items with newline characters, so tr
translates them into null characters.
This approach is about 50 times slower than iterating manually with for ...
(see Michael Aaron Safyans answer) (3.55s vs. 0.066s). But for other input commands like locate, find, reading from a file (tr \\n \\0 <file
) or similar, you have to work with xargs
like this.
I just figure it out lately on how easy it is to make your bootstrap v3.1.1 being non-responsive. This includes navbars to not to collpase. I don't know if everyone knows this but I'd like to share it.
Two Steps to a Non-responsive Bootsrap v3.1.1
First, create a css file name it as non-responsive.css. Make sure to append it to your themes or link right after the bootstrap css files.
Second, paste this code to your non-responsive.css:
/* Template-specific stuff
*
* Customizations just for the template; these are not necessary for anything
* with disabling the responsiveness.
*/
/* Account for fixed navbar */
body {
min-width: 970px;
padding-top: 70px;
padding-bottom: 30px;
}
/* Finesse the page header spacing */
.page-header {
margin-bottom: 30px;
}
.page-header .lead {
margin-bottom: 10px;
}
/* Non-responsive overrides
*
* Utilitze the following CSS to disable the responsive-ness of the container,
* grid system, and navbar.
*/
/* Reset the container */
.container {
width: 970px;
max-width: none !important;
}
/* Demonstrate the grids */
.col-xs-4 {
padding-top: 15px;
padding-bottom: 15px;
background-color: #eee;
background-color: rgba(86,61,124,.15);
border: 1px solid #ddd;
border: 1px solid rgba(86,61,124,.2);
}
.container .navbar-header,
.container .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
/* Always float the navbar header */
.navbar-header {
float: left;
}
/* Undo the collapsing navbar */
.navbar-collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-toggle {
display: none;
}
.navbar-collapse {
border-top: 0;
}
.navbar-brand {
margin-left: -15px;
}
/* Always apply the floated nav */
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding: 15px;
}
/* Redeclare since we override the float above */
.navbar-nav.navbar-right {
float: right;
}
/* Undo custom dropdowns */
.navbar .navbar-nav .open .dropdown-menu {
position: absolute;
float: left;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-width: 0 1px 1px;
border-radius: 0 0 4px 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #333;
}
.navbar .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar .navbar-nav .open .dropdown-menu > li > a:focus,
.navbar .navbar-nav .open .dropdown-menu > .active > a,
.navbar .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff !important;
background-color: #428bca !important;
}
.navbar .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #999 !important;
background-color: transparent !important;
}
That's all and Enjoy..^^
Source: non-responsive.css from the example at getbootstrap.com.
You can use JavaScript CallBak like this:
var a;
function function1(callback) {
console.log("First comeplete");
a = "Some value";
callback();
}
function function2(){
console.log("Second comeplete:", a);
}
function1(function2);
Or Java Script Promise:
let promise = new Promise(function(resolve, reject) {
// do function1 job
let a = "Your assign value"
resolve(a);
});
promise.then(
function(a) {
// do function2 job with function1 return value;
console.log("Second comeplete:", a);
},
function(error) {
console.log("Error found");
});
Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild
ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers
parameter. Then each process will start 25 threads determined by ThreadsPerChild
parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit
parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients
is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients
. This also means that if I set MaxClients
to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient
parameter. In this case, we need to also increase ServerLimit
to 1000/25 i.e. MaxClients/ThreadsPerChild=40
So this is the optmized configuration to server 1000 clients
<IfModule mpm_worker_module>
ServerLimit 40
StartServers 2
MaxClients 1000
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
You can use HttpPost, there are methods to add Header to the Request.
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");
HttpResponse response = httpclient.execute(httpPost);
This is an aggregation problem, not a reshaping problem as the question originally suggested -- we wish to aggregate each column into a mean and standard deviation by ID. There are many packages that handle such problems. In the base of R it can be done using aggregate
like this (assuming DF
is the input data frame):
ag <- aggregate(. ~ ID, DF, function(x) c(mean = mean(x), sd = sd(x)))
Note 1: A commenter pointed out that ag
is a data frame for which some columns are matrices. Although initially that may seem strange, in fact it simplifies access. ag
has the same number of columns as the input DF
. Its first column ag[[1]]
is ID
and the ith column of the remainder ag[[i+1]]
(or equivalanetly ag[-1][[i]]
) is the matrix of statistics for the ith input observation column. If one wishes to access the jth statistic of the ith observation it is therefore ag[[i+1]][, j]
which can also be written as ag[-1][[i]][, j]
.
On the other hand, suppose there are k
statistic columns for each observation in the input (where k=2 in the question). Then if we flatten the output then to access the jth statistic of the ith observation column we must use the more complex ag[[k*(i-1)+j+1]]
or equivalently ag[-1][[k*(i-1)+j]]
.
For example, compare the simplicity of the first expression vs. the second:
ag[-1][[2]]
## mean sd
## [1,] 36.333 10.2144
## [2,] 32.250 4.1932
## [3,] 43.500 4.9497
ag_flat <- do.call("data.frame", ag) # flatten
ag_flat[-1][, 2 * (2-1) + 1:2]
## Obs_2.mean Obs_2.sd
## 1 36.333 10.2144
## 2 32.250 4.1932
## 3 43.500 4.9497
Note 2: The input in reproducible form is:
Lines <- "ID Obs_1 Obs_2 Obs_3
1 43 48 37
1 27 29 22
1 36 32 40
2 33 38 36
2 29 32 27
2 32 31 35
2 25 28 24
3 45 47 42
3 38 40 36"
DF <- read.table(text = Lines, header = TRUE)
You are printing a formatted string. The {0} means to insert the first parameter following the format string; in this case the value associated with the key "rtf".
For String.Format, which is similar, if you had something like
// Format string {0} {1}
String.Format("This {0}. The value is {1}.", "is a test", 42 )
you'd create a string "This is a test. The value is 42".
You can also use expressions, and print values out multiple times:
// Format string {0} {1} {2}
String.Format("Fib: {0}, {0}, {1}, {2}", 1, 1+1, 1+2)
yielding "Fib: 1, 1, 2, 3"
See more at http://msdn.microsoft.com/en-us/library/txafckwd.aspx, which talks about composite formatting.
CASE TO_CHAR(META.RHCONTRATOSFOLHA.CONTRATO)
WHEN '91' AND TO_CHAR(META.RHCONTRATOSFOLHA.UNIDADE) = '0001' THEN '91RJ'
WHEN '91' AND TO_CHAR(META.RHCONTRATOSFOLHA.UNIDADE) = '0002' THEN '91SP'
END CONTRATO,
00905. 00000 - "missing keyword"
*Cause:
*Action:
Erro na linha: 15 Coluna: 11
declare @nReturn int = 0 EXEC @nReturn = Stored Procedures
Wikipedia makes heavy use of this feature like this:
<a href="#History">[...]</a>
<span class="mw-headline" id="History">History</span>
And Wikipedia is working for everybody, so I would feel safe sticking with this form.
Also don't forget, you can use this not only with spans but with divs or even table cells, and then you have access to the :target pseudo-class on the element. Just watch out not to change the width, like with bold text, cause that moves content around, which is disturbing.
Named anchors - my vote is to avoid:
@dsimcha wrote: Counting sort: When you are sorting integers with a limited range
I would change that to:
Counting sort: When you sort positive integers (0 - Integer.MAX_VALUE-2 due to the pigeonhole).
You can always get the max and min values as an efficiency heuristic in linear time as well.
Also you need at least n extra space for the intermediate array and it is stable obviously.
/**
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
(even though it actually will allow to MAX_VALUE-2) see: Do Java arrays have a maximum size?
Also I would explain that radix sort complexity is O(wn) for n keys which are integers of word size w. Sometimes w is presented as a constant, which would make radix sort better (for sufficiently large n) than the best comparison-based sorting algorithms, which all perform O(n log n) comparisons to sort n keys. However, in general w cannot be considered a constant: if all n keys are distinct, then w has to be at least log n for a random-access machine to be able to store them in memory, which gives at best a time complexity O(n log n). (from wikipedia)
Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.
http://iphone.trac.wordpress.org/browser/trunk
The files you want are:
Then to show it use something like:
[[WPActivityIndicator sharedActivityIndicator] show];
And hide with:
[[WPActivityIndicator sharedActivityIndicator] hide];
You can use a Handler to post runnable code. This technique is outlined very nicely here: https://guides.codepath.com/android/Repeating-Periodic-Tasks
You can try this:
SELECT * FROM MYTABLE WHERE DATE BETWEEN '03/10/2014 06:25:00' and '03/12/2010 6:25:00'
Just use the function plot
as follows
figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
lets say you have a model called Book and on it a field called 'cover_pic', in that case, you can do the following to compress the image:
from PIL import Image
b = Book.objects.get(title='Into the wild')
image = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)
hope it helps to anyone stumbling upon it.
I know this is a bit more than the OP asked for, However I had the pieces to the following url, and was looking for a simple way to join them:
>>> url = 'https://api.foo.com/orders/bartag?spamStatus=awaiting_spam&page=1&pageSize=250'
Doing some looking around:
>>> split = urlparse.urlsplit(url)
>>> split
SplitResult(scheme='https', netloc='api.foo.com', path='/orders/bartag', query='spamStatus=awaiting_spam&page=1&pageSize=250', fragment='')
>>> type(split)
<class 'urlparse.SplitResult'>
>>> dir(split)
['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_asdict', '_fields', '_make', '_replace', 'count', 'fragment', 'geturl', 'hostname', 'index', 'netloc', 'password', 'path', 'port', 'query', 'scheme', 'username']
>>> split[0]
'https'
>>> split = (split[:])
>>> type(split)
<type 'tuple'>
So in addition to the path joining which has already been answered in the other answers, To get what I was looking for I did the following:
>>> split
('https', 'api.foo.com', '/orders/bartag', 'spamStatus=awaiting_spam&page=1&pageSize=250', '')
>>> unsplit = urlparse.urlunsplit(split)
>>> unsplit
'https://api.foo.com/orders/bartag?spamStatus=awaiting_spam&page=1&pageSize=250'
According to the documentation it takes EXACTLY a 5 part tuple.
With the following tuple format:
scheme 0 URL scheme specifier empty string
netloc 1 Network location part empty string
path 2 Hierarchical path empty string
query 3 Query component empty string
fragment 4 Fragment identifier empty string
I think what you may be after is the CSS property touch-action. You just need a CSS rule like this:
html, body {touch-action: none;}
You will see it has pretty good support (https://caniuse.com/#feat=mdn-css_properties_touch-action_none), including Safari, as well as back to IE10.
I used this format - but...I found I had to run it three or more times to get it to actually change every instance which I found extremely strange. Running it once would change some in each file but not all. Running exactly the same string two-four times would catch all instances.
find . -type f -name '*.txt' -exec sed -i '' s/thistext/newtext/ {} +
Personally I sanitize all my data with some PHP libraries before going into the database so there's no need for another XSS filter for me.
From AngularJS 1.0.8
directives.directive('ngBindHtmlUnsafe', [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
}
}]);
To use:
<div ng-bind-html-unsafe="group.description"></div>
To disable $sce
:
app.config(['$sceProvider', function($sceProvider) {
$sceProvider.enabled(false);
}]);
i want to know if my memory reduction efforts actually help in reducing memory
Following up on this comment, here's what you should do: Try to produce a memory problem - Write code that creates all these objects and graudally increase the upper limit until you ran into a problem (Browser crash, Browser freeze or an Out-Of-memory error). Ideally you should repeat this experiment with different browsers and different operating system.
Now there are two options: option 1 - You didn't succeed in producing the memory problem. Hence, you are worrying for nothing. You don't have a memory issue and your program is fine.
option 2- you did get a memory problem. Now ask yourself whether the limit at which the problem occurred is reasonable (in other words: is it likely that this amount of objects will be created at normal use of your code). If the answer is 'No' then you're fine. Otherwise you now know how many objects your code can create. Rework the algorithm such that it does not breach this limit.
Neither. You set the isolation level to READ UNCOMMITTED
which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.
This is what I did to get formatted date from front end
@RequestMapping(value = "/{dateString}", method = RequestMethod.GET)
@ResponseBody
public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) {
return OK;
}
You can use it to get what you want.
@Ramiz Uddin's answer definitely deserves more visibility :
cmd /K python "$(FULL_CURRENT_PATH)"
server.session.timeout
in the application.properties
file is now deprecated. The correct setting is:
server.servlet.session.timeout=60s
Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.
I have been using Inno Setup for an installer. I'm using 64-bit Windows 7 only. I'm finding that registry entries are being written to
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
I haven't yet figured out how to get this list to be reported by WMI (although the program is listed as installed in Programs and Features). If I figure it out, I'll try to remember to report back here.
UPDATE:
Entries for 32-bit programs installed on a 64-bit machine go in that registry location. There's more written here:
http://mdb-blog.blogspot.com/2010/09/c-check-if-programapplication-is.html
See my comment that describes 32-bit vs 64-bit behavior in that same post here:
Unfortunately, there doesn't seem to be a way to get WMI to list all programs from the add/remove programs list (aka Programs and Features in Windows 7, not sure about Vista). My current code has dropped WMI in favor of using the registry. The code itself to interrogate the registry is even easier than using WMI. Sample code is in the above link.
Couldn't you just call the following replaceing the {zipcode} with the zip code or city and state http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}
Here is a link with a How To Geocode using JavaScript: Geocode walk-thru. If you need the specific lat/lng numbers call geometry.location.lat() or geometry.location.lng() (API for google.maps.LatLng class)
EXAMPLE to get lat/lng:
var lat = '';
var lng = '';
var address = {zipcode} or {city and state};
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
alert('Latitude: ' + lat + ' Logitude: ' + lng);
Another way is to mutate the undesired columns to NULL
, this avoids the embedded parentheses :
head(iris,2) %>% mutate_at(drop.cols, ~NULL)
# Petal.Length Petal.Width Species
# 1 1.4 0.2 setosa
# 2 1.4 0.2 setosa
I know the answer is in reply to a question asked 6 years ago ...
But I was looking for something similar for a few hours and then found out that: cut -c does exactly that, with an added bonus that you could also specify an offset.
cut -c 1-5 will return Hello and cut -c 7-11 will return world. No need for any other command
Forking creates an entirely new repository from existing repository (simply doing git clone on gitHub/bitbucket)
Forks are best used: when the intent of the ‘split’ is to create a logically independent project, which may never reunite with its parent.
Branch strategy creates a new branch over the existing/working repository
Branches are best used: when they are created as temporary places to work through a feature, with the intent to merge the branch with the origin.
More Specific :- In open source projects it is the owner of the repository who decides who can push to the repository. However, the idea of open source is that everybody can contribute to the project.
This problem is solved by forks: any time a developer wants to change something in an open source project, they don’t clone the official repository directly. Instead, they fork it to create a copy. When the work is finished, they make a pull request so that the owner of the repository can review the changes and decide whether to merge them to his project.
At its core forking is similar to feature branching, but instead of creating branches a fork of the repository is made, and instead of doing a merge request you create a pull request.
The below links provide the difference in a well-explained manner :
https://blog.gitprime.com/the-definitive-guide-to-forks-and-branches-in-git/
You could rely on wget which usually handles ftp get properly (at least in my own experience). For example:
wget -r ftp://user:[email protected]/
You can also use -m
which is suitable for mirroring. It is currently equivalent to -r -N -l inf
.
If you've some special characters in the credential details, you can specify the --user
and --password
arguments to get it to work. Example with custom login with specific characters:
wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/
As pointed out by @asmaier, watch out that even if -r
is for recursion, it has a default max level of 5:
-r --recursive Turn on recursive retrieving. -l depth --level=depth Specify recursion maximum depth level depth. The default maximum depth is 5.
If you don't want to miss out subdirs, better use the mirroring option, -m
:
-m --mirror Turn on options suitable for mirroring. This option turns on recursion and time-stamping, sets infinite recursion depth and keeps FTP directory listings. It is currently equivalent to -r -N -l inf --no-remove-listing.
VisualSVN Server 4.2 supports finding files and folders in the web interface. Try out the new feature on one of the demo server’s repositories!
See the version 4.2 Release Notes, and download VisualSVN Server 4.2.0 from the main download page.
Old answer
Beginning with Subversion 1.8, you can use --search
option with svn log
command. Note that the command does not perform full-text search inside a repository, it considers the following data only:
svn:author
unversioned property),svn:date
unversioned property),svn:log
unversioned property),Here is the help page about these new search options:
If the --search option is used, log messages are displayed only if the
provided search pattern matches any of the author, date, log message
text (unless --quiet is used), or, if the --verbose option is also
provided, a changed path.
The search pattern may include "glob syntax" wildcards:
? matches any single character
* matches a sequence of arbitrary characters
[abc] matches any of the characters listed inside the brackets
If multiple --search options are provided, a log message is shown if
it matches any of the provided search patterns. If the --search-and
option is used, that option's argument is combined with the pattern
from the previous --search or --search-and option, and a log message
is shown only if it matches the combined search pattern.
If --limit is used in combination with --search, --limit restricts the
number of log messages searched, rather than restricting the output
to a particular number of matching log messages.
You can use mplayer.
mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi
The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.
In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.
et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
et.setHint(temp +" Characters");
}
});
You could do:
var numberOfChecked = $('input:checkbox:checked').length;
var totalCheckboxes = $('input:checkbox').length;
var numberNotChecked = totalCheckboxes - numberOfChecked;
EDIT
Or even simple
var numberNotChecked = $('input:checkbox:not(":checked")').length;
Adding to Winnie's great answer,
If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.
SHOW config_file;
For me changing the max_connections alone made the trick.
Several answers are here but nobody has posted usefull code.
Here is my code that detects all encodings that Microsoft detects in Framework 4 in the StreamReader class.
Obviously you must call this function immediately after opening the stream before reading anything else from the stream because the BOM are the first bytes in the stream.
This function requires a Stream that can seek (for example a FileStream). If you have a Stream that cannot seek you must write a more complicated code that returns a Byte buffer with the bytes that have already been read but that are not BOM.
/// <summary>
/// UTF8 : EF BB BF
/// UTF16 BE: FE FF
/// UTF16 LE: FF FE
/// UTF32 BE: 00 00 FE FF
/// UTF32 LE: FF FE 00 00
/// </summary>
public static Encoding DetectEncoding(Stream i_Stream)
{
if (!i_Stream.CanSeek || !i_Stream.CanRead)
throw new Exception("DetectEncoding() requires a seekable and readable Stream");
// Try to read 4 bytes. If the stream is shorter, less bytes will be read.
Byte[] u8_Buf = new Byte[4];
int s32_Count = i_Stream.Read(u8_Buf, 0, 4);
if (s32_Count >= 2)
{
if (u8_Buf[0] == 0xFE && u8_Buf[1] == 0xFF)
{
i_Stream.Position = 2;
return new UnicodeEncoding(true, true);
}
if (u8_Buf[0] == 0xFF && u8_Buf[1] == 0xFE)
{
if (s32_Count >= 4 && u8_Buf[2] == 0 && u8_Buf[3] == 0)
{
i_Stream.Position = 4;
return new UTF32Encoding(false, true);
}
else
{
i_Stream.Position = 2;
return new UnicodeEncoding(false, true);
}
}
if (s32_Count >= 3 && u8_Buf[0] == 0xEF && u8_Buf[1] == 0xBB && u8_Buf[2] == 0xBF)
{
i_Stream.Position = 3;
return Encoding.UTF8;
}
if (s32_Count >= 4 && u8_Buf[0] == 0 && u8_Buf[1] == 0 && u8_Buf[2] == 0xFE && u8_Buf[3] == 0xFF)
{
i_Stream.Position = 4;
return new UTF32Encoding(true, true);
}
}
i_Stream.Position = 0;
return Encoding.Default;
}
I have something like this which is very very useful:
generalEditText.getBackground().mutate().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
where generalEditText is my EditText and color white is:
<color name="white">#ffffff</color>
This will not remove padding and your EditText will stay as is. Only the line at the bottom will be removed. Sometimes it is more useful to do it like this.
If you use android:background="@null"
as many suggested you lose the padding and EditText becomes smaller. At least, it was my case.
A little side note is if you set background null and try the java code I provided above, your app will crash right after executing it. (because it gets the background but it is null.) It may be obvious but I think pointing it out is important.
Visual Studio has multiple flags to reset various settings:
The last three show up when running devenv.exe /?
. The first one seems to be undocumented/unsupported/the big hammer. From here:
Disclaimer: you will lose all your environment settings and customizations if you use this switch. It is for this reason that this switch is not officially supported and Microsoft does not advertise this switch to the public (you won't see this switch if you type devenv.exe /? in the command prompt). You should only use this switch as the last resort if you are experiencing an environment problem, and make sure you back up your environment settings by exporting them before using this switch.
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
Add this in your Xml - android:background="@android:color/transparent"
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Button"
android:background="@android:color/transparent"
android:textStyle="bold"/>
document.getElementById('gadget_url').value = 'your value';
Depending on the server-side language, you could use one of these:
.NET 4.0
string result = System.Web.HttpUtility.JavaScriptStringEncode("jsString")
Java
import org.apache.commons.lang.StringEscapeUtils;
...
String result = StringEscapeUtils.escapeJavaScript(jsString);
Python
import json
result = json.dumps(jsString)
PHP
$result = strtr($jsString, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"',
"\r" => '\\r', "\n" => '\\n' ));
Ruby on Rails
<%= escape_javascript(jsString) %>
The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.
LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.
LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.
Key features of LXD are:
There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.
However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.
The OpenStack nclxd plugin a list of features supported include:
stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support
By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.
Have a look at https://wiki.debian.org/JavaPackage At the bottom of this page an other method is descibed using a command from the java-common package
Easiest solution is to create the column using the correct data type: DATE
For example:
Create table:
create table test_date (mydate date);
Insert row:
insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));
To get the month and year, do as follows:
select to_char(mydate, 'MM-YYYY') from test_date;
Your result will be as follows: 01-2011
Another cool function to use is "EXTRACT"
select extract(year from mydate) from test_date;
This will return: 2011
Here's a good tutorial on what crontab is and how to use it on Ubuntu. Your crontab line will look something like this:
00 00 * * * ruby path/to/your/script.rb
(00 00
indicates midnight--0 minutes and 0 hours--and the *
s mean every day of every month.)
Syntax: mm hh dd mt wd command mm minute 0-59 hh hour 0-23 dd day of month 1-31 mt month 1-12 wd day of week 0-7 (Sunday = 0 or 7) command: what you want to run all numeric values can be replaced by * which means all
Here is the correct test of the device, without depending on the orientation
- (BOOL)isIPhone5
{
CGSize size = [[UIScreen mainScreen] bounds].size;
if (MIN(size.width,size.height) == 320 && MAX(size.width,size.height == 568)) {
return YES;
}
return NO;
}
Some addition to the previous answers. It is nice to regulate the density of the polygon to avoid obscuring the data points.
library(MASS)
attach(Boston)
lm.fit2 = lm(medv~poly(lstat,2))
plot(lstat,medv)
new.lstat = seq(min(lstat), max(lstat), length.out=100)
preds <- predict(lm.fit2, newdata = data.frame(lstat=new.lstat), interval = 'prediction')
lines(sort(lstat), fitted(lm.fit2)[order(lstat)], col='red', lwd=3)
polygon(c(rev(new.lstat), new.lstat), c(rev(preds[ ,3]), preds[ ,2]), density=10, col = 'blue', border = NA)
lines(new.lstat, preds[ ,3], lty = 'dashed', col = 'red')
lines(new.lstat, preds[ ,2], lty = 'dashed', col = 'red')
Please note that you see the prediction interval on the picture, which is several times wider than the confidence interval. You can read here the detailed explanation of those two types of interval estimates.
You have to duplicate the repo
You can see this doc (from github)
To create a duplicate of a repository without forking, you need to run a special clone command against the original repository and mirror-push to the new one.
In the following cases, the repository you're trying to push to--like exampleuser/new-repository or exampleuser/mirrored--should already exist on GitHub. See "Creating a new repository" for more information.
Mirroring a repository
To make an exact duplicate, you need to perform both a bare-clone and a mirror-push.
Open up the command line, and type these commands:
$ git clone --bare https://github.com/exampleuser/old-repository.git # Make a bare clone of the repository $ cd old-repository.git $ git push --mirror https://github.com/exampleuser/new-repository.git # Mirror-push to the new repository $ cd .. $ rm -rf old-repository.git # Remove our temporary local repository
If you want to mirror a repository in another location, including getting updates from the original, you can clone a mirror and periodically push the changes.
$ git clone --mirror https://github.com/exampleuser/repository-to-mirror.git # Make a bare mirrored clone of the repository $ cd repository-to-mirror.git $ git remote set-url --push origin https://github.com/exampleuser/mirrored # Set the push location to your mirror
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references will be overwritten each time you fetch, so it will always be the same as the original repository. Setting the URL for pushes simplifies pushing to your mirror. To update your mirror, fetch updates and push, which could be automated by running a cron job.
$ git fetch -p origin $ git push --mirror
You should be able to use something similar to:
$('#selectElementId').change(
function(){
$(this).closest('form').trigger('submit');
/* or:
$('#formElementId').trigger('submit');
or:
$('#formElementId').submit();
*/
});
I found other solution in my case this problem: Eclipse->Preferences->Java->Installed JRE
then press button Search. Select folder in Linux /usr
then Eclipse found all JVM.
Select another JVM too current. It is solved for my case.
In your terminal type:
code --diff file1.txt file2.txt
A tab will open up in VS Code showing the differences in the two files.
In Windows, first installed Python 3.7 and then Python 2.7. Then, use command prompt:
pip install python2-module-name
pip3 install python3-module-name
That's all
I faced the same problem. Updating bash_profile with the following lines, solved the problem for me:
export JAVA_HOME='/usr/'
export PATH=${JAVA_HOME}/bin:$PATH
A simple function to call a function dynamically with parameters:
this.callFunction = this.call_function = function(name) {
var args = Array.prototype.slice.call(arguments, 1);
return window[name].call(this, ...args);
};
function sayHello(name, age) {
console.log('hello ' + name + ', your\'e age is ' + age);
return some;
}
console.log(call_function('sayHello', 'john', 30)); // hello john, your'e age is 30
An easy approach is to leverage this code:
<a href="javascript:void(0);">Link Title</a>
This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.
For these reasons, the above solution is better than:
<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>
where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.
std::string replace(std::string str, const std::string& sub1, const std::string& sub2)
{
if (sub1.empty())
return str;
std::size_t pos;
while ((pos = str.find(sub1)) != std::string::npos)
str.replace(pos, sub1.size(), sub2);
return str;
}
after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.
You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item
{
public string name { get; set; }
public string index { get; set; }
public string optional { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Usage:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex json
s
In My example call add function from button click event and then get value from form control's and call function generateTable.
In generateTable Function check first Table is Generaed or not. If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.
<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="dataGridForItem">
</div>
</div>
</div>
//Call Function From Button click Event
var counts = 1;
function add(){
var Weightage = $('#Weightage').val();
var ItemName = $('#ItemName option:selected').text();
var ItemNamenum = $('#ItemName').val();
generateTable(Weightage,ItemName,ItemNamenum);
$('#Weightage').val('');
$('#ItemName').val(-1);
return true;
}
function generateTable(Weightage,ItemName,ItemNamenum){
var tableHtml = '';
if($("#rDataTable").html() == undefined){
tableHtml = generateHeader();
}else{
tableHtml = $("#rDataTable");
}
var temp = $("<div/>");
var row = addToRow(Weightage,ItemName,ItemNamenum);
$(temp).append($(row));
$("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}
//Generate Header
function generateHeader(){
var html = "<table id='rDataTable' class='table table-striped'>";
html+="<tr class=''>";
html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
html+="</tr></table>";
return html;
}
//Add New Row
function addToRow(Weightage,ItemName,ItemNamenum){
var html="<tr class='trObj'>";
html+="<td>"+counts+"</td>";
html+="<td>"+ItemName+"</td>";
html+="<td>"+Weightage+"</td>";
html+="</tr>";
counts++;
return html;
}
I found this thread among others and I agree it contains the most complete answers so I'm adding mine too:
sed
and ed
are so useful...by hand.
Look at this code from @Johnny:
sed -i -e 's/abc/XYZ/g' /tmp/file.txt
When my restriction is to use it in a shell script, no variable can be used inside in place of "abc" or "XYZ". The BashFAQ seems to agree with what I understand at least. So, I can't use:
x='abc'
y='XYZ'
sed -i -e 's/$x/$y/g' /tmp/file.txt
#or,
sed -i -e "s/$x/$y/g" /tmp/file.txt
but, what can we do? As, @Johnny said use a while read...
but, unfortunately that's not the end of the story. The following worked well with me:
#edit user's virtual domain
result=
#if nullglob is set then, unset it temporarily
is_nullglob=$( shopt -s | egrep -i '*nullglob' )
if [[ is_nullglob ]]; then
shopt -u nullglob
fi
while IFS= read -r line; do
line="${line//'<servername>'/$server}"
line="${line//'<serveralias>'/$alias}"
line="${line//'<user>'/$user}"
line="${line//'<group>'/$group}"
result="$result""$line"'\n'
done < $tmp
echo -e $result > $tmp
#if nullglob was set then, re-enable it
if [[ is_nullglob ]]; then
shopt -s nullglob
fi
#move user's virtual domain to Apache 2 domain directory
......
As one can see if nullglob
is set then, it behaves strangely when there is a string containing a *
as in:
<VirtualHost *:80>
ServerName www.example.com
which becomes
<VirtualHost ServerName www.example.com
there is no ending angle bracket and Apache2 can't even load.
This kind of parsing should be slower than one-hit search and replace but, as you already saw, there are four variables for four different search patterns working out of one parse cycle.
The most suitable solution I can think of with the given assumptions of the problem.
Here's another way:
{
Sub find_test2()
alpha_col = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,W,Z"
MsgBox Split(alpha_col, ",")(ActiveCell.Column - 1)
End Sub
}
Yes, even we can change image of UIButton, by using flag.
class ViewController: UIViewController
{
@IBOutlet var btnImage: UIButton!
var flag = false
override func viewDidLoad()
{
super.viewDidLoad()
//setting default image for button
setButtonImage()
}
@IBAction func btnClick(_ sender: Any)
{
flag = !flag
setButtonImage()
}
func setButtonImage(){
let imgName = flag ? "share" : "image"
let image1 = UIImage(named: "\(imgName).png")!
self.btnImage.setImage(image1, for: .normal)
}
}
Here, after every click your button image will change alternatively.
SQL 2008
Radim Köhler's answer works, but here is a shorter version:
select top 20 * from
(
select *,
ROW_NUMBER() OVER (ORDER BY columnid) AS ROW_NUM
from tablename
) x
where ROW_NUM>10
findViewById(R.id.android_text) does not need typecasting.
For a web based service, check out loader.io.
Summary:
loader.io is a free load testing service that allows you to stress test your web-apps/apis with thousands of concurrent connections.
They also have an API.
You can use a struct to read write into a file. You do not need to cast it as a `char*. Struct size will also be preserved. (This point is not closest to the topic but guess it: behaving on hard memory is often similar to RAM one.)
To move (to & from) a single string field you must use strncpy
and a transient string buffer '\0'
terminating.
Somewhere you must remember the length of the record string field.
To move other fields you can use the dot notation, ex.:
NodeB->one=intvar;
floatvar2=(NodeA->insidebisnode_subvar).myfl;
struct mynode {
int one;
int two;
char txt3[3];
struct{char txt2[6];}txt2fi;
struct insidenode{
char txt[8];
long int myl;
void * mypointer;
size_t myst;
long long myll;
} insidenode_subvar;
struct insidebisnode{
float myfl;
} insidebisnode_subvar;
} mynode_subvar;
typedef struct mynode* Node;
...(main)
Node NodeA=malloc...
Node NodeB=malloc...
You can embed each string into a structs that fit it,
to evade point-2 and behave like Cobol:
NodeB->txt2fi=NodeA->txt2fi
...but you will still need of a transient string
plus one strncpy
as mentioned at point-2 for scanf
, printf
otherwise an operator longer input (shorter),
would have not be truncated (by spaces padded).
(NodeB->insidenode_subvar).mypointer=(NodeA->insidenode_subvar).mypointer
will create a pointer alias.NodeB.txt3=NodeA.txt3
causes the compiler to reject:
error: incompatible types when assigning to type ‘char[3]’ from type ‘char *’
point-4 works only because NodeB->txt2fi
& NodeA->txt2fi
belong to the same typedef
!!
A correct and simple answer to this topic I found at In C, why can't I assign a string to a char array after it's declared? "Arrays (also of chars) are second-class citizens in C"!!!
If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.
Example:
List<Thread> threads = new List<Thread>();
// Start threads
for(int i = 0; i<10; i++)
{
int tmp = i; // Copy value for closure
Thread t = new Thread(() => Console.WriteLine(tmp));
t.Start;
threads.Add(t);
}
// Await threads
foreach(Thread thread in threads)
{
thread.Join();
}
Normally, it is included. However, as @ngn999 said, if your python has been built from source manually, you'll have to add it.
Here is an example of a script that will setup an encapsulated version (virtual environment) of Python3 in your user directory with an encapsulated version of sqlite3.
INSTALL_BASE_PATH="$HOME/local"
cd ~
mkdir build
cd build
[ -f Python-3.6.2.tgz ] || wget https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz
tar -zxvf Python-3.6.2.tgz
[ -f sqlite-autoconf-3240000.tar.gz ] || wget https://www.sqlite.org/2018/sqlite-autoconf-3240000.tar.gz
tar -zxvf sqlite-autoconf-3240000.tar.gz
cd sqlite-autoconf-3240000
./configure --prefix=${INSTALL_BASE_PATH}
make
make install
cd ../Python-3.6.2
LD_RUN_PATH=${INSTALL_BASE_PATH}/lib configure
LDFLAGS="-L ${INSTALL_BASE_PATH}/lib"
CPPFLAGS="-I ${INSTALL_BASE_PATH}/include"
LD_RUN_PATH=${INSTALL_BASE_PATH}/lib make
./configure --prefix=${INSTALL_BASE_PATH}
make
make install
cd ~
LINE_TO_ADD="export PATH=${INSTALL_BASE_PATH}/bin:\$PATH"
if grep -q -v "${LINE_TO_ADD}" $HOME/.bash_profile; then echo "${LINE_TO_ADD}" >> $HOME/.bash_profile; fi
source $HOME/.bash_profile
Why do this? You might want a modular python environment that you can completely destroy and rebuild without affecting your managed package installation. This would give you an independent development environment. In this case, the solution is to install sqlite3 modularly too.
sns.boxplot() function returns Axes(matplotlib.axes.Axes) object. please refer the documentation you can add title using 'set' method as below:
sns.boxplot('Day', 'Count', data=gg).set(title='lalala')
you can also add other parameters like xlabel, ylabel to the set method.
sns.boxplot('Day', 'Count', data=gg).set(title='lalala', xlabel='its x_label', ylabel='its y_label')
There are some other methods as mentioned in the matplotlib.axes.Axes documentaion to add tile, legend and labels.
Bart Kiers, your regex has a couple issues. The best way to do that is this:
(.*[a-z].*) // For lower cases
(.*[A-Z].*) // For upper cases
(.*\d.*) // For digits
In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.
You can also look into using the Collection Object. This usually works better than an array for custom objects, since it dynamically sizes and has methods for:
Plus its normally easier to loop through a collection too since you can use the for...each structure very easily with a collection.
POSTMAN : A google chrome extension
Use postman to send message instead of server. Postman settings are as follows :
Request Type: POST
URL: https://android.googleapis.com/gcm/send
Header
Authorization : key=your key //Google API KEY
Content-Type : application/json
JSON (raw) :
{
"registration_ids":["yours"],
"data": {
"Hello" : "World"
}
}
on success you will get
Response :
{
"multicast_id": 6506103988515583000,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1432811719975865%54f79db3f9fd7ecd"
}
]
}
The below example didnt quite work for me,this is the version that i made work!
HTML:
<div class="social-links">
<a href="#"><i class="fa fa-facebook fa-lg"></i></a>
<a href="#"><i class="fa fa-twitter fa-lg"></i></a>
<a href="#"><i class="fa fa-google-plus fa-lg"></i></a>
<a href="#"><i class="fa fa-pinterest fa-lg"></i></a>
</div>
CSS:
.social-links {
text-align:center;
}
.social-links a{
display: inline-block;
width:50px;
height: 50px;
border: 2px solid #909090;
border-radius: 50px;
margin-right: 15px;
}
.social-links a i{
padding: 18px 11px;
font-size: 20px;
color: #909090;
}
Another scenario that you can get the [: too many arguments
or [: a: binary operator expected
errors is if you try to test for all arguments "$@"
if [ -z "$@" ]
then
echo "Argument required."
fi
It works correctly if you call foo.sh
or foo.sh arg1
. But if you pass multiple args like foo.sh arg1 arg2
, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ]
, which is not a valid syntax.
The correct way to check for existence of arguments is [ "$#" -eq 0 ]
. ($#
is the number of arguments).
create a logfile in php, to do it you need to pass data on function and it will create log file for you.
function wh_log($log_msg)
{
$log_filename = "log";
if (!file_exists($log_filename))
{
// create directory/folder uploads.
mkdir($log_filename, 0777, true);
}
$log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
// if you don't add `FILE_APPEND`, the file will be erased each time you add a log
file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}
// call to function
wh_log("this is my log message");
I can't see any native .NET way to do it but if you want to get your hands dirty with the underlying Win32 controls...
You should be able to send it the CB_GETCOMBOBOXINFO
message with a COMBOBOXINFO
structure which will contain the internal edit control's handle.
You can then send the edit control the EM_SETCUEBANNER
message with a pointer to the string.
(Note that this requires at least XP and visual styles to be enabled.
The CSS selector for the direct first-child in your case is:
.section > :first-child
The direct selector is > and the first child selector is :first-child
No need for an asterisk before the : as others suggest. You could speed up the DOM searching by modifying this solution by prepending the tag:
div.section > :first-child
First off, are you setting your desired JRE or your desired JDK?
Even if your Eclipse is set up properly, there might be a wacky project-specific setting somewhere. You can open up a context menu on a given Java project in the Project Explorer and select Properties > Java Compiler to check on that.
If none of that helps, leave a comment and I'll take another look.
We can achieve by Bootstrap 4 Flexbox:
<div class="d-flex justify-content-between w-100">
<p>TotalCost</p> <p>$42</p>
</div>
d-flex // Display Flex
justify-content-between // justify-content:space-between
w-100 // width:100%
Example: JSFiddle
This example shows how to use the method GetInvocationList() to retrieve delegates to all the handlers that have been added. If you are looking to see if a specific handler (function) has been added then you can use array.
public class MyClass
{
event Action MyEvent;
}
...
MyClass myClass = new MyClass();
myClass.MyEvent += SomeFunction;
...
Action[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example
Console.WriteLine(handlers[0].Method.Name);//prints the name of the method
You can examine various properties on the Method property of the delegate to see if a specific function has been added.
If you are looking to see if there is just one attached, you can just test for null.
so you can use parent() to reach to the parent tr and then use find to gather the td with class two
var Something = $(this).parent().find(".two").html();
or
var Something = $(this).parent().parent().find(".two").html();
use as much as parent() what ever the depth of the clicked object according to the tr row
hope this works...
I have Tried something like this and its works fine;
this is the html part :
<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select></td>
<td width="8%"> </td>
<td colspan="2"> </td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>
this is Javascript part;
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
$('#data').append(strToAdd);
});
});
//]]>
</script>
Finaly PHP submit part:
for( $i = 1; $i <= $count; $i++ )
{
$year = $_POST['year'.$i];
$month = $_POST['month'.$i];
$week = $_POST['week'.$i];
$actual = $_POST['actual'.$i];
$max = $_POST['max'.$i];
$target = $_POST['target'.$i];
$extreme = $_POST['extreme'.$i];
$que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
mysql_query($que);
}
you can find more details via Dynamic table row inserter
You are thinking in the function ABS
, that gives you the absolute value of numeric data.
SELECT ABS(a) AS AbsoluteA, ABS(b) AS AbsoluteB
FROM YourTable
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
element.setAttribute("required", ""); //turns required on
element.required = true; //turns required on through reflected attribute
jQuery(element).attr('required', ''); //turns required on
$("#elementId").attr('required', ''); //turns required on
element.removeAttribute("required"); //turns required off
element.required = false; //turns required off through reflected attribute
jQuery(element).removeAttr('required'); //turns required off
$("#elementId").removeAttr('required'); //turns required off
if (edName.hasAttribute("required")) { } //check if required
if (edName.required) { } //check if required using reflected attribute
Once T.J. Crowder managed to point out reflected properties, i learned that following syntax is wrong:
element.attributes["name"] = value; //bad! Overwrites the HtmlAttribute object
element.attributes.name = value; //bad! Overwrites the HtmlAttribute object
value = element.attributes.name; //bad! Returns the HtmlAttribute object, not its value
value = element.attributes["name"]; //bad! Returns the HtmlAttribute object, not its value
You must go through element.getAttribute
and element.setAttribute
:
element.getAttribute("foo"); //correct
element.setAttribute("foo", "test"); //correct
This is because the attribute actually contains a special HtmlAttribute object:
element.attributes["foo"]; //returns HtmlAttribute object, not the value of the attribute
element.attributes.foo; //returns HtmlAttribute object, not the value of the attribute
By setting an attribute value to "true", you are mistakenly setting it to a String object, rather than the HtmlAttribute object it requires:
element.attributes["foo"] = "true"; //error because "true" is not a HtmlAttribute object
element.setAttribute("foo", "true"); //error because "true" is not an HtmlAttribute object
Conceptually the correct idea (expressed in a typed language), is:
HtmlAttribute attribute = new HtmlAttribute();
attribute.value = "";
element.attributes["required"] = attribute;
This is why:
getAttribute(name)
setAttribute(name, value)
exist. They do the work on assigning the value to the HtmlAttribute object inside.
On top of this, some attribute are reflected. This means that you can access them more nicely from Javascript:
//Set the required attribute
//element.setAttribute("required", "");
element.required = true;
//Check the attribute
//if (element.getAttribute("required")) {...}
if (element.required) {...}
//Remove the required attribute
//element.removeAttribute("required");
element.required = false;
What you don't want to do is mistakenly use the .attributes
collection:
element.attributes.required = true; //WRONG!
if (element.attributes.required) {...} //WRONG!
element.attributes.required = false; //WRONG!
This led to testing around the use of a required
attribute, comparing the values returned through the attribute, and the reflected property
document.getElementById("name").required;
document.getElementById("name").getAttribute("required");
with results:
HTML .required .getAttribute("required")
========================== =============== =========================
<input> false (Boolean) null (Object)
<input required> true (Boolean) "" (String)
<input required=""> true (Boolean) "" (String)
<input required="required"> true (Boolean) "required" (String)
<input required="true"> true (Boolean) "true" (String)
<input required="false"> true (Boolean) "false" (String)
<input required="0"> true (Boolean) "0" (String)
Trying to access the .attributes
collection directly is wrong. It returns the object that represents the DOM attribute:
edName.attributes["required"] => [object Attr]
edName.attributes.required => [object Attr]
This explains why you should never talk to the .attributes
collect directly. You're not manipulating the values of the attributes, but the objects that represent the attributes themselves.
What's the correct way to set required
on an attribute? You have two choices, either the reflected property, or through correctly setting the attribute:
element.setAttribute("required", ""); //Correct
edName.required = true; //Correct
Strictly speaking, any other value will "set" the attribute. But the definition of Boolean
attributes dictate that it should only be set to the empty string ""
to indicate true. The following methods all work to set the required
Boolean attribute,
but do not use them:
element.setAttribute("required", "required"); //valid, but not preferred
element.setAttribute("required", "foo"); //works, but silly
element.setAttribute("required", "true"); //Works, but don't do it, because:
element.setAttribute("required", "false"); //also sets required boolean to true
element.setAttribute("required", false); //also sets required boolean to true
element.setAttribute("required", 0); //also sets required boolean to true
We already learned that trying to set the attribute directly is wrong:
edName.attributes["required"] = true; //wrong
edName.attributes["required"] = ""; //wrong
edName.attributes["required"] = "required"; //wrong
edName.attributes.required = true; //wrong
edName.attributes.required = ""; //wrong
edName.attributes.required = "required"; //wrong
The trick when trying to remove the required
attribute is that it's easy to accidentally turn it on:
edName.removeAttribute("required"); //Correct
edName.required = false; //Correct
With the invalid ways:
edName.setAttribute("required", null); //WRONG! Actually turns required on!
edName.setAttribute("required", ""); //WRONG! Actually turns required on!
edName.setAttribute("required", "false"); //WRONG! Actually turns required on!
edName.setAttribute("required", false); //WRONG! Actually turns required on!
edName.setAttribute("required", 0); //WRONG! Actually turns required on!
When using the reflected .required
property, you can also use any "falsey" values to turn it off, and truthy values to turn it on. But just stick to true and false for clarity.
required
?Check for the presence of the attribute through the .hasAttribute("required")
method:
if (edName.hasAttribute("required"))
{
}
You can also check it through the Boolean reflected .required
property:
if (edName.required)
{
}
The javadoc of the File
class describes the class as:
An abstract representation of file and directory pathnames.
File
is only a representation of a pathname, with a few methods concerning the filesystem (like exists()
) and directory handling but actual streaming input and output is done elsewhere. Streams can be opened and closed, files cannot.
(My personal opinion is that it's rather unfortunate that Sun then went on to create RandomAccessFile
, causing much confusion with its inconsistent naming.)
Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.
Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):
onClick=""
OR
The element css needs to have the following declaration:
cursor:pointer
Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working
Late to the game, but here's a really handy function that is super simple to use, allows you to pass as many arguments as you like, of any type, and will display the object contents in the browser console window as though you called console.log from JavaScript - but from PHP
Note, you can use tags as well by passing 'TAG-YourTag' and it will be applied until another tag is read, for example, 'TAG-YourNextTag'
/*
* Brief: Print to console.log() from PHP
* Description: Print as many strings,arrays, objects, and other data types to console.log from PHP.
* To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that
* you can pass as many data as you want an this will still work.
*
* This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.
*
* A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is
* detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then
* be applied to all data after it.
*
* Example:
* consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3);
* Result:
* FirstTag '...data...'
* FirstTag '...data2...'
* SecTag '...data3...'
*/
function consoleLog(){
if(func_num_args() == 0){
return;
}
$tag = '';
for ($i = 0; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
if(!empty($arg)){
if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){
$tag = substr($arg,4);
}else{
$arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );
echo "<script>console.log('".$tag." ".$arg."');</script>";
}
}
}
}
NOTE: func_num_args() and func_num_args() are php functions for reading a dynamic number of input args, and allow this function to have infinitely many console.log requests from one function call