Try:
h1 {
margin-top: 0;
}
You're seeing the effects of margin collapsing.
As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException
as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:
public class NotYetImplementedException extends RuntimeException
{
/**
* @deprecated Deprecated to remind you to implement the corresponding code
* before releasing the software.
*/
@Deprecated
public NotYetImplementedException()
{
}
/**
* @deprecated Deprecated to remind you to implement the corresponding code
* before releasing the software.
*/
@Deprecated
public NotYetImplementedException(String message)
{
super(message);
}
}
This approach has the following benefits:
NotYetImplementedException
, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException
says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.import
line (JDK 9 fixed this, though).in Jquery "data" doesn't refresh by default :
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());
You'd use "attr" instead for live update:
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());
i have just tried it and this works perfectly
USE YourDatabseName
GO
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%YourColumnName%'
ORDER BY schema_name, table_name;
Only change YourDatbaseName to your database and YourcolumnName to your column name that you are looking for the rest keep it as it is.
Hope this has helped
Make sure Postgres is installed and PATH is updated before running pip install psycopg2
export PATH="$PATH:/Applications/Postgres.app/Contents/Versions/12/bin"
Tackling this task, I'd first find the number of decimal places in x
, then round y
accordingly. I'd use:
y.toFixed(x.toString().split(".")[1].length);
It should convert x
to a string, split it over the decimal point, find the length of the right part, and then y.toFixed(length)
should round y
based on that length.
I encounter same trouble as you, this is my solution.
body {
background-image: url(image/background.jpg);
background-size: 100% 100%;
}
I'm the author of the article in question.
No doubt there are multiple ways to do it, but the way I typically do it is to implement a custom UserDetails
that knows about roles and permissions. Role
and Permission
are just custom classes that you write. (Nothing fancy--Role
has a name and a set of Permission
instances, and Permission
has a name.) Then the getAuthorities()
returns GrantedAuthority
objects that look like this:
PERM_CREATE_POST
, PERM_UPDATE_POST
, PERM_READ_POST
instead of returning things like
ROLE_USER
, ROLE_MODERATOR
The roles are still available if your UserDetails
implementation has a getRoles()
method. (I recommend having one.)
Ideally you assign roles to the user and the associated permissions are filled in automatically. This would involve having a custom UserDetailsService
that knows how to perform that mapping, and all it has to do is source the mapping from the database. (See the article for the schema.)
Then you can define your authorization rules in terms of permissions instead of roles.
Hope that helps.
You will have to apply all Eclipse shortcuts with Android Studio before using all those shortcuts.
Procedure:
Steps:
Setting -> KeyMap -> Select Eclipse -> Apply -> OK
Now you can use all Eclipse shortcuts in Android Studio...
Have some snapshots here.
Try this:
your_command 2>stderr.log 1>stdout.log
The numerals 0
through 9
are file descriptors in bash.
0
stands for standard input, 1
stands for standard output, 2
stands for standard error. 3
through 9
are spare for any other temporary usage.
Any file descriptor can be redirected to a file or to another file descriptor using the operator >
. You can instead use the operator >>
to appends to a file instead of creating an empty one.
Usage:
file_descriptor > filename
file_descriptor > &file_descriptor
Please refer to Advanced Bash-Scripting Guide: Chapter 20. I/O Redirection.
keep sqljdbc_auth.dll
in your windows/system32 folder and it will work.Download sqljdbc driver from this link Unzip it and you will find sqljdbc_auth.dll
.Now keep the sqljdbc_auth.dll
inside system32 folder and run your program
In fact I would not use any REDIM, nor a loop for transferring data from sheet to array:
dim arOne()
arOne = range("A2:F1000")
or even
arOne = range("A2").CurrentRegion
and that's it, your array is filled much faster then with a loop, no redim.
Normally I would recommend floating but from your 3 requirements I would suggest this:
position: absolute;
right: 10px;
top: 5px;
Don't forget position: relative;
on the parent div
I am assuming you have a remote with all relevant changes already pushed to it. I did not care about local changes and simply wanted to avoid deleting and recloning a large repository. If you do have important local changes you might want to be more careful.
I had the same problem after my laptop crashed.
Probably because it was a large repository I had quite a few corrupt object files, which only appeared one at a time when calling git fsck --full
, so I wrote a small shell one-liner to automatically delete one of them:
$ sudo rm `git fsck --full 2>&1 | grep -oE -m 1 ".git/objects/[0-9a-f]{2}/[0-9a-f]*"`
2>&1
redirects the error message to stdout to be able to grep it-o
only returns the part of a line that actually matches-E
enables advanced regexes-m 1
make sure only the first match is returned[0-9a-f]{2}
matches any of the characters between 0 and 9 and a and f if two of them occur together[0-9a-f]*
matches any number of the characters between 0 and 9 and a and f occuring togetherIt still only deletes one file at a time, so you might want to call it in a loop like:
$ while true; do sudo rm `git fsck --full 2>&1 | grep -oE -m 1 ".git/objects/[0-9a-f]{2}/[0-9a-f]*"`; done
The problem with this is, that it does not output anything useful anymore so you do not know when it is finished (it should just not do anything useful after some time)
To "fix" this I then just added a call of git fsck --full
after each round like so:
$ while true; do sudo rm `git fsck --full 2>&1 | grep -oE -m 1 ".git/objects/[0-9a-f]{2}/[0-9a-f]*"`; git fsck --full; done
It now is approximately half as fast, but it does output it's "state".
After this I played around some with the suggestions in this thread and finally got to a point where I could git stash
and git stash drop
a lot of the broken stuff.
first problem solved
Afterwards I still had the following problem:
unable to resolve reference 'refs/remotes/origin/$branch': reference broken
which could be solved by
$ rm \repo.git\refs\remotes\origin\$branch
$ git fetch
I then did a
$ git gc --prune=now
$ git remote prune origin
for good measure and
git reflog expire --stale-fix --all
to get rid of error: HEAD: invalid reflog entry $blubb
when running git fsck --full
.
layout.xml
<Button
android:id="@+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="finishActivity"
android:text="Back" />
Activity.java
public void finishActivity(View v){
finish();
}
Related:
In my case I was doing this:
double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));
Instead of the "correct" :
double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);
Take attention with the parentheses !
To Increase Maximum heap: Click to open your Android Studio, look at below pictures. Step by step. ANDROID STUDIO v2.1.2
Click to navigate to Settings from the Configure or GO TO FILE SETTINGS at the top of Android Studio.
check also the android compilers from the link to confirm if it also change if not increase to the same size you modify from the compiler link.
Note: You can increase the size base on your memory capacity and remember this setting is base on Android Studio v2.1.2
All the test cases in this post are flawed as they access the same file for each method tested. So disk caching kicks in which tests 2 and 3 benefit from. To prove my point I took test case provided by GHAD and changed the order of enumeration and below are the results.
Looking at result I think File.length() is the winner really.
Order of test is the order of output. You can even see the time taken on my machine varied between executions but File.Length() when not first, and incurring first disk access won.
---
LENGTH sum: 1163351, per Iteration: 4653.404
CHANNEL sum: 1094598, per Iteration: 4378.392
URL sum: 739691, per Iteration: 2958.764
---
CHANNEL sum: 845804, per Iteration: 3383.216
URL sum: 531334, per Iteration: 2125.336
LENGTH sum: 318413, per Iteration: 1273.652
---
URL sum: 137368, per Iteration: 549.472
LENGTH sum: 18677, per Iteration: 74.708
CHANNEL sum: 142125, per Iteration: 568.5
If it has to be "nested", this would be one way, to get your job done:
SELECT o.name AS country, o.headofstate
FROM country o
WHERE o.headofstate like 'A%'
AND (
SELECT i.population
FROM city i
WHERE i.id = o.capital
) > 100000
A JOIN
would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?
I found that excluding the full spring-boot-starter-logging
module is not necessary. All that is needed is to exclude the org.slf4j:slf4j-log4j12
module.
Adding this to a Gradle build file will resolve the issue:
configurations {
runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"
compile.exclude group: "org.slf4j", module: "slf4j-log4j12"
}
See this other StackOverflow answer for more details.
As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.
You can defeat this behavior by using an object rather than a scalar for 'count':
{% set count = [1] %}
You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):
{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}
The alert() function can't output an object in a read-friendly manner. Try using console.log(object) instead, and fire up your browser's console to debug.
Mac Mountain Lion has the same password now it uses Oracle.
i am still pretty unsure about this. I am working since 7 years on an Application Server. Our bigger installations take use of 24 GB Ram. Its hightly Multithreaded, and ALL calls for GC.Collect() ran into really terrible performance issues.
Many third party Components used GC.Collect() when they thought it was clever to do this right now. So a simple bunch of Excel-Reports blocked the App Server for all threads several times a minute.
We had to refactor all the 3rd Party Components in order to remove the GC.Collect() calls, and all worked fine after doing this.
But i am running Servers on Win32 as well, and here i started to take heavy use of GC.Collect() after getting a OutOfMemoryException.
But i am also pretty unsure about this, because i often noticed, when i get a OOM on 32 Bit, and i retry to run the same Operation again, without calling GC.Collect(), it just worked fine.
One thing i wonder is the OOM Exception itself... If i would have written the .Net Framework, and i can't alloc a memory block, i would use GC.Collect(), defrag memory (??), try again, and if i still cant find a free memory block, then i would throw the OOM-Exception.
Or at least make this behavior as configurable option, due the drawbacks of the performance issue with GC.Collect.
Now i have lots of code like this in my app to "solve" the problem:
public static TResult ExecuteOOMAware<T1, T2, TResult>(Func<T1,T2 ,TResult> func, T1 a1, T2 a2)
{
int oomCounter = 0;
int maxOOMRetries = 10;
do
{
try
{
return func(a1, a2);
}
catch (OutOfMemoryException)
{
oomCounter++;
if (maxOOMRetries > 10)
{
throw;
}
else
{
Log.Info("OutOfMemory-Exception caught, Trying to fix. Counter: " + oomCounter.ToString());
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(oomCounter * 10));
GC.Collect();
}
}
} while (oomCounter < maxOOMRetries);
// never gets hitted.
return default(TResult);
}
(Note that the Thread.Sleep() behavior is a really App apecific behavior, because we are running a ORM Caching Service, and the service takes some time to release all the cached objects, if RAM exceeds some predefined values. so it waits a few seconds the first time, and has increased waiting time each occurence of OOM.)
An alternative is to call the pip
module by using python2.7, as below:
python2.7 -m pip <commands>
For example, you could run python2.7 -m pip install <package>
to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.
In case the pip module has not yet been installed for this version of python, you can run the following:
python2.7 -m ensurepip
Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo
). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.
Thanks all, it was of great help. Just to add more [from MS page]:
Warning
Top-level wildcard bindings (
http://*:8080/
andhttp://+:8080
) should not be used. Top-level wildcard bindings can open up your app to security vulnerabilities. This applies to both strong and weak wildcards. Use explicit host names rather than wildcards. Subdomain wildcard binding (for example,*.mysub.com
) doesn't have this security risk if you control the entire parent domain (as opposed to*.com
, which is vulnerable). See rfc7230 section-5.4 for more information.
Are you trying to actually follow the link or trigger the onclick? You can trigger an onclick with something like this:
var link = document.getElementById(linkId);
link.onclick.call(link);
Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem
instances. This is fortunately not needed anymore in JSF 2.x.
To answer your question directly, just use <f:selectItems>
whose value
points to a List<T>
property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T
actually represents a String
.
<h:selectOneMenu value="#{bean.name}">
<f:selectItems value="#{bean.names}" />
</h:selectOneMenu>
with
@ManagedBean
@RequestScoped
public class Bean {
private String name;
private List<String> names;
@EJB
private NameService nameService;
@PostConstruct
public void init() {
names = nameService.list();
}
// ... (getters, setters, etc)
}
Simple as that. Actually, the T
's toString()
will be used to represent both the dropdown item label and value. So, when you're instead of List<String>
using a list of complex objects like List<SomeEntity>
and you haven't overridden the class' toString()
method, then you would see com.example.SomeEntity@hashcode
as item values. See next section how to solve it properly.
Also note that the bean for <f:selectItems>
value does not necessarily need to be the same bean as the bean for <h:selectOneMenu>
value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.
<h:selectOneMenu value="#{bean.name}">
<f:selectItems value="#{data.names}" />
</h:selectOneMenu>
Whenever T
concerns a complex object (a javabean), such as User
which has a String
property of name
, then you could use the var
attribute to get hold of the iteration variable which you in turn can use in itemValue
and/or itemLabel
attribtues (if you omit the itemLabel
, then the label becomes the same as the value).
Example #1:
<h:selectOneMenu value="#{bean.userName}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>
with
private String userName;
private List<User> users;
@EJB
private UserService userService;
@PostConstruct
public void init() {
users = userService.list();
}
// ... (getters, setters, etc)
Or when it has a Long
property id
which you would rather like to set as item value:
Example #2:
<h:selectOneMenu value="#{bean.userId}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>
with
private Long userId;
private List<User> users;
// ... (the same as in previous bean example)
Whenever you would like to set it to a T
property in the bean as well and T
represents an User
, then you would need to bake a custom Converter
which converts between User
and an unique string representation (which can be the id
property). Do note that the itemValue
must represent the complex object itself, exactly the type which needs to be set as selection component's value
.
<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
with
private User user;
private List<User> users;
// ... (the same as in previous bean example)
and
@ManagedBean
@RequestScoped
public class UserConverter implements Converter {
@EJB
private UserService userService;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return userService.find(Long.valueOf(submittedValue));
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (modelValue instanceof User) {
return String.valueOf(((User) modelValue).getId());
} else {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
}
}
}
(please note that the Converter
is a bit hacky in order to be able to inject an @EJB
in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class)
, but that unfortunately doesn't allow @EJB
injections)
Don't forget to make sure that the complex object class has equals()
and hashCode()
properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.
public class User {
private Long id;
@Override
public boolean equals(Object other) {
return (other != null && getClass() == other.getClass() && id != null)
? id.equals(((User) other).id)
: (other == this);
}
@Override
public int hashCode() {
return (id != null)
? (getClass().hashCode() + id.hashCode())
: super.hashCode();
}
}
Head to this answer: Implement converters for entities with Java Generics.
The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu>
without the need to create a custom converter. The SelectItemsConverter
will simply do the conversion based on readily available items in <f:selectItem(s)>
.
<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
If you want to guarantee the same order regardless of the order of elements in the input array, here is a stable sorting:
myArray.sort(function(a, b) {
/* Storing case insensitive comparison */
var comparison = a.toLowerCase().localeCompare(b.toLowerCase());
/* If strings are equal in case insensitive comparison */
if (comparison === 0) {
/* Return case sensitive comparison instead */
return a.localeCompare(b);
}
/* Otherwise return result */
return comparison;
});
I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.
I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it
Edit: I just did a quick test with this:
<a href="test.html" style="{color: blue; background: white}
:visited {color: green}
:hover {background: yellow}
:visited:hover {color: purple}">Test</a>
And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?
ClassList add
var dynamic=document.getElementById("dynamic");
dynamic.classList.add("red");
dynamic.classList.add("size");
dynamic.classList.add("bold");
_x000D_
.red{
color:red;
}
.size{
font-size:40px;
}
.bold{
font-weight:800;
}
_x000D_
<div id="dynamic">dynamic css</div>
_x000D_
Look at this code, it can help you to get out of the loop fast!
foreach (var name in parent.names)
{
if (name.lastname == null)
{
Violated = true;
this.message = "lastname reqd";
break;
}
else if (name.firstname == null)
{
Violated = true;
this.message = "firstname reqd";
break;
}
}
Yes, I believe it should work and it can also be applied to other data types.
For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.
While working with selected cells as shown by @tbur can be useful, it's also not the only option available.
You can use Range() like so:
If Worksheets("Sheet1").Range("A1").MergeCells Then
Do something
Else
Do something else
End If
Or:
If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
Do something
Else
Do something else
End If
Alternately, you can use Cells():
If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
Do something
Else
Do something else
End If
The example by user11617 is incorrect; it will report that the file exists even in cases where it does not, but there was an error of some other sort.
The signature should be Exists(string) (bool, error). And then, as it happens, the call sites are no better.
The code he wrote would better as:
func Exists(name string) bool {
_, err := os.Stat(name)
return !os.IsNotExist(err)
}
But I suggest this instead:
func Exists(name string) (bool, error) {
_, err := os.Stat(name)
if os.IsNotExist(err) {
return false, nil
}
return err != nil, err
}
It's probably to late but i think this code work...
$blocks.each(function(i, elm) {
$(elm).fadeOut(200, function() {
$(elm).remove();
});
}).promise().done( function(){ alert("All was done"); } );
In case you are using Mac, most probably your gradle home should be /usr/local/gradle-2.0
for example.
In preference of IDEA search for gradle and set gradle home as given above. It should work
To check for null values you could use _.isNull
from official documentation
isNull_.isNull(object)
Returns true if the value of object is null.
_.isNull(null);
=> true
_.isNull(undefined);
=> false
Another way you can achieve the desired effect is to use this Material Search View library. It handles search history automatically and it's possible to provide search suggestions to the view as well.
Sample: (It's shown in Portuguese, but it also works in english and italian).
Before you can use this lib, you have to implement a class named MsvAuthority
inside the br.com.mauker
package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY
. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.
Example:
MsvAuthority.java
package br.com.mauker;
public class MsvAuthority {
public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<application ... >
<provider
android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
android:exported="false"
android:protectionLevel="signature"
android:syncable="true"/>
</application>
</manifest>
To use it, add the dependency:
compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'
And then, on your Activity
layout file, add the following:
<br.com.mauker.materialsearchview.MaterialSearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
After that, you'll just need to get the MaterialSearchView
reference by using getViewById()
, and open it up or close it using MaterialSearchView#openSearch()
and MaterialSearchView#closeSearch()
.
P.S.: It's possible to open and close the view not only from the Toolbar
. You can use the openSearch()
method from basically any Button
, such as a Floating Action Button.
// Inside onCreate()
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchView.openSearch();
}
});
You can also close the view using the back button, doing the following:
@Override
public void onBackPressed() {
if (searchView.isOpen()) {
// Close the search on the back button press.
searchView.closeSearch();
} else {
super.onBackPressed();
}
}
For more information on how to use the lib, check the github page.
I've figure out that even though Myisam has locking contention, it's still faster than InnoDb in most scenarios because of the rapid lock acquisition scheme it uses. I've tried several times Innodb and always fall back to MyIsam for one reason or the other. Also InnoDB can be very CPU intensive in huge write loads.
width="100" height="100"
in the svg file then add this x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100"
while keeping the already defined width="100" height="100"
. img
so you could then do this: img{height: 20px; width: 20px;}
and the image will scale.I'm not sure if someone will ever see this answer but here it is. The idea here is to simply detect if any click was done outside the element itself.
I first start by giving an id to the main div of my "dropdown".
<template>
<div class="relative" id="dropdown">
<div @click="openDropdown = !openDropdown" class="cursor-pointer">
<slot name="trigger" />
</div>
<div
class="absolute mt-2 w-48 origin-top-right right-0 text-red bg-tertiary text-sm text-black"
v-show="openDropdown"
@click="openDropdown = false"
>
<slot name="content" />
</div>
</div>
</template>
And then I just loop thru the path of the mouse event and see if the div with my id "dropdown" is there. If it is, then we good, if it is no, then we close the dropdown.
<script>
export default {
data() {
return {
openDropdown: false,
};
},
created() {
document.addEventListener("click", (e) => {
let me = false;
for (let index = 0; index < e.path.length; index++) {
const element = e.path[index];
if (element.id == "dropdown") {
me = true;
return;
}
}
if (!me) this.openDropdown = false;
});
}
};
</script>
I'm pretty sure this can bring performance issues if you have many nested elements, but I found this as the most lazy-friendly way of doing it.
The Django documentation for database queries includes a section on copying model instances. Assuming your primary keys are autogenerated, you get the object you want to copy, set the primary key to None
, and save the object again:
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1
blog.pk = None
blog.save() # blog.pk == 2
In this snippet, the first save()
creates the original object, and the second save()
creates the copy.
If you keep reading the documentation, there are also examples on how to handle two more complex cases: (1) copying an object which is an instance of a model subclass, and (2) also copying related objects, including objects in many-to-many relations.
Note on miah's answer: Setting the pk to None
is mentioned in miah's answer, although it's not presented front and center. So my answer mainly serves to emphasize that method as the Django-recommended way to do it.
Historical note: This wasn't explained in the Django docs until version 1.4. It has been possible since before 1.4, though.
Possible future functionality: The aforementioned docs change was made in this ticket. On the ticket's comment thread, there was also some discussion on adding a built-in copy
function for model classes, but as far as I know they decided not to tackle that problem yet. So this "manual" way of copying will probably have to do for now.
It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment
geonames.org has an api and a data dump of worldwide geographical places.
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
Jérôme Petazzoni has a pretty interesting blog post on how to Attach a volume to a container while it is running. This isn't something that's built into Docker out of the box, but possible to accomplish.
As he also points out
This will not work on filesystems which are not based on block devices.
It will only work if /proc/mounts correctly lists the block device node (which, as we saw above, is not necessarily true).
Also, I only tested this on my local environment; I didn’t even try on a cloud instance or anything like that
YMMV
Since the onItemClickLitener()
will itself provide you the index of the selected item, you can simply do a getItemAtPosition(i).toString()
. The code snippet is given below :-
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String s = listView.getItemAtPosition(i).toString();
Toast.makeText(activity.getApplicationContext(), s, Toast.LENGTH_LONG).show();
adapter.dismiss(); // If you want to close the adapter
}
});
On the method above, the i
parameter actually gives you the position of the selected item.
git submodule update --recursive
You will also probably want to use the --init option which will make it initialize any uninitialized submodules:
git submodule update --init --recursive
Note: in some older versions of Git, if you use the --init
option, already-initialized submodules may not be updated. In that case, you should also run the command without --init
option.
Easiest way to do is :
awk 'NR==FNR{a[$1]++;next} a[$1] ' file1 file2
Files are not necessary to be sorted.
This issue is resolved after spending few hours and i got it working. which is believe is the simplest way to solve the pagination with angular material. - Do first start by working on (component.html) file
<mat-paginator [pageSizeOptions]="[2, 5, 10, 15, 20]" showFirstLastButtons>
</mat-paginator>
and do in the (component.ts) file
import { MatPaginator } from '@angular/material/paginator';
import { Component, OnInit, ViewChild } from '@angular/core';
export interface UserData {
full_name: string;
email: string;
mob_number: string;
}
export class UserManagementComponent implements OnInit{
dataSource : MatTableDataSource<UserData>;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(){
this.userList();
}
ngOnInit() { }
public userList() {
this._userManagementService.userListing().subscribe(
response => {
console.log(response['results']);
this.dataSource = new MatTableDataSource<UserData>(response['results']);
this.dataSource.paginator = this.paginator;
console.log(this.dataSource);
},
error => {});
}
}
Remember Must import the pagination module in your currently working module(module.ts) file.
import {MatPaginatorModule} from '@angular/material/paginator';
@NgModule({
imports: [MatPaginatorModule]
})
Hope it will Work for you.
def player(game_over):
do something here
game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
if not game_over:
computer(game_over) #We are only going to do this if check_winner comes back as False
def check_winner():
check something
#here needs to be an if / then statement deciding if the game is over, return True if over, false if not
if score == 100:
return True
else:
return False
def computer(game_over):
do something here
game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
if not game_over:
player(game_over) #We are only going to do this if check_winner comes back as False
game_over = False #We need a variable to hold wether the game is over or not, we'll start it out being false.
player(game_over) #Start your loops, sending in the status of game_over
Above is a pretty simple example... I made up a statement for check_winner
using score = 100
to denote the game being over.
You will want to use similar method of passing score
into check_winner
, using game_over = check_winner(score)
. Then you can create a score at the beginning of your program and pass it through to computer
and player
just like game_over
is being handled.
If you want to pass variables from the current function, another way to do this is, for example:
document.getElementById("space1").onclick = new Function("lrgWithInfo('"+myVar+"')");
If you don't need to pass information from this function, it's just:
document.getElementById("space1").onclick = new Function("lrgWithInfo('13')");
Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):
To install additional ESP8266WiFi library:
After above steps, you should compile the sketch normally.
If you know which column # it is (first / second / nth) then this solution posted on a similar question works regardless of whether it is named or unnamed, and in one line: https://stackoverflow.com/a/26336314/4355695
df.rename(columns = {list(df)[1]:'new_name'}, inplace=True)
# 1 is for second column (0,1,2..)
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
Okay, I fixed it by rebuilding it for doing a ./gradlew clean assemble for the fourth time... Android Studio is a weird thing
You can either use JavaScript or CSS3.
JavaScript solution: Use an absolute positioned <img>
tag and resize it on the page load and whenever the page resizes. Be careful of possible bugs when trying to get the page/window size.
CSS3 solution: Use the CSS3 background-size property. You might use either 100% 100%
or contain
or cover
, depending on how you want the image to resize. Of course, this only works on modern browsers.
ContextLoaderListner is a Servlet listener that loads all the different configuration files (service layer configuration, persistence layer configuration etc) into single spring application context.
This helps to split spring configurations across multiple XML files.
Once the context files are loaded, Spring creates a WebApplicationContext object based on the bean definition and stores it in the ServletContext of your web application.
I struggled with this a little because I wanted to use Knockout to bind the button to the click event. Here's my button and the relevant function from inside my view model.
<a class="btn btn-secondary showBusy" data-bind="click: back">Back to Dashboard</a>
var vm = function () {
...
self.back = function() {
window.location.href = '@Url.Action("LicenseDashboard", "Application")';
}
}
The Heap is divided into young and old generations as follows :
Young Generation: It is a place where an object lived for a short period and it is divided into two spaces:
Old Generation: This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from the Young Generation.
Explanation
Let's imagine our application has just started.
So at this point all three of these spaces are empty (Eden, S0, S1).
Whenever a new object is created it is placed in the Eden space.
When the Eden space gets full then the garbage collection process (minor GC) will take place on the Eden space and any surviving objects are moved into S0.
Our application then continues running add new objects are created in the Eden space the next time that the garbage collection process runs it looks at everything in the Eden space and in S0 and any objects that survive get moved into S1.
PS: Based on the configuration that how much time object should survive in Survivor space, the object may also move back and forth to S0 and S1 and then reaching the threshold objects will be moved to old generation heap space.
If you're using django, you can use urlquote:
>>> from django.utils.http import urlquote
>>> urlquote(u"Müller")
u'M%C3%BCller'
Note that changes to Python since this answer was published mean that this is now a legacy wrapper. From the Django 2.1 source code for django.utils.http:
A legacy compatibility wrapper to Python's urllib.parse.quote() function.
(was used for unicode handling on Python 2)
Try this:
string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);
It is not a "problem" as you stated it.
Hibernate has the built-in find()
, but you have to build your own query in order to get a particular object. I recommend using Hibernate's Criteria
:
Criteria criteria = session.createCriteria(YourClass.class);
YourObject yourObject = criteria.add(Restrictions.eq("yourField", yourFieldValue))
.uniqueResult();
This will create a criteria
on your current class, adding the restriction that the column "yourField" is equal to the value yourFieldValue
. uniqueResult()
tells it to bring a unique result. If more objects match, you should retrive a list.
List<YourObject> list = criteria.add(Restrictions.eq("yourField", yourFieldValue)).list();
If you have any further questions, please feel free to ask. Hope this helps.
I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"
It's possible by accessing the key as index
for example:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2
Now will this socket connection remain open forever or is there a timeout limit associated with it similar to HTTP keep-alive?
The short answer is no it won't remain open forever, it will probably time out after a few hours. Therefore yes there is a timeout and it is enforced via TCP Keep-Alive.
If you would like to configure the Keep-Alive timeout on your machine, see the "Changing TCP Timeouts" section below. Otherwise read through the rest of the answer to learn how TCP Keep-Alive works.
TCP connections consist of two sockets, one on each end of the connection. When one side wants to terminate the connection, it sends an RST
packet which the other side acknowledges and both close their sockets.
Until that happens, however, both sides will keep their socket open indefinitely. This leaves open the possibility that one side may close their socket, either intentionally or due to some error, without informing the other end via RST
. In order to detect this scenario and close stale connections the TCP Keep Alive process is used.
There are three configurable properties that determine how Keep-Alives work. On Linux they are1:
tcp_keepalive_time
tcp_keepalive_probes
tcp_keepalive_intvl
The process works like this:
tcp_keepalive_time
seconds, send a single empty ACK
packet.1ACK
of its own?
tcp_keepalive_intvl
seconds, then send another ACK
ACK
probes that have been sent equals tcp_keepalive_probes
.RST
and terminate the connection.This process is enabled by default on most operating systems, and thus dead TCP connections are regularly pruned once the other end has been unresponsive for 2 hours 11 minutes (7200 seconds + 75 * 9 seconds).
Since the process doesn't start until a connection has been idle for two hours by default, stale TCP connections can linger for a very long time before being pruned. This can be especially harmful for expensive connections such as database connections.
According to RFC 1122 4.2.3.6, responding to and/or relaying TCP Keep-Alive packets is optional:
Implementors MAY include "keep-alives" in their TCP implementations, although this practice is not universally accepted. If keep-alives are included, the application MUST be able to turn them on or off for each TCP connection, and they MUST default to off.
...
It is extremely important to remember that ACK segments that contain no data are not reliably transmitted by TCP.
The reasoning being that Keep-Alive packets contain no data and are not strictly necessary and risk clogging up the tubes of the interwebs if overused.
In practice however, my experience has been that this concern has dwindled over time as bandwidth has become cheaper; and thus Keep-Alive packets are not usually dropped. Amazon EC2 documentation for instance gives an indirect endorsement of Keep-Alive, so if you're hosting with AWS you are likely safe relying on Keep-Alive, but your mileage may vary.
Unfortunately since TCP connections are managed on the OS level, Java does not support configuring timeouts on a per-socket level such as in java.net.Socket
. I have found some attempts3 to use Java Native Interface (JNI) to create Java sockets that call native code to configure these options, but none appear to have widespread community adoption or support.
Instead, you may be forced to apply your configuration to the operating system as a whole. Be aware that this configuration will affect all TCP connections running on the entire system.
The currently configured TCP Keep-Alive settings can be found in
/proc/sys/net/ipv4/tcp_keepalive_time
/proc/sys/net/ipv4/tcp_keepalive_probes
/proc/sys/net/ipv4/tcp_keepalive_intvl
You can update any of these like so:
# Send first Keep-Alive packet when a TCP socket has been idle for 3 minutes
$ echo 180 > /proc/sys/net/ipv4/tcp_keepalive_time
# Send three Keep-Alive probes...
$ echo 3 > /proc/sys/net/ipv4/tcp_keepalive_probes
# ... spaced 10 seconds apart.
$ echo 10 > /proc/sys/net/ipv4/tcp_keepalive_intvl
Such changes will not persist through a restart. To make persistent changes, use sysctl
:
sysctl -w net.ipv4.tcp_keepalive_time=180 net.ipv4.tcp_keepalive_probes=3 net.ipv4.tcp_keepalive_intvl=10
The currently configured settings can be viewed with sysctl
:
$ sysctl net.inet.tcp | grep -E "keepidle|keepintvl|keepcnt"
net.inet.tcp.keepidle: 7200000
net.inet.tcp.keepintvl: 75000
net.inet.tcp.keepcnt: 8
Of note, Mac OS X defines keepidle
and keepintvl
in units of milliseconds as opposed to Linux which uses seconds.
The properties can be set with sysctl
which will persist these settings across reboots:
sysctl -w net.inet.tcp.keepidle=180000 net.inet.tcp.keepcnt=3 net.inet.tcp.keepintvl=10000
Alternatively, you can add them to /etc/sysctl.conf
(creating the file if it doesn't exist).
$ cat /etc/sysctl.conf
net.inet.tcp.keepidle=180000
net.inet.tcp.keepintvl=10000
net.inet.tcp.keepcnt=3
I don't have a Windows machine to confirm, but you should find the respective TCP Keep-Alive settings in the registry at
\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\TCPIP\Parameters
Footnotes
1. See man tcp
for more information.
2. This packet is often referred to as a "Keep-Alive" packet, but within the TCP specification it is just a regular ACK
packet. Applications like Wireshark are able to label it as a "Keep-Alive" packet by meta-analysis of the sequence and acknowledgement numbers it contains in reference to the preceding communications on the socket.
3. Some examples I found from a basic Google search are lucwilliams/JavaLinuxNet and flonatel/libdontdie.
Download and install Python 3.6 and then change the system path environment variable to that of python 3.6 and delete the python 3.7 path system environment variable. Restart pc for results.
Here is an actual working version of the above async foreach variants with sequential processing:
public static async Task ForEachAsync<T>(this List<T> enumerable, Action<T> action)
{
foreach (var item in enumerable)
await Task.Run(() => { action(item); }).ConfigureAwait(false);
}
Here is the implementation:
public async void SequentialAsync()
{
var list = new List<Action>();
Action action1 = () => {
//do stuff 1
};
Action action2 = () => {
//do stuff 2
};
list.Add(action1);
list.Add(action2);
await list.ForEachAsync();
}
What's the key difference? .ConfigureAwait(false);
which keeps the context of main thread while async sequential processing of each task.
This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?
In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.
See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html
Some lambda function :
import org.junit.Test;
import java.awt.event.ActionListener;
import java.util.function.Function;
public class TestLambda {
@Test
public void testLambda() {
System.out.println("test some lambda function");
////////////////////////////////////////////
//1-any input | any output:
//lambda define:
Runnable lambda1 = () -> System.out.println("no parameter");
//lambda execute:
lambda1.run();
////////////////////////////////////////////
//2-one input(as ActionEvent) | any output:
//lambda define:
ActionListener lambda2 = (p) -> System.out.println("One parameter as action");
//lambda execute:
lambda2.actionPerformed(null);
////////////////////////////////////////////
//3-one input | by output(as Integer):
//lambda define:
Function<String, Integer> lambda3 = (p1) -> {
System.out.println("one parameters: " + p1);
return 10;
};
//lambda execute:
lambda3.apply("test");
////////////////////////////////////////////
//4-two input | any output
//lambda define:
TwoParameterFunctionWithoutReturn<String, Integer> lambda4 = (p1, p2) -> {
System.out.println("two parameters: " + p1 + ", " + p2);
};
//lambda execute:
lambda4.apply("param1", 10);
////////////////////////////////////////////
//5-two input | by output(as Integer)
//lambda define:
TwoParameterFunctionByReturn<Integer, Integer> lambda5 = (p1, p2) -> {
System.out.println("two parameters: " + p1 + ", " + p2);
return p1 + p2;
};
//lambda execute:
lambda5.apply(10, 20);
////////////////////////////////////////////
//6-three input(Integer,Integer,String) | by output(as Integer)
//lambda define:
ThreeParameterFunctionByReturn<Integer, Integer, Integer> lambda6 = (p1, p2, p3) -> {
System.out.println("three parameters: " + p1 + ", " + p2 + ", " + p3);
return p1 + p2 + p3;
};
//lambda execute:
lambda6.apply(10, 20, 30);
}
@FunctionalInterface
public interface TwoParameterFunctionWithoutReturn<T, U> {
public void apply(T t, U u);
}
@FunctionalInterface
public interface TwoParameterFunctionByReturn<T, U> {
public T apply(T t, U u);
}
@FunctionalInterface
public interface ThreeParameterFunctionByReturn<M, N, O> {
public Integer apply(M m, N n, O o);
}
}
Try this:
using System.ComponentModel;
youtItemsControl.Items.SortDescriptions.Add(new SortDescription("yourFavoritePropertyFromItem",ListSortDirection.Ascending);
The simplest solution is create a JavaScript function and call it for the Ajax success
callback.
function callServerAsync(){
$.ajax({
url: '...',
success: function(response) {
successCallback(response);
}
});
}
function successCallback(responseObj){
// Do something like read the response and show data
alert(JSON.stringify(responseObj)); // Only applicable to JSON response
}
function foo(callback) {
$.ajax({
url: '...',
success: function(response) {
return callback(null, response);
}
});
}
var result = foo(function(err, result){
if (!err)
console.log(result);
});
You can store a reference to that timeout, and then call clearTimeout
on that reference.
// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);
// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);
// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);
I had same exception in a custom binding
scenario. Anybody using this approach, can check this too.
I was actually adding the service reference from a local WSDL
file. It got added successfully and required custom binding was added to config file. However, the actual service was https; not http. So I changed the httpTransport elemet as httpsTransport
. This fixed the problem
<system.serviceModel>
<bindings>
<customBinding>
<binding name="MyBindingConfig">
<textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
messageVersion="Soap11" writeEncoding="utf-8">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</textMessageEncoding>
<!--Manually changed httpTransport to httpsTransport-->
<httpsTransport manualAddressing="false" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
bypassProxyOnLocal="false"
decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="65536"
proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
useDefaultWebProxy="true" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="https://mainservices-certint.mycompany.com/Services/HRTest"
binding="customBinding" bindingConfiguration="MyBindingConfig"
contract="HRTest.TestWebserviceManagerImpl" name="TestWebserviceManagerImpl" />
</client>
</system.serviceModel>
References
All of these schemes, except AES and Blowfish, have known vulnerabilities and should not be used.
However, Blowfish has been replaced by Twofish.
Such as
VERSION=1.0.0
deploy.sh
INPUTFILE=docker-compose.yml
RESULT_NAME=docker-compose.product.yml
NAME=test
prepare() {
local inFile=$(pwd)/$INPUTFILE
local outFile=$(pwd)/$RESULT_NAME
cp $inFile $outFile
while read -r line; do
OLD_IFS="$IFS"
IFS="="
pair=($line)
IFS="$OLD_IFS"
sed -i -e "s/\${${pair[0]}}/${pair[1]}/g" $outFile
done <.env
}
deploy() {
docker stack deploy -c $outFile $NAME
}
prepare
deploy
The problem that I had with the above is that I wanted to associate a short cut key with a macro in an xlam which has no visible interface. I found that the folllowing worked
To associate a short cut key with a macro
In Excel (not VBA) on the Developer Tab click Macros - no macros will be shown Type the name of the Sub The Options button should then be enabled Click it Ctrl will be the default Hold down Shift and press the letter you want eg Shift and A will associate Ctrl-Shift-A with the Sub
This is working for me
Podfile:
platform :ios, '9.0'
use_frameworks!
target '<Your Target Name>' do
pod 'SwiftGifOrigin', '~> 1.7.0'
end
Usage:
// An animated UIImage
let jeremyGif = UIImage.gif(name: "jeremy")
// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "jeremy")
// A UIImageView with async loading from asset catalog(from iOS9)
let imageView = UIImageView()
imageView.loadGif(asset: "jeremy")
For more information follow this link: https://github.com/swiftgif/SwiftGif
git checkout master
That's result something like this:
Warning: you are leaving 2 commits behind, not connected to
any of your branches:
1e7822f readme
0116b5b returned to clean django
If you want to keep them by creating a new branch, this may be a good time to do so with:
git branch new_branch_name 1e7822f25e376d6a1182bb86a0adf3a774920e1e
So, let's do it:
git merge 1e7822f25e376d6a1182bb86a0adf3a774920e1e
For me this problem occurred because I develop in two different environments with the same files. The newer environment converts the file structure and works fine then when I go back to the old environment I get this error. After messing around for a while trying to figure this out here is the solution I use:
1) rename project.properties to default.properties
2) edit .classpath file to remove the line:
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
4) Restart eclipse and/or clean the projects (may not be necessary)
Try any of the following solutions. I get errors with adb every now and then. And one of the following always works.
Solution 1
Open command prompt as administrator and enter
adb kill-server
adb start-server
Solution 2
Install drivers for your phone if you're not testing on emulator.
Solution 3
Open android sdk manager and install "Google USB Driver" from extras folder. (attached screenshot)
Android SDK Google USB Driver missing
Solution 4
Go to settings > Developer Options > Enable USB Debugging.
(If you don't see Developer Options, Go to Settings > About Phone > Keep tapping "Build number" until it says "You're a developer!"
I got a similar error and hit this page while searching the solution.
With Qt this error can happen if you forget to add the QT_WRAP_CPP( ... )
step in your build to run meta object compiler (moc). Including the Qt header is not sufficient.
If it´s in the global scope it´s better to use:
function foo()
{
alert('foo');
}
var a = 'foo';
window[a]();
than eval()
. Because eval()
is evaaaaaal.
Exactly like Nosredna said 40 seconds before me that is >.<
Just a minor change to Jesse Crossen's answer that made it work perfectly for me:
instead of:
CGSize titleSize = button.titleLabel.frame.size;
I have used this:
CGSize titleSize = [button.titleLabel.text sizeWithAttributes: @{NSFontAttributeName:button.titleLabel.font}];
I found the solution for this problem here. Don't forget to allow verb OPTIONS on IIS app service handler.
Works fine. Thank you André Pedroso. :-)
You Could try the other format for the case statement
CASE WHEN Product.type_id = 10
THEN
(
Select Statement
)
ELSE
(
Other select statement
)
END
FROM Product
WHERE Product.product_id = $pid
See http://msdn.microsoft.com/en-us/library/ms181765.aspx for more information.
This is a pretty common issue. The solution is to loop backwards:
for (var i = Auction.auctions.length - 1; i >= 0; i--) {
Auction.auctions[i].seconds--;
if (Auction.auctions[i].seconds < 0) {
Auction.auctions.splice(i, 1);
}
}
It doesn't matter if you're popping them off of the end because the indices will be preserved as you go backwards.
I would add another two arguments:
An img tag is good if you need to resize the image. E.g. if the original image is 100px by 100 px, and you want it to be 80px by 80px, you can set the CSS width and height of the img tag. I don't know of any good way to do this using background-image. EDIT: This can now also be done with a background-image, using the background-size
CSS3 attribute.
Using background-image is good when you need to dynamically switch between sprites. E.g. if you have a button image, and you want a separate image displayed when the cursor is hovering over the element, you can use a background image containing both the normal and hover sprites, and dynamically change the background-position.
If you are using windows then try with CTRL,SHIFT,+ and for decreasing font size you can use CTRL,SHIFT,-
You simply have to set the state
of the your button self.x
to normal
:
self.x['state'] = 'normal'
or
self.x.config(state="normal")
This code would go in the callback for the event that will cause the Button to be enabled.
Also, the right code should be:
self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
self.x.pack(side=LEFT)
The method pack
in Button(...).pack()
returns None
, and you are assigning it to self.x
. You actually want to assign the return value of Button(...)
to self.x
, and then, in the following line, use self.x.pack()
.
The DateTime.Ticks
property gets the number of ticks that represent the date and time.
10,000 Ticks is a millisecond (10,000,000 ticks per second).
As others said, libreoffice
can convert xls files to csv. The problem for me was the sheet selection.
This libreoffice Python script does a fine job at converting a single sheet to CSV.
Usage is:
./libreconverter.py File.xls:"Sheet Name" output.csv
The only downside (on my end) is that --headless
doesn't seem to work. I have a LO window that shows up for a second and then quits.
That's OK with me, it's the only tool that does the job rapidly.
If someone is using @Sceduled this might work for you.
@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")
This worked for me.
Use the following expression:
^[a-zA-Z0-9]*$
ie:
using System.Text.RegularExpressions;
Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
...
}
To parse the age:
Age age;
if (Enum.TryParse(typeof(Age), "New_Born", out age))
MessageBox.Show("Defined"); // Defined for "New_Born, 1, 4 , 8, 12"
To see if it is defined:
if (Enum.IsDefined(typeof(Age), "New_Born"))
MessageBox.Show("Defined");
Depending on how you plan to use the Age
enum, flags may not be the right thing. As you probably know, [Flags]
indicates you want to allow multiple values (as in a bit mask). IsDefined
will return false for Age.Toddler | Age.Preschool
because it has multiple values.
In my case an unexpected error notice in the source code stopped the facebook crawler from parsing the (correctly set) og-meta tags.
I was using the HTTP_ACCEPT_LANGUAGE
header, which worked fine for regular browser requests but not for the crawler, as it obviously won't use/set it.
Therefore, it was crucial for me to use the facebook's debugger feature See exactly what our scraper sees for your URL
, as the error notice only could only be seen there (but not through the regular 'view source code'-browser feature).
It should be getResource("/install.xml");
The resource names are relative to where the getClass() class resides, e.g. if your test is org/example/foo/MyTest.class
then getResource("install.xml")
will look in org/example/foo/install.xml
.
If your install.xml
is in src/test/resources
, it's in the root of the classpath, hence you need to prepend the resource name with /
.
Also, if it works only sometimes, then it might be because Eclipse has cleaned the output directory (e.g. target/test-classes
) and the resource is simply missing from the runtime classpath. Verify that using the Navigator view of Eclipse instead of the Package explorer. If the files is missing, run the mvn package
goal.
You can truncate text based on CSS. It helps to truncate a text-based on width not fix character.
Example
CSS
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.content {
width:100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
HTML
<div class="content">
<span class="truncate">Lorem Ipsum is simply dummied text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
</div>
Note: this code use full for one line not for more than one.
Ketan's Solution is best if you want to do it by Angular
If you're not set on rolling your own solution, check out this jQuery plugin:
malsup.com/jquery/form/
It will do that and more for you. It's highly recommended.
The only property corresponding in WPF to the
Winforms property: TextBox.Multiline = true
is the WPF property: TextBox.AcceptsReturn = true
.
<TextBox AcceptsReturn="True" ...... />
All other settings, such as VerticalAlignement
, WordWrap
etc., only control how the TextBox interacts in the UI but do not affect the Multiline
behaviour.
Update 2015/06
As jQuery has evolved since the question was posted, the recommended approach now is using $.on
$(document).ready(function() {
$("input[name=group2]").on( "change", function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
} );
});
or outside $.ready()
$(document).on( "change", "input[name=group2]", function() { ... } );
Original answer
You should use .change()
event handler:
$(document).ready(function(){
$("input[name=group2]").change(function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
});
});
should work
Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.
First, your IntentFilter must contain an event.
static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
Second, when you send a broadcast, use this same action:
Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);
Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.
Fourth, is your service declared in the AndroidManifest.xml?
A solution that works for me (July 2017), is to utilize ESLint. As everybody knows, you can use the linter in multiple ways, globally or locally. I use it locally and with the google style guide. They way I set it up is as follow...
cd to your working directory
npm init
npm install --save-dev eslint
node_modules/.bin/eslint --init
I use google style and json config file
Now you will have a .eslintrc.json
file the root of your working directory. You can open that file and modify as you please utilizing the eslint rules. Next cmd+,
to open vscode
system preferences. In the search bar type eslint
and look for "eslint.autoFixOnSave": false
. Copy the setting and pasted in the user settings file and change false
to true
. Hope this can help someone utilizing vscode.
Can you provide an example, because put should work fine as well?
Documentation -
The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url
) -
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "name=John&location=Boston",
success: function(data) {
alert('Load was performed.');
}
});
Demo tested from jQuery 1.3.2 onwards on Chrome.
Well, if the string really ends with the pattern, you could do this:
str = str.replace(new RegExp(list[i] + '$'), 'finish');
Based on @Dave Syer, @kaliatech and @asmaier answers the springboot v2+ way would be:
@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class StaticResourceConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String myExternalFilePath = "file:///C:/temp/whatever/m/";
registry.addResourceHandler("/m/**").addResourceLocations(myExternalFilePath);
}
}
Raw HTML is actually perfectly valid in markdown. For instance:
Normal *markdown* paragraph.
<p class="myclass">This paragraph has a class "myclass"</p>
Just make sure the HTML is not inside a code block.
This is a simple way to do client-side validation BEFORE the confirmation. It makes use of the built in ASP.NET validation javascript.
<script type="text/javascript">
function validateAndConfirm() {
Page_ClientValidate("GroupName"); //'GroupName' is the ValidationGroup
if (Page_IsValid) {
return confirm("Are you sure?");
}
return false;
}
</script>
<asp:TextBox ID="IntegerTextBox" runat="server" Width="100px" MaxLength="6" />
<asp:RequiredFieldValidator ID="reqIntegerTextBox" runat="server" ErrorMessage="Required"
ValidationGroup="GroupName" ControlToValidate="IntegerTextBox" />
<asp:RangeValidator ID="rangeTextBox" runat="server" ErrorMessage="Invalid"
ValidationGroup="GroupName" Type="Integer" ControlToValidate="IntegerTextBox" />
<asp:Button ID="SubmitButton" runat="server" Text="Submit" ValidationGroup="GroupName"
OnClick="SubmitButton_OnClick" OnClientClick="return validateAndConfirm();" />
Source: Client Side Validation using ASP.Net Validator Controls from Javascript
$M2_HOME
is used sometimes, for example, to install Takari Extensions for Apache Maven
One way to find $M2_HOME
value is to search for mvn
:
sudo find / -name "mvn" 2>/dev/null
And, probably it will be: /opt/maven/
You mean like this?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
install sqlescapy package:
pip install sqlescapy
then you can escape variables in you raw query
from sqlescapy import sqlescape
query = """
SELECT * FROM "bar_table" WHERE id='%s'
""" % sqlescape(user_input)
This question doesn't really have anything to do with how require()
works. Basically, whatever you set module.exports
to in your module will be returned from the require()
call for it.
This would be equivalent to:
var square = function(width) {
return {
area: function() {
return width * width;
}
};
}
There is no need for the new
keyword when calling square
. You aren't returning the function instance itself from square
, you are returning a new object at the end. Therefore, you can simply call this function directly.
For more intricate arguments around new
, check this out: Is JavaScript's "new" keyword considered harmful?
I would like to add to the answers of BalusC and Pascal Thivent another common use of insertable=false, updatable=false
:
Consider a column that is not an id but some kind of sequence number. The responsibility for calculating the sequence number may not necessarily belong to the application.
For example, sequence number starts with 1000 and should increment by one for each new entity. This is easily done, and very appropriately so, in the database, and in such cases these configurations makes sense.
You have to enable curl with php.
Here is the instructions for same
I would like to propose a generalization with awk.
When the file is made by blocks of a fixed size and the lines to delete are repeated for each block, awk can work fine in such a way
awk '{nl=((NR-1)%2000)+1; if ( (nl<714) || ((nl>1025)&&(nl<1029)) ) print $0}'
OriginFile.dat > MyOutputCuttedFile.dat
In this example the size for the block is 2000 and I want to print the lines [1..713] and [1026..1029].
NR
is the variable used by awk to store the current line number.%
gives the remainder (or modulus) of the division of two integers;nl=((NR-1)%BLOCKSIZE)+1
Here we write in the variable nl the line number inside the current block. (see below)||
and &&
are the logical operator OR and AND.print $0
writes the full lineWhy ((NR-1)%BLOCKSIZE)+1:
(NR-1) We need a shift of one because 1%3=1, 2%3=2, but 3%3=0.
+1 We add again 1 because we want to restore the desired order.
+-----+------+----------+------------+
| NR | NR%3 | (NR-1)%3 | (NR-1)%3+1 |
+-----+------+----------+------------+
| 1 | 1 | 0 | 1 |
| 2 | 2 | 1 | 2 |
| 3 | 0 | 2 | 3 |
| 4 | 1 | 0 | 1 |
+-----+------+----------+------------+
This guide was helpful for me http://wiki.eclipse.org/EGit/User_Guide#Resolving_a_merge_conflict.
UPDATED Just a note on that about my procedure, this is how I proceed:
It is dangerous in some cases but it is very usefull to avoid to use external tool like Git Extension or Source Tree
it's as specified in the JLS (15.22.2):
When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.
For &, the result value is true if both operand values are true; otherwise, the result is false.
For ^, the result value is true if the operand values are different; otherwise, the result is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
The "trick" is that &
is an Integer Bitwise Operator as well as an Boolean Logical Operator. So why not, seeing this as an example for operator overloading is reasonable.
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:
<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />
The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):
var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;
Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...
You give the name of your file, the path of the directory to search, and let it make the job.
private static String getPath(String drl, String whereIAm) {
File dir = new File(whereIAm); //StaticMethods.currentPath() + "\\src\\main\\resources\\" +
for(File e : dir.listFiles()) {
if(e.isFile() && e.getName().equals(drl)) {return e.getPath();}
if(e.isDirectory()) {
String idiot = getPath(drl, e.getPath());
if(idiot != null) {return idiot;}
}
}
return null;
}
I added below two lines in gradle.properties file
android.useAndroidX=true
android.enableJetifier=true
then I got the following error
error: package android.support.v7.app does not exist
import android.support.v7.app.AlertDialog;
^
I have removed the imports and added below line
import static android.app.AlertDialog.*;
And the classes which are extended from AppCompactActivity, added the below line. (For these errors you just need to press alt+enter in android studio which will import the correct library for you. Like this you can resolve all the errors)
import androidx.appcompat.app.AppCompatActivity;
In your xml file if you have used any
<android.support.v7.widget.Toolbar
replace it with androidx.appcompat.widget.Toolbar
then in your java code
import androidx.appcompat.widget.Toolbar;
I'm surprised no one mentioned the possibility to use an API to do the work.
Granted, if you want to stay secure, converting HTML to PDF directly from within the browser using javascript is not a good idea.
But here's what you can do:
When your user hit the "Print" (for example) button, you:
For a user point of view, they will receive a PDF by clicking on a button.
There are many available API that does the job, some better than others (that's not why I'm here) and a Google search will give you a lot of answers.
Depending on what is written your backend, you might be interested in PDFShift (Truth: I work there).
They offer ready to work packages for PHP, Python and Node.js. All you have to do is install the package, create an account, indicate your API key and you are all set!
The advantage of the API is that they work well in all languages. All you have to do is a request (generally POST) containing the data you want to be converted and get a PDF back. And depending on your usage, it's generally free, except if you are a heavy user.
Use the built-in isinstance()
function.
import pandas as pd
def f(var):
if isinstance(var, pd.DataFrame):
print("do stuff")
Alejandro nailed it, adding clarification to the exception (Ubuntu or Debian) - I don't have the rep to add to the answer itself:
sudoers file:
sudo visudo
exception added:
www-data ALL=(ALL) NOPASSWD: ALL
Could someone tell me what I'm doing wrong?"
"bold" has never been an HTML element ("b" is the closest match).
HTML should contain structured content; publisher CSS should suggest styles for that content. That way user agents can expose the structured content with useful styling and navigational controls to users who can't see your suggested bold styling (e.g. users of search engines, totally blind users using screen readers, poorly sighted users using their own colors and fonts, geeky users using text browsers, users of voice-controlled, speaking browsers like Opera for Windows). Thus the right way to make text bold depends on why you want to style it bold. For example:
Want to distinguish headings from other text? Use heading elements ("h1" to "h6") and suggest a bold style for them within your CSS ("h1, h2, h3, h4, h5, h6 {font-weight: bold;}".
Want to embolden labels for form fields? Use a "label" element, programmatically associate it with the the relevant "select", "input" or "textarea" element by giving it a "for" attribute matching an "id" attribute on the target, and suggest a bold style for it within your CSS ("label {font-weight: bold;"}).
Want to embolden a heading for a group of related fields in a form, such as a group of radio choices? Surround them with a "fieldset" element, give it a "legend" element, and suggest a bold style for it within your CSS ("legend {font-weight: bold;}").
Want to distinguish a table caption from the table it captions? Use a "caption" element and suggest a bold style for it within your CSS ("caption {font-weight: bold;}").
Want to distinguish table headings from table data cells? Use a "th" element and suggest a bold style for it within your CSS ("th {font-weight: bold;}").
Want to distinguish the title of a referenced film or album from surrounding text? Use a "cite" element with a class ("cite class="movie-title"), and suggest a bold style for it within your CSS (".movie-title {font-weight: bold;}").
Want to distinguish a defined keyword from the surrounding text defining or explaining it? Use a "dfn" element and suggest a bold style for it within your CSS ("dfn {font-weight: bold;}").
Want to distinguish some computer code from surrounding text? Use a "code" element and suggest a bold style for it within your CSS ("code {font-weight: bold;}").
Want to distinguish a variable name from surrounding text? Use a "var" element and suggest a bold style for it within your CSS ("var {font-weight: bold;}").
Want to indicate that some text has been added as an update? Use an "ins" element and suggest a bold style for it within your CSS ("ins {font-weight: bold;}").
Want to lightly stress some text ("I love kittens!")? Use an "em" element and suggest a bold style for it within your CSS (e.g. "em {font-weight: bold;}").
Want to heavily stress some text, perhaps for a warning ("Beware the dog!")? Use a "strong" element and suggest a bold style for it within your CSS (e.g. "strong {font-weight: bold;}").
… You get the idea (hopefully).
Can't find an HTML element with the right semantics to express /why/ you want to make this particular text bold? Wrap it in a generic "span" element, give it a meaningful class name that expresses your rationale for distinguishing that text ("<span class="lede">Let me begin this news article with a sentence that summarizes it.</span>), and suggest a bold style for it within your CSS (".lede {font-weight: bold;"}. Before making up your own class names, you might want to check if there's a microformat (microformats.org) or common convention for what you want to express.
It prints the byte
in Hexadecimal format.
No format string: 13
'X2' format string: 0D
http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx
When you declare a variable, you need to declare its type - in this case: int
. Also you've put a random comma in the while
loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
You can do this easily using a mask:
<input type='text' mask="99" formControlName="percentage" placeholder="0">
99 - optional 2 digits
Don't forget to import NgxMaskModule in your module:
imports: [
NgxMaskModule.forRoot(),
]
From the numpy fft page http://docs.scipy.org/doc/numpy/reference/routines.fft.html:
When the input a is a time-domain signal and A = fft(a), np.abs(A) is its amplitude spectrum and np.abs(A)**2 is its power spectrum. The phase spectrum is obtained by np.angle(A).
Relative positioning: The element creates its own coordinate axes, at a location offset from the viewport coordinate axis. It is Part of document flow but shifted.
Absolute positioning: An element searches for the nearest available coordinate axes among its parent elements. The element is then positioned by specifying offsets from this coordinate axis. It is removed from document normal flow.
Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.
Here's how to do it for Internet Explorer:
function copy (str)
{
//for IE ONLY!
window.clipboardData.setData('Text',str);
}
I had this problem on windows.
This is the solution:
To pass '' for NULL you should disable STRICT_MODE (which is enabled by default on Windows installations)
BTW It's funny to pass '' for NULL. I don't know why they let this kind of behavior.
I had similiar problem. The quick fix I found is to change:
<div class="input-group datepicker" data-provide="datepicker">
to
<div class="input-group date" data-provide="datepicker">
allow_url_fopen
is generally set to On.
If it is not On, then you can try two things.
Create an .htaccess
file and keep it in root folder ( sometimes it may need to place it one step back folder of the root) and paste this code there.
php_value allow_url_fopen On
Create a php.ini
file (for update server php5.ini
) and keep it in root folder (sometimes it may need to place it one step back folder of the root) and paste the following code there:
allow_url_fopen = On;
I have personally tested the above solutions; they worked for me.
Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-
npm install jquery --save
Then, import $ from "jquery";
instanceof is a keyword that can be used to test if an object is of a specified type.
Example :
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}
Here is my source.
HTML:
<div class="CalendarBlock">
<input type="hidden">
</div>
CODE:
$CalendarBlock=$('.CalendarBlock');
$CalendarBlock.click(function(){
var $datepicker=$(this).find('input');
datepicker.datepicker({dateFormat: 'mm/dd/yy'});
$datepicker.focus(); });
tcping is a great tool with a very low overhead.It also has a timeout argument to make it quicker:
[root@centos_f831dfb3 ~]# tcping 10.86.151.175 22 -t 1
10.86.151.175 port 22 open.
[root@centos_f831dfb3 ~]# tcping 10.86.150.194 22 -t 1
10.86.150.194 port 22 user timeout.
[root@centos_f831dfb3 ~]# tcping 1.1.1.1 22 -t 1
1.1.1.1 port 22 closed.
That's because you created a Web Site instead of a Web Application. The cs/vb
files can only be seen in a Web Application, but in a website you can't have a separate cs/vb
file.
Edit: In the website you can add a cs file behavior like..
<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>
~/Global.asax.cs:
namespace ApplicationName
{
public partial class MyApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
}
}
}
CREATE TABLE new_table LIKE old_table;
or u can use this
CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];
I just looked and found cell|all output|clear which worked with:
Server Information: You are using Jupyter notebook.
The version of the notebook server is: 6.1.5 The server is running on this version of Python: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]
Current Kernel Information: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b)
. The first example uses the string 'key'
as the property name, and 'val'
as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1:
{ key: 'val' }
Result #2:
{ foo: 'bar', key: 'val' }
It probably shouldn't matter. You are going to get much better performance designing your algorithm to use a fixed number of threads (eg, 4 or 8 if you have 4 or 8 processors). You can do this with work queues, asynchronous IO, or something like libevent.
Memoization is keeping the results of expensive calculations and returning the cached result rather than continuously recalculating it.
Here's an example:
def doSomeExpensiveCalculation(self, input):
if input not in self.cache:
<do expensive calculation>
self.cache[input] = result
return self.cache[input]
A more complete description can be found in the wikipedia entry on memoization.
jQuery <1.9
$('#inputId').attr('readonly', true);
jQuery 1.9+
$('#inputId').prop('readonly', true);
Read more about difference between prop and attr
This is the best method:
public static boolean isValidEmail(String enteredEmail){
String EMAIL_REGIX = "^[\\\\w!#$%&’*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$";
Pattern pattern = Pattern.compile(EMAIL_REGIX);
Matcher matcher = pattern.matcher(enteredEmail);
return ((!enteredEmail.isEmpty()) && (enteredEmail!=null) && (matcher.matches()));
}
Sources:- http://howtodoinjava.com/2014/11/11/java-regex-validate-email-address/
There are many options, for example:
import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))
You can run loop for each column but this is the simplest way to convert string column into integer.
I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:
<xsl:value-of select="count(//td[text()=' '])" />
The value returned is 1, which is the correct value in my test case.
However, I did have to declare nbsp as an entity within my XML and XSL using the following:
<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp " "> ]>
I'm not sure if that helps you, but I was able to actually find nbsp using an XPath expression.
Edit: My code sample actually contains the characters ' ' but the JavaScript syntax highlight converts it to the space character. Don't be mislead!
try this
self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0
self.mainImageView.clipsToBounds = true
You could create a list of Object like List<Object> list = new ArrayList<Object>()
. As all classes implementation extends implicit or explicit from java.lang.Object
class, this list can hold any object, including instances of Employee
, Integer
, String
etc.
When you retrieve an element from this list, you will be retrieving an Object
and no longer an Employee
, meaning you need to perform a explicit cast in this case as follows:
List<Object> list = new ArrayList<Object>();
list.add("String");
list.add(Integer.valueOf(1));
list.add(new Employee());
Object retrievedObject = list.get(2);
Employee employee = (Employee)list.get(2); // explicit cast
I just had this issue.. I just added the MinGW\bin directory to the path environment variable, and it solved the issue.
In the top level of the IIS Manager (above Sites), you should see the Application Pools tree node. Right click on "Application Pools", choose "Add Application Pool".
Give it a name, choose .NET Framework 4.0 and either Integrated or Classic mode.
When you add or edit a web site, your new application pools will now show up in the list.
why not simply
new Date (timestamp);
A date is a date, the formatting of it is a different matter.
Since Angular 2 went to RC 0, /angular2/typings/browser.d.ts is no longer part of the Angular 2 distribution. The file can be installed separately.
From here: https://github.com/angular/angular/issues/8513 there are a few options. The one that worked for me was:
typings install es6-shim --ambient --save
// In your app.ts
/// <reference path="typings/browser.d.ts" />
You can use the listings package. It supports many different languages and there are lots of options for customising the output.
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=html]
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{lstlisting}
\end{document}
In the case of some programs, these errors are normal and should not be fixed.
I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.
If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.
use Illuminate\Database\Eloquent\Builder;
$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
$query = $query->where('orders.customer_id', 'NULL')
});
$query = $query->get();
You can try this code:
public void itemClicked(View v) {
//code to check if this checkbox is checked!
if(((Checkbox)v).isChecked()){
// code inside if
}
}
As long as we're using jQuery (> v1.8), we can parse the incoming string with $.parseHTML().
$('.tooltip').tooltip({
content: function () {
var tooltipContent = $('<div />').html( $.parseHTML( $(this).attr('title') ) );
return tooltipContent;
},
});
We'll parse the incoming string's attribute for unpleasant things, then convert it back to jQuery-readable HTML. The beauty of this is that by the time it hits the parser the strings are already concatenates, so it doesn't matter if someone is trying to split the script tag into separate strings. If you're stuck using jQuery's tooltips, this appears to be a solid solution.
"A final variable can only be assigned once"
*Reflection*
- "wowo wait, hold my beer".Freeze of final
fields happen in two scenarios:
Let's break the law
public class HoldMyBeer
{
final int notSoFinal;
public HoldMyBeer()
{
notSoFinal = 1;
}
static void holdIt(HoldMyBeer beer, int yetAnotherFinalValue) throws Exception
{
Class<HoldMyBeer> cl = HoldMyBeer.class;
Field field = cl.getDeclaredField("notSoFinal");
field.setAccessible(true);
field.set(beer, yetAnotherFinalValue);
}
public static void main(String[] args) throws Exception
{
HoldMyBeer beer = new HoldMyBeer();
System.out.println(beer.notSoFinal);
holdIt(beer, 50);
System.out.println(beer.notSoFinal);
holdIt(beer, 100);
System.out.println(beer.notSoFinal);
holdIt(beer, 666);
System.out.println(beer.notSoFinal);
holdIt(beer, 8888);
System.out.println(beer.notSoFinal);
}
}
Output:
1
50
100
666
8888
The "final" field has been assigned 5 different "final" values (note the quotes). And it could keep being assigned different values over and over...
Why? Because reflection is like Chuck Norris, and if it wants to change the value of an initialized final field, it does. Some say he himself is the one that pushes the new values into the stack :
Code:
7: astore_1
11: aload_1
12: getfield
18: aload_1
19: bipush 50 //wait what
27: aload_1
28: getfield
34: aload_1
35: bipush 100 //come on...
43: aload_1
44: getfield
50: aload_1
51: sipush 666 //...you were supposed to be final...
60: aload_1
61: getfield
67: aload_1
68: sipush 8888 //ok i'm out whatever dude
77: aload_1
78: getfield
We show up two functions that prints a SINGLE character to binary.
void printbinchar(char character)
{
char output[9];
itoa(character, output, 2);
printf("%s\n", output);
}
printbinchar(10) will write into the console
1010
itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".
The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.
void printbincharpad(char c)
{
for (int i = 7; i >= 0; --i)
{
putchar( (c & (1 << i)) ? '1' : '0' );
}
putchar('\n');
}
printbincharpad(10) will write into the console
00001010
Now i present a function that prints out an entire string (without last null character).
void printstringasbinary(char* s)
{
// A small 9 characters buffer we use to perform the conversion
char output[9];
// Until the first character pointed by s is not a null character
// that indicates end of string...
while (*s)
{
// Convert the first character of the string to binary using itoa.
// Characters in c are just 8 bit integers, at least, in noawdays computers.
itoa(*s, output, 2);
// print out our string and let's write a new line.
puts(output);
// we advance our string by one character,
// If our original string was "ABC" now we are pointing at "BC".
++s;
}
}
Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:
1000001
1000010
110001
I'm assuming you mean that you don't care which row is used to obtain the title
, id
, and commentname
values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:
select
id,
title,
email,
commentname
from
(
select
*,
row_number() over (partition by email order by id) as RowNbr
from YourTable
) source
where RowNbr = 1
You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):
var myElement = document.getElementById('element_within_div');
var topPos = myElement.offsetTop;
The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).
Now we tell the div to scroll to that position using scrollTop
:
document.getElementById('scrolling_div').scrollTop = topPos;
If you're using the prototype JS framework, you'd do the same thing like this:
var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];
Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).
Inspired by Robert K's solution, this version does not strip HTML tags, and is just as secure.
var decode_entities = (function() {
// Remove HTML Entities
var element = document.createElement('div');
function decode_HTML_entities (str) {
if(str && typeof str === 'string') {
// Escape HTML before decoding for HTML Entities
str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';');
element.innerHTML = str;
if(element.innerText){
str = element.innerText;
element.innerText = '';
}else{
// Firefox support
str = element.textContent;
element.textContent = '';
}
}
return unescape(str);
}
return decode_HTML_entities;
})();
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]
You could just use parameter expansion:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
So try this:
var=${DEPLOY_ENV:-default_value}
There's also the ${parameter-word} form, which substitutes the default value only when parameter is unset (but not when it's null).
To demonstrate the difference between the two:
$ unset DEPLOY_ENV
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' 'default_value'
$ DEPLOY_ENV=
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' ''
Locks are a concept required in a multi-threaded system. Even with worker threads, messages are sent by value between workers so that locking is unnecessary.
I suspect you need to just set a semaphore (flagging system) between your buttons.
Template:
<select class="randomClass" id="randomId" (change) =
"filterSelected($event.target.value)">
<option *ngFor = 'let type of filterTypes' [value]='type.value'>{{type.display}}
</option>
</select>
Component:
public filterTypes = [{
value : 'New', display : 'Open'
},
{
value : 'Closed', display : 'Closed'
}]
filterSelected(selectedValue:string){
console.log('selected value= '+selectedValue)
}
If you already know size of the char*, use this instead
char* data = ...;
int size = ...;
std::string myString(data, size);
This doesn't use strlen.
EDIT: If string variable already exists, use assign():
std::string myString;
char* data = ...;
int size = ...;
myString.assign(data, size);
Yes it is Possible Will Den. we can run PHP code in tomcat server using it's own port number localhost:8080
here I'm writing some step which is so much useful for you.
How to install or run PHP on Tomcat 6 in windows
download and unzip PHP 5 to a directory, c:\php-5.2.6-Win32
- php-5.2.9-2-Win32.zip Download
download PECL 5.2.5 Win32 binaries - PECL 5.2.5 Win32 Download
rename php.ini-dist
to php.ini
in c:\php-5.2.6-Win32
Uncomment or add the line (remove semi-colon at the beginning) in php.ini
:
;extension=php_java.dll
copy php5servlet.dll
from PECL 5.2.5 to c:\php-5.2.6-Win32
copy php_java.dll
from PECL 5.2.5 to c:\php-5.2.6-Win32\ext
copy php_java.jar
from PECL 5.2.5 to tomcat\lib
create a directory named "php"
(or what ever u like) in tomcat\webapps
directory
copy phpsrvlt.jar
from PECL 5.2.5 to tomcat\webapps\php\WEB-INF\lib
Unjar or unzip phpsrvlt.jar
for unzip use winrar or winzip for unjar use : jar xfv phpsrvlt.jar
change both net\php\reflect.properties
and net\php\servlet.properties
to library=php5servlet
Recreate the jar file
-> jar cvf php5srvlt.jar net/php/.
PS: if the jar file doesnt run you have to add the Path to system variables for me I added C:\Program Files\Java\jdk1.6.0\bin; to System variables/Path
create web.xml
in tomcat\webapps\php\WEB-INF
with this content:
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">
<servlet>
<servlet-name>php</servlet-name>
<servlet-class>net.php.servlet</servlet-class>
</servlet>
<servlet>
<servlet-name>php-formatter</servlet-name>
<servlet-class>net.php.formatter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>php</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>php-formatter</servlet-name>
<url-pattern>*.phps</url-pattern>
</servlet-mapping>
</web-app>
Add PHP path( c:\php-5.2.6-Win32
) to your System or User Path in Windows enironment (Hint: Right-click and select Properties from My Computer
create test.php
for testing under tomcat\webapps\php
like
Restart tomcat
browse localhost:8080/php/test.php
Towards the second half of Create REST API using ASP.NET MVC that speaks both JSON and plain XML, to quote:
Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."
He then implements an action filter that maps the JSON to C# objects with code shown.
All I had to do was:
This allows autolayout to dynamically size the textView based on its content.
In order of preference:
{{ var|e('html_attr') }}
htmlentities($var, ENT_QUOTES | ENT_HTML5, $charset)
and make sure the rest of your document uses the same character set as $charset
. In most cases, 'UTF-8'
is the desired character set.Also, make sure you escape on output, not on input.
Via SQL as per MSDN
SET IDENTITY_INSERT sometableWithIdentity ON
INSERT INTO sometableWithIdentity
(IdentityColumn, col2, col3, ...)
VALUES
(AnIdentityValue, col2value, col3value, ...)
SET IDENTITY_INSERT sometableWithIdentity OFF
The complete error message tells you exactly what is wrong...
Cannot insert explicit value for identity column in table 'sometableWithIdentity' when IDENTITY_INSERT is set to OFF.
The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:
Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.
Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.
To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark
was used.
require_relative 'base'
require 'benchmark'
class LargeDOM < Base
LOCATORS = {
nested_sibling_traversal: {
css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
},
nested_sibling_traversal_by_class: {
css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
},
table_header_id_and_class: {
css: "table#large-table thead .column-50",
xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
},
table_header_id_class_and_direct_desc: {
css: "table#large-table > thead .column-50",
xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
},
table_header_traversing: {
css: "table#large-table thead tr th:nth-of-type(50)",
xpath: "//table[@id='large-table']//thead//tr//th[50]"
},
table_header_traversing_and_direct_desc: {
css: "table#large-table > thead > tr > th:nth-of-type(50)",
xpath: "//table[@id='large-table']/thead/tr/th[50]"
},
table_cell_id_and_class: {
css: "table#large-table tbody .column-50",
xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
},
table_cell_id_class_and_direct_desc: {
css: "table#large-table > tbody .column-50",
xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
},
table_cell_traversing: {
css: "table#large-table tbody tr td:nth-of-type(50)",
xpath: "//table[@id='large-table']//tbody//tr//td[50]"
},
table_cell_traversing_and_direct_desc: {
css: "table#large-table > tbody > tr > td:nth-of-type(50)",
xpath: "//table[@id='large-table']/tbody/tr/td[50]"
}
}
attr_reader :driver
def initialize(driver)
@driver = driver
visit '/large'
is_displayed?(id: 'siblings')
super
end
# The benchmarking approach was borrowed from
# http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
def benchmark
Benchmark.bmbm(27) do |bm|
LOCATORS.each do |example, data|
data.each do |strategy, locator|
bm.report(example.to_s + " using " + strategy.to_s) do
begin
ENV['iterations'].to_i.times do |count|
find(strategy => locator)
end
rescue Selenium::WebDriver::Error::NoSuchElementError => error
puts "( 0.0 )"
end
end
end
end
end
end
end
NOTE: The output is in seconds, and the results are for the total run time of 100 executions.
In Table Form:
In Chart Form:
You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.
You CAN do it using only xml shapes - just use layer-list AND negative padding like this:
<layer-list>
<item>
<shape>
<solid android:color="#ffffff" />
<padding android:top="20dp" />
</shape>
</item>
<item>
<shape>
<gradient android:endColor="#ffffff" android:startColor="#efefef" android:type="linear" android:angle="90" />
<padding android:top="-20dp" />
</shape>
</item>
</layer-list>
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
export class LanguageComponent implemnts OnInit {
displayedColumns = ['name', 'native', 'code', 'leavel'];
user: any;
private update = new Subject<void>();
update$ = this.update.asObservable();
constructor(private authService: AuthService, private dialog: MatDialog) {}
ngOnInit() {
this.update$.subscribe(() => { this.refresh()});
}
setUpdate() {
this.update.next();
}
add() {
this.dialog.open(LanguageAddComponent, {
data: { user: this.user },
}).afterClosed().subscribe(result => {
this.setUpdate();
});
}
refresh() {
this.authService.getAuthenticatedUser().subscribe((res) => {
this.user = res;
this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);
});
}
}
Step 1: convert the string to an array using the str_split
function
$array = str_split($your_string);
Step 2: loop through the newly created array
foreach ($array as $char) {
echo $char;
}
You can check the PHP docs for more information: str_split
To your first question:
I would go with Paul R's comment and terminate with '\0'
. But the value 0
itself works also fine. A matter of taste. But don't use the MACRO NULL
which is meant for pointers.
To your second question:
If your string is not terminated with\0
, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'
.
There are two better solutions
display: inline-block;
OR
display: table;
Out of these two display:table;
is better, because display: inline-block;
adds an extra margin.
For display:inline-block;
you can use the negative margin method to fix the extra space
You can count option tag first, and then set the count for size attribute. For example, in PHP you can count the array and then use a foreach loop for the array.
<?php $count = count($array); ?>
<select size="<?php echo $count; ?>" style="height:100%;">
<?php foreach ($array as $item){ ?>
<option value="valueItem">Name Item</option>
<?php } ?>
</select>
.highlight { background-color: papayawhip; }
$("#table tr").click(function() {
$("#table tr").removeClass("highlight");
$(this).addClass("highlight");
});
I would suggest taking a look JetBrains AppCode IDE. It has a Reformat Code command. I have come from a C# background and used Visual Studio with Jetbrains Resharper plugin, so learning AppCode has been a pleasure because many of the features in Resharper also exist in AppCode!
Theres too many features to list here but could well be worth checking out
To unpack a dictionary into keyword arguments, use **
. Also,, new-style formatting supports referring to attributes of objects and items of mappings:
'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example
I found this answer on msdn, that explains marking the file as Content and then Copy to Output = If Newer. See article below:
GH
library(lubridate)
if your date format is like this '04/24/2017 05:35:00'then change it like below
prods.all$Date2<-gsub("/","-",prods.all$Date2)
then change the date format
parse_date_time(prods.all$Date2, orders="mdy hms")
Use:
overflow: hidden;
height: 100%;
position: fixed;
width: 100%;
This type of error can also occur when the excel file is corrupted for some reason
you all forget about quantifier n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp
here best solution
str = str.replace(/\s{2,}/g, ' ');
Here's another option for those not using heatmap.2
(aheatmap
is good!)
Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:
breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)
There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).
Headers or trailers (?1) like “sign-off” (?2) is, in current
practice in projects like Git and Linux, effectively structured metadata
for the commit. These are all appended to the end of the commit message,
after the “free form” (unstructured) part of the body of the message.
These are token–value (or key–value) pairs typically delimited by a
colon and a space (:?
).
Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:
mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
This is an ancient bug that was actually attempted to be fixed once
(badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
get_user_pages() race for write access") but that was then undone due to
problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").
In the meantime, the s390 situation has long been fixed, and we can now
fix it by checking the pte_dirty() bit properly (and do it better). The
s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
software dirty bits") which made it into v3.9. Earlier kernels will
have to look at the page state itself.
Also, the VM has become more scalable, and what used a purely
theoretical race back then has become easier to trigger.
To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
we already did a COW" rather than play racy games with FOLL_WRITE that
is very fundamental, and then use the pte dirty flag to validate that
the FOLL_COW flag is still valid.
Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
Acked-by: Hugh Dickins <[email protected]>
Reviewed-by: Michal Hocko <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: Greg Thelen <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
In addition to the “sign-off” trailer in the above, there is:
Other projects, like for example Gerrit, have their own headers and associated meaning for them.
See: https://git.wiki.kernel.org/index.php/CommitMessageConventions
It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.
[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.
break x if ((int)strcmp(y, "hello")) == 0
On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!
If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su
then apt-get install -y wget
If you know the sting will always be in the same format, first split the string based on .
and store the string at the first index in a variable. Then split the string in the second index based on -
and store indexes 0, 1 and 2. Finally, split index 2 of the previous array based on .
and you should have obtained all of the relevant fields.
Refer to the following snippet:
String[] tmp = pdfName.split(".");
String val1 = tmp[0];
tmp = tmp[1].split("-");
String val2 = tmp[0];
...
It can be done by using pytest. Just write the file test_me.py
with content:
import pytest
@pytest.mark.parametrize('name, left, right', [['foo', 'a', 'a'],
['bar', 'a', 'b'],
['baz', 'b', 'b']])
def test_me(name, left, right):
assert left == right, name
And run your test with command py.test --tb=short test_me.py
. Then the output will look like:
=========================== test session starts ============================
platform darwin -- Python 2.7.6 -- py-1.4.23 -- pytest-2.6.1
collected 3 items
test_me.py .F.
================================= FAILURES =================================
_____________________________ test_me[bar-a-b] _____________________________
test_me.py:8: in test_me
assert left == right, name
E AssertionError: bar
==================== 1 failed, 2 passed in 0.01 seconds ====================
It is simple! Also pytest has more features like fixtures
, mark
, assert
, etc.