svg.selectAll("rect")
.attr('x',function(d,i){
// get x coord
console.log(this.getBBox().x, 'or', d3.select(this).attr('x'))
})
.attr('y',function(d,i){
// get y coord
console.log(this.getBBox().y)
})
.attr('dx',function(d,i){
// get dx coord
console.log(parseInt(d3.select(this).attr('dx')))
})
hsThumbList.setLayoutParams(new LayoutParams(100, 400));
I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:
<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>
Then you can trigger all links with the .link
class attached as tooltips like so:
$('.link').tooltip()
Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel
attribute. With this attribute you can target all links or elements with the rel
property set to tooltip
, like so:
$('[rel=tooltip]').tooltip()
And your links would look like something like this:
<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>
Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:
$('#example').tooltip({
selector: "a[rel=tooltip]"
})
This selector will target all of your tooltips with the rel
attribute "within" your #example
div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.
Below code works fine before 18 API :-
public String getRealPathFromURI(Uri contentUri) {
// can post image
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
below code use on kitkat :-
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
see below link for more info:-
If you want to do something like the following example, you'd have to use nested if
s.
If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.
Here's how you'd do it:
=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))
There might be a margin style that your table is inheriting. Try setting the margin of the table to 0:
<table border="1" width="100%" ID="Table2" style="margin: 0px;">
<tr>
<td>100</td>
</tr>
</table>
In addition to the simple print answer, you can actually customise the print output through the use of the numpy.set_printoptions function.
Prerequisites:
>>> import numpy as np
>>> inf = np.float('inf')
>>> A = np.array([[0,1,4,inf,3],[1,0,2,inf,4],[4,2,0,1,5],[inf,inf,1,0,3],[3,4,5,3,0]])
The following option:
>>> np.set_printoptions(infstr="(infinity)")
Results in:
>>> print(A)
[[ 0. 1. 4. (infinity) 3.]
[ 1. 0. 2. (infinity) 4.]
[ 4. 2. 0. 1. 5.]
[(infinity) (infinity) 1. 0. 3.]
[ 3. 4. 5. 3. 0.]]
The following option:
>>> np.set_printoptions(formatter={'float': "\t{: 0.0f}\t".format})
Results in:
>>> print(A)
[[ 0 1 4 inf 3 ]
[ 1 0 2 inf 4 ]
[ 4 2 0 1 5 ]
[ inf inf 1 0 3 ]
[ 3 4 5 3 0 ]]
If you just want to have a specific string output for a specific array, the function numpy.array2string is also available.
Polymorphism
1. Static binding/Compile-Time binding/Early binding/Method overloading.(in same class)
2. Dynamic binding/Run-Time binding/Late binding/Method overriding.(in different classes)
class Calculation {
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]) {
Calculation obj=new Calculation();
obj.sum(10,10,10); // 30
obj.sum(20,20); //40
}
}
class Animal {
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();//output: Animals can move
b.move();//output:Dogs can walk and run
}
}
It might work.
.hide-text {
opacity:0;
pointer-events:none;
overflow:hidden;
}
None of the answers above are complete. Although Leo Theobald answer looks nearest answer.
The basic point is how hibernate is dealing with states of entities and how it handles them when there is a state change. Everything must be seen with respect to flushes and commits as well, which everyone seems to have ignored completely.
NEVER USE THE SAVE METHOD of HIBERNATE. FORGET THAT IT EVEN EXISTS IN HIBERNATE!
Persist
As everyone explained, Persist basically transitions an entity from "Transient" state to "Managed" State. At this point, a slush or a commit can create an insert statement. But the entity will still remains in "Managed" state. That doesn't change with flush.
At this point, if you "Persist" again there will be no change. And there wont be any more saves if we try to persist a persisted entity.
The fun begins when we try to evict the entity.
An evict is a special function of Hibernate which will transition the entity from "Managed" to "Detached". We cannot call a persist on a detached entity. If we do that, then Hibernate raises an exception and entire transaction gets rolled back on commit.
Merge vs Update
These are 2 interesting functions doing different stuff when dealt in different ways. Both of them are trying to transition the entity from "Detached" state to "Managed" state. But doing it differently.
Understand a fact that Detached means kind of an "offline" state. and managed means "Online" state.
Observe the code below:
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
ses1.merge(entity);
ses1.delete(entity);
tx1.commit();
When you do this? What do you think will happen? If you said this will raise exception, then you are correct. This will raise exception because, merge has worked on entity object, which is detached state. But it doesn't alter the state of object.
Behind the scene, merge will raise a select query and basically returns a copy of entity which is in attached state. Observe the code below:
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
HibEntity copied = (HibEntity)ses1.merge(entity);
ses1.delete(copied);
tx1.commit();
The above sample works because merge has brought a new entity into the context which is in persisted state.
When applied with Update the same works fine because update doesn't actually bring a copy of entity like merge.
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
ses1.update(entity);
ses1.delete(entity);
tx1.commit();
At the same time in debug trace we can see that Update hasn't raised SQL query of select like merge.
delete
In the above example I used delete without talking about delete. Delete will basically transition the entity from managed state to "removed" state. And when flushed or commited will issue a delete command to store.
However it is possible to bring the entity back to "managed" state from "removed" state using the persist method.
Hope the above explanation clarified any doubts.
git log --pretty=format:"%h%x09%an%x09%ad%x09%s"
did the job. This outputs:
fbc3503 mads Thu Dec 4 07:43:27 2008 +0000 show mobile if phone is null...
ec36490 jesper Wed Nov 26 05:41:37 2008 +0000 Cleanup after [942]: Using timezon
ae62afd tobias Tue Nov 25 21:42:55 2008 +0000 Fixed #67 by adding time zone supp
164be7e mads Tue Nov 25 19:56:43 2008 +0000 fixed tests, and a 'unending appoi
93f1526 jesper Tue Nov 25 09:45:56 2008 +0000 adding time.ZONE.now as time zone
2f0f8c1 tobias Tue Nov 25 03:07:02 2008 +0000 Timezone configured in environment
a33c1dc jesper Tue Nov 25 01:26:18 2008 +0000 updated to most recent will_pagina
Inspired by stackoverflow question: "git log output like svn ls -v", i found out that I could add the exact params I needed.
To shorten the date (not showing the time) use --date=short
In case you were curious what the different options were:
%h
= abbreviated commit hash
%x09
= tab (character for code 9)
%an
= author name
%ad
= author date (format respects --date= option)
%s
= subject
From kernel.org/pub/software/scm/git/docs/git-log.html (PRETTY FORMATS section) by comment of Vivek.
sed will need to read the data too to count the lines. The only way a shortcut would be possible would there to be context/order in the file to operate on. For example if there were log lines prepended with a fixed width time/date etc. you could use the look unix utility to binary search through the files for particular dates/times
I would suggest the use of exists
instead of in
because in some scenarios that implies null values the behavior is different, so
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
DELETE FROM database2.dbo.table2 childTable
WHERE bar = 4 AND exists (SELECT id FROM deleted where deleted.id = childTable.id)
GO
Regarding int main():
According to the Standard, argv
points to a NULL-terminated array (of pointers to null-terminated strings). (5.1.2.2.1:1).
That is, argv = (char **){ argv[0], ..., argv[argc - 1], 0 };
.
Hence, size calculation is performed by a function which is a trivial modification of strlen()
.
argc
is only there to make argv
length calculation O(1).
The count-until-NULL method will NOT work for generic array input. You will need to manually specify size as a second argument.
There is another type-safe alternative to specifying a base-package location as a String. See the API here, but I've also illustrated below:
@ComponentScan(basePackageClasses = {ExampleController.class, ExampleModel.class, ExmapleView.class})
Using the basePackageClasses specifier with your class references will tell Spring to scan those packages (just like the mentioned alternatives), but this method is both type-safe and adds IDE support for future refactoring -- a huge plus in my book.
Reading from the API, Spring suggests creating a no-op marker class or interface in each package you wish to scan that serves no other purpose than to be used as a reference for/by this attribute.
IMO, I don't like the marker-classes (but then again, they are pretty much just like the package-info classes) but the type safety, IDE support, and drastically reducing the number of base packages needed to include for this scan is, with out a doubt, a far better option.
According to this: http://www.vistax64.com/vista-installation-setup/33219-regsvr32-error-0x80004005.html
Run it in a elevated command prompt.
Simply try this
It's another way
public enum CaseOriginCode
{
Web = 0,
Email = 1,
Telefoon = 2
}
public void setCaseOriginCode(string CaseOriginCode)
{
int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}
for a series: used describe functions
suppose you have df with following columns sales and id. you want to calculate percentiles for sales then it works like this,
df['sales'].describe(percentiles = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])
0.0: .0: minimum
1: maximum
0.1 : 10th percentile and so on
I resolved the same issue with a recursive chown on the parent folder:
sudo chown -R postgres:postgres /home/my_user/export_folder
(my export being in /home/my_user/export_folder/export_1.csv
)
Gradle
is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins!
Advantages:
Manifest entries
Through the DSL it is possible to configure the following manifest entries:
Build variant
By default, the Android plugin automatically sets up the project to build both a debug and a release version of the application.
Dependencies
If you have binary archives in your local filesystem that a module depends on, such as JAR files, you can declare these dependencies in the build file for that module.
First the repository must be added to the list, and then the dependency must be declared in a way that Maven or Ivy declare their artifacts.
Update:
For mongodb versions 2.2+ more efficient way to do this described by @JohnnyHK in another answer.
1.Using $where
db.accommodations.find( { $where: "this.name.length > 1" } );
But...
Javascript executes more slowly than the native operators listed on this page, but is very flexible. See the server-side processing page for more information.
2.Create extra field NamesArrayLength
, update it with names array length and then use in queries:
db.accommodations.find({"NamesArrayLength": {$gt: 1} });
It will be better solution, and will work much faster (you can create index on it).
It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.
print('Hello world!')
This will do it for you:
var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )
If you want to load the view from the same controller you are on:
if ($validator->fails()) {
return self::index($request)->withErrors($validator->errors());
}
And if you want to quickly display all errors but have a bit more control:
@if ($errors->any())
@foreach ($errors->all() as $error)
<div>{{$error}}</div>
@endforeach
@endif
Well best option is %java_home%\bin\xjc -p [your namespace] [xsd_file].xsd
.
I also have a question if we have an option to do reverse engineering here. if yes can we generate xsd from pojo class?
Just as Daniel said "Git and TFVC are the two source control options in TFS
". Fortunately both are supported for now in VS Code.
You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.
Add the following lines to your user settings
If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe", "tfvc.restrictWorkspace": true }
Or for VS 2017:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe", "tfvc.restrictWorkspace": true }
Open a local folder (repository), From View -> Command Pallette ..., type team signin
Provide user name --> Enter --> Provide password to connect to TFS.
Please refer to below links for more details:
Note that Server Workspaces are not supported:
"TFVC support is limited to Local workspaces":
You need to loop through and parse/convert the elements in your array, like this:
var result_string = 'a,b,c,d|1,2,3,4',
result = result_string.split("|"),
alpha = result[0],
count = result[1],
count_array = count.split(",");
for(var i=0; i<count_array.length;i++) count_array[i] = +count_array[i];
//now count_array contains numbers
You can test it out here. If the +
, is throwing, think of it as:
for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);
Go to Path C:\ProgramData\Oracle\Java\javapath (This path is in my case might be different in your case). Rename the folder ORACLE with other name line ORACLE_OLD. And Restart the STS/IDE . This works for me
If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:
tagcloud: {
map: function(doc){
for(tag in doc.tags){
emit(doc.tags[tag],1)
}
}
reduce: function(keys,values){
return values.length
}
}
Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to counting the occurrences of a word in text.
The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.
For code sleuths: fonts.xml
is the definitive and ever-expanding list of Android fonts.
Set the android:fontFamily
and android:textStyle
attributes, e.g.
<!-- Roboto Bold -->
<TextView
android:fontFamily="sans-serif"
android:textStyle="bold" />
to the desired values from this table:
Font | android:fontFamily | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin | sans-serif-thin |
Roboto Light | sans-serif-light |
Roboto Regular | sans-serif |
Roboto Bold | sans-serif | bold
Roboto Medium | sans-serif-medium |
Roboto Black | sans-serif-black |
Roboto Condensed Light | sans-serif-condensed-light |
Roboto Condensed Regular | sans-serif-condensed |
Roboto Condensed Medium | sans-serif-condensed-medium |
Roboto Condensed Bold | sans-serif-condensed | bold
Noto Serif | serif |
Noto Serif Bold | serif | bold
Droid Sans Mono | monospace |
Cutive Mono | serif-monospace |
Coming Soon | casual |
Dancing Script | cursive |
Dancing Script Bold | cursive | bold
Carrois Gothic SC | sans-serif-smallcaps |
(Noto Sans is a fallback font; you can't specify it directly)
Note: this table is derived from fonts.xml
. Each font's family name and style is listed in fonts.xml, e.g.
<family name="serif-monospace">
<font weight="400" style="normal">CutiveMono.ttf</font>
</family>
serif-monospace
is thus the font family, and normal
is the style.
Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:
Your layout name is in snake_case.
activity_login.xml
Then your binding class name will be in CamelCase.
ActivityLoginBinding.java
Also build project after creating layout. Sometimes it is not generated automatically.
If using RamdaJS is an option, this can be achieved in one line: R.transpose(myArray)
"Googling it" is okay!
Yes, I know it offends some people out there that their years of intense memorization and/or glorious stacks of programming books are starting to fall by the wayside to a resource that anyone can access within seconds, but you shouldn't hold that against people that use it.
Too often I hear googling answers to problems the result of criticism, and it really is without sense. First of all, it must be conceded that everyone needs materials to reference. You don't know everything and you will need to look things up. Conceding that, does it really matter where you got the information? Does it matter if you looked it up in a book, looked it up on Google, or heard it from a talking frog that you hallucinated? No. A right answer is a right answer.
What is important is that you understand the material, use it as the means to an end of a successful programming solution, and the client/your employer is happy with the results.
(although if you are getting answers from hallucinatory talking frogs, you should probably get some help all the same)
You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open
or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
Here's a good example. I use it to rename the variable because the JSON is coming from a .Net
environment where properties start with an upper-case letter.
public class Parameter {
@JsonProperty("Name")
public String name;
@JsonProperty("Value")
public String value;
}
This correctly parses to/from the JSON:
"Parameter":{
"Name":"Parameter-Name",
"Value":"Parameter-Value"
}
This chunk should do the work:
plot(var2 ~ var1, data=subset(dataframe, var3 < 150))
My best regards.
How this works:
If you list the bakground-none
class after the other classes, its properties will override those already set. There is no need to use !important
here.
For example:
.red { background-color: red; }
.background-none { background: none; }
and
<a class="red background-none" href="#carousel">...</a>
The link will not have a red background. Please note that this only overrides properties that have a selector that is less or equally specific.
Alternatively via Project Settings:
Depending on how your build is set up, this may be the way to go.
I did it like this in my Jtable its autorefreshing after 300 ms;
DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
JTable table = new JTable();
Timer t = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addColumns();
remakeData(set);
table.setModel(model);
}
});
t.start();
private void addColumns() {
model.setColumnCount(0);
model.addColumn("NAME");
model.addColumn("EMAIL");}
private void remakeData(CollectionType< Objects > name) {
model.setRowCount(0);
for (CollectionType Objects : name){
String n = Object.getName();
String e = Object.getEmail();
model.insertRow(model.getRowCount(),new Object[] { n,e });
}}
I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange
i think the only reason for this message is because target Array is actually an array like string etc (JSON -> {"host": "127.0.0.1"}) variable
I agree with the previous answer. Your compile SDK version must match the support library. Here is what I did.
Then it should build without problem.
GRANT
s on different objects are separate. GRANT
ing on a database doesn't GRANT
rights to the schema within. Similiarly, GRANT
ing on a schema doesn't grant rights on the tables within.
If you have rights to SELECT
from a table, but not the right to see it in the schema that contains it then you can't access the table.
The rights tests are done in order:
Do you have `USAGE` on the schema?
No: Reject access.
Yes: Do you also have the appropriate rights on the table?
No: Reject access.
Yes: Check column privileges.
Your confusion may arise from the fact that the public
schema has a default GRANT
of all rights to the role public
, which every user/group is a member of. So everyone already has usage on that schema.
The phrase:
(assuming that the objects' own privilege requirements are also met)
Is saying that you must have USAGE
on a schema to use objects within it, but having USAGE
on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.
It's like a directory tree. If you create a directory somedir
with file somefile
within it then set it so that only your own user can access the directory or the file (mode rwx------
on the dir, mode rw-------
on the file) then nobody else can list the directory to see that the file exists.
If you were to grant world-read rights on the file (mode rw-r--r--
) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.
If you instead set rwx-r-xr-x
on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.
You need to set both permissions for people to actually be able to view the file.
Same thing in Pg. You need both schema USAGE
rights and object rights to perform an action on an object, like SELECT
from a table.
(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT
ing from pg_class
directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
I think the simplest/handy way to consuming JSON is using a Java class that resembles your JSON: https://stackoverflow.com/a/6019761
But if you can't use a Java class you can use one of these two solutions.
Solution 1: you can do it receiving a Map<String, Object>
from your controller:
@RequestMapping(
value = "/process",
method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object> payload)
throws Exception {
System.out.println(payload);
}
Using your request:
curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process
Solution 2: otherwise you can get the POST payload as a String
:
@RequestMapping(
value = "/process",
method = RequestMethod.POST,
consumes = "text/plain")
public void process(@RequestBody String payload) throws Exception {
System.out.println(payload);
}
Then parse the string as you want. Note that must be specified consumes = "text/plain"
on your controller.
In this case you must change your request with Content-type: text/plain
:
curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST \
-d '{"name":"value"}' http://localhost:8080/myservice/process
When you do : f.readlines()
you already read all the file so f.tell()
will show you that you are in the end of the file, and doing f.next()
will result in a StopIteration
error.
Alternative of what you want to do is:
filne = "D:/testtube/testdkanimfilternode.txt"
with open(filne, 'r+') as f:
for line in f:
if line.startswith("anim "):
print f.next()
# Or use next(f, '') to return <empty string> instead of raising a
# StopIteration if the last line is also a match.
break
The reason of this problem when input field value is undefined then throw the warning from react. If you create one changeHandler for multiple input field and you want to change state with changeHandler then you need to assign previous value using by spread operator. As like my code here.
constructor(props){
super(props)
this.state = {
user:{
email:'',
password:''
}
}
}
// This handler work for every input field
changeHandler = event=>{
// Dynamically Update State when change input value
this.setState({
user:{
...this.state.user,
[event.target.name]:event.target.value
}
})
}
submitHandler = event=>{
event.preventDefault()
// Your Code Here...
}
render(){
return (
<div className="mt-5">
<form onSubmit={this.submitHandler}>
<input type="text" value={this.state.user.email} name="email" onChage={this.changeHandler} />
<input type="password" value={this.state.user.password} name="password" onChage={this.changeHandler} />
<button type="submit">Login</button>
</form>
</div>
)
}
Now we have the option of...
ParallelOptions parallelOptions = new ParallelOptions();
parallelOptions.MaxDegreeOfParallelism = 4;
#if DEBUG
parallelOptions.MaxDegreeOfParallelism = 1;
#endif
Parallel.ForEach(bookIdList, parallelOptions, bookID => UpdateStockCount(bookID));
Of course, this opens up a whole new can of threadworms.
ps (Sorry about the fonts, it's what the system decided)
If you're looking for something like MySQL's DUMP
, then good news: SQL Server 2008 Management Studio added that ability.
In SSMS, just right-click on the DB in question and select Tasks > Generate Scripts. Then in the 2nd page of the options wizard, make sure to select that you'd like the data scripted as well, and it will generate what amounts to a DUMP
file for you.
The replaceAll method is attempting to match the String literal []
which does not exist within the String
try replacing these items separately.
String str = "[Chrissman-@1]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");
For Visual Basic:
[Enum].GetNames(typeof(MyEnum)).Length
did not work with me, but
[Enum].GetNames(GetType(Animal_Type)).length
did.
Seems like in Java 8 some methods are added to Long to treat old good [signed] long as unsigned. Seems like a workaround, but may help sometimes.
There is no simple way to achieves this directly. But P99 has macros that allow you to create such type of function automatically:
P99_DECLARE_ENUM(color, red, green, blue);
in a header file, and
P99_DEFINE_ENUM(color);
in one compilation unit (.c file) should then do the trick, in that example the function then would be called color_getname
.
You can't do it. But you can use custom Alert and Confirm boxes.
You can read about some User Interface libraries here:
http://speckyboy.com/2010/05/17/15-javascript-web-ui-libraries-frameworks-and-libraries/
Most common libraries are:
Use the format()
function:
>>> format(14, '#010b')
'0b00001110'
The format()
function simply formats the input following the Format Specification mini language. The #
makes the format include the 0b
prefix, and the 010
size formats the output to fit in 10 characters width, with 0
padding; 2 characters for the 0b
prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format()
and put the second argument for the format()
function after the colon of the placeholder {:..}
:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format()
:
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...)
communicates the intent better.
If you did not want the 0b
prefix, simply drop the #
and adjust the length of the field:
>>> format(14, '08b')
'00001110'
You need to specify the classpath. This should do it:
java -cp . Echo "hello"
This tells java to use .
(the current directory) as its classpath, i.e. the place where it looks for classes. Note than when you use packages, the classpath has to contain the root directory, not the package subdirectories. e.g. if your class is my.package.Echo
and the .class file is bin/my/package/Echo.class
, the correct classpath directory is bin
.
At last! I got the answer to this, the size to edit it in photoshop is: 379x674
You are welcome
in my case just removing background-image
from nav-bar
item solved the problem
.navbar-default .navbar-nav > .active > a:focus {
.
.
.
background-image: none;
}
Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:
public ActionResult GetImages(string artistName, string apiKey)
MVC will auto-populate the parameters when given a URL like:
/Artist/GetImages/?artistName=cher&apiKey=XXX
One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:
public ActionResult GetImages(string id, string apiKey)
would be populated correctly with a URL like the following:
/Artist/GetImages/cher?apiKey=XXX
In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
If you wanted to support a url like
/Artist/GetImages/cher/api-key
you could add a route like:
routes.MapRoute(
"ArtistImages", // Route name
"{controller}/{action}/{artistName}/{apikey}", // URL with parameters
new { controller = "Home", action = "Index", artistName = "", apikey = "" } // Parameter defaults
);
and a method like the first example above.
Simple URL :
https://www.google.com/maps/dir/?api=1&destination=lat,lng
This url is specific for routing.
Reference : https://developers.google.com/maps/documentation/urls/guide#directions-action
Remember that when you restart the database by removing .lock files by force, the data might get corrupted. Your server shouldn't be considered "healthy" if you restarted the server that way.
To amend the situation, either run
mongod --repair
or
> db.repairDatabase();
in the mongo shell to bring your database back to "healthy" state.
def mode(data):
lst =[]
hgh=0
for i in range(len(data)):
lst.append(data.count(data[i]))
m= max(lst)
ml = [x for x in data if data.count(x)==m ] #to find most frequent values
mode = []
for x in ml: #to remove duplicates of mode
if x not in mode:
mode.append(x)
return mode
print mode([1,2,2,2,2,7,7,5,5,5,5])
Ubuntu
sudo apt-get install php5-dev pecl imagemagick libmagickwand-dev
sudo pecl install imagick
sudo apt-get install php5-imagick
sudo service apache2 restart
Some dependencies will probably already be met but excluding the Apache service, that's everything required for PHP to use the Imagick
class.
For anyone who is reaching here and is not able to solve their issue, I used to make my widget horizontally center by setting both right and left to 0 like below:
Stack(
children: <Widget>[
Positioned(
top: 100,
left: 0,
right: 0,
child: Text("Search",
style: TextStyle(
color: Color(0xff757575),
fontWeight: FontWeight.w700,
fontFamily: "Roboto",
fontStyle: FontStyle.normal,
fontSize: 56.0),
textAlign: TextAlign.center),
),
]
)
Call SYS_CONTEXT
to get the current schema. From Ask Tom "How to get current schema:
select sys_context( 'userenv', 'current_schema' ) from dual;
I use following line of code to fix this problem. Write the following code in web.config file
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
You should use profiles.
<profiles>
<profile>
<id>otherOutputDir</id>
<build>
<directory>yourDirectory</directory>
</build>
</profile>
</profiles>
And start maven with your profile
mvn compile -PotherOutputDir
If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :
<properties>
<buildDirectory>${project.basedir}/target</buildDirectory>
</properties>
<build>
<directory>${buildDirectory}</directory>
</build>
And compile like this :
mvn compile -DbuildDirectory=test
That's because you can't change the target directory by using -Dproject.build.directory
1) Go to "Window".
2) Then click on "Open Perspective",
3) Then click on "Other",
4) Select "Java(Default)" and click "OK"
Then again go to "Window" and click on "Reset Perspective"
Do search with LEFT OUTER JOIN
. I don't know if MySQL allows inline VALUES
in join clauses but you can have predefined table for this purposes.
Try paste in console this:
$ mkdir /var/pgsql_socket/
$ ln -s /private/tmp/.s.PGSQL.5432 /var/pgsql_socket/
R.id.button
is not part of R.layout.activity_main
. How should the activity find it in the content view?
The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.
In platforms like Java, int
s are primitives while Integer
is an object which holds a integer field. The important distinction is that primitives are always passed around by value and by definition are immutable.
Any operation involving a primitive variable always returns a new value. On the other hand, objects are passed around by reference. One could argue that the point to the object (AKA the reference) is also being passed around by value, but the contents are not.
All the above answer not working for me for AppCompatDialog
If you are using AppCompatDialog try this
Important note: Set this before calling setContentView.
dialog.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
e.g.
$('element[attr=val]')
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
import tensorflow as tf
print(tf.VERSION)
My steps:
In addition to making sure "Build Active Architectures" was set to YES as mentioned in previous answers, this was what had done it for me.
Replace this
<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">
with
<button value=" Send" class="btn btn-success" type="submit" id="submit">
Use the filter_var()
function to validate whether a string is URL or not:
var_dump(filter_var('example.com', FILTER_VALIDATE_URL));
It is bad practice to use regular expressions when not necessary.
EDIT: Be careful, this solution is not unicode-safe and not XSS-safe. If you need a complex validation, maybe it's better to look somewhere else.
…or a shorter try:
library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))
the picked table is the longest one on the page
tables[[which.max(n.rows)]]
You can use getEventListeners in your Google Chrome developer console.
getEventListeners(object) returns the event listeners registered on the specified object.
getEventListeners(document.querySelector('option[value=Closed]'));
My 'random' library provide a high convenient wrapper around C++11 random classes. You can do almost all things with a simple 'get' method.
Examples:
Random number in a range
auto val = Random::get(-10, 10); // Integer
auto val = Random::get(10.f, -10.f); // Float point
Random boolean
auto val = Random::get<bool>( ) // 50% to generate true
auto val = Random::get<bool>( 0.7 ) // 70% to generate true
Random value from a std::initilizer_list
auto val = Random::get( { 1, 3, 5, 7, 9 } ); // val = 1 or 3 or...
Random iterator from iterator range or all container
auto it = Random::get( vec.begin(), vec.end() ); // it = random iterator
auto it = Random::get( vec ); // return random iterator
And even more things ! Check out the github page:
You just need to get selenium package imported, that you can do from command prompt using the command
pip install selenium
When you have to use it in any IDE just import this package, no other documentation required to be imported
For Eg :
import selenium
print(selenium.__filepath__)
This is just a general command you may use in starting to check the filepath of selenium
By default, Apache prohibits using an .htaccess file to apply rewrite rules, so
Step 1 — Enabling mod_rewrite (if not Enabled) First, we need to activate mod_rewrite. It's available but not enabled with a clean Apache 2 installation.
$ sudo a2enmod rewrite
This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.
$ sudo systemctl restart apache2
mod_rewrite is now fully enabled. In the next step we will set up an .htaccess file that we'll use to define rewrite rules for redirects.
Step 2 — Setting Up .htaccess Open the default Apache configuration file using nano or your favorite text editor.
$ sudo nano /etc/apache2/sites-available/000-default.conf
Inside that file, you will find a block starting on the first line. Inside of that block, add the following new block so your configuration file looks like the following. Make sure that all blocks are properly indented.
/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
. . .
</VirtualHost>
Save and close the file. To put these changes into effect, restart Apache.
$ sudo systemctl restart apache2
Done. Your .htacess should work. This link may actually help somebody https://www.digitalocean.com/community/tutorials/how-to-rewrite-urls-with-mod_rewrite-for-apache-on-ubuntu-16-04
I found this to be the simplest way.
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>>
I tried the below and it worked like a charm :)
rec_list = ['[email protected]', '[email protected]']
rec = ', '.join(rec_list)
msg['To'] = rec
send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())
A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal()
on the semaphore when a file is downloaded. The consumer calls wait()
on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.
A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait()
can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.
A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.
A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized
keyword. The synchronized
keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.
I would use
WHERE columnName LIKE '%[%]%'
SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE
clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.
The response to this Connect Item states
We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.
An example
CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)
CREATE NONCLUSTERED INDEX IX ON T(X)
INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT TOP (100000) 'blah'
FROM master..spt_values v1, master..spt_values v2
SET STATISTICS IO ON;
SELECT *
FROM T
WHERE X LIKE '%[%]%'
SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'
Shows 457 logical reads for the first query and 33,335 for the second.
Here's my own implementation. Keys in the input array will be renumbered with incrementing keys starting from $start_index.
function array_reindex($array, $start_index)
{
$array = array_values($array);
$zeros_array = array_fill(0, $start_index, null);
return array_slice(array_merge($zeros_array, $array), $start_index, null, true);
}
You could use a Scanner
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();
prints the following output:
1 2 red blue
To add the ; secure
suffix to the Set-Cookie
http header I simply used the <httpCookies>
element in the web.config:
<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>
IMHO much more handy than writing code as in the article of Anubhav Goyal.
See: http://msdn.microsoft.com/en-us/library/ms228262(v=vs.100).aspx
I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
CheckBox optSingleShot;
Button btnStart, btnCancel;
TextView textCounter;
Timer timer;
MyTimerTask myTimerTask;
int tobeShown = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
optSingleShot = (CheckBox)findViewById(R.id.singleshot);
btnStart = (Button)findViewById(R.id.start);
btnCancel = (Button)findViewById(R.id.cancel);
textCounter = (TextView)findViewById(R.id.counter);
tobeShown = 1;
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
btnStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
/*if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}*/
}});
btnCancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (timer!=null){
timer.cancel();
timer = null;
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
}
@Override
protected void onPause() {
super.onPause();
if (timer!=null){
timer.cancel();
timer = null;
}
}
@Override
protected void onStop() {
super.onStop();
if (timer!=null){
timer.cancel();
timer = null;
}
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
}
}
}
Go Playground http://play.golang.org/p/DN5Py5MxaB
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
// The Time type implements the Stringer interface -- it
// has a String() method which gets called automatically by
// functions like Printf().
fmt.Printf("%s\n", t)
// See the Constants section for more formats
// http://golang.org/pkg/time/#Time.Format
formatedTime := t.Format(time.RFC1123)
fmt.Println(formatedTime)
}
Using String.format, you can do this:
double price = 52000;
String.format("$%,.2f", price);
Notice the comma which makes this different from @Vincent's answer
Output:
$52,000.00
A good resource for formatting is the official java page on the subject
For Official information:
https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced
A simple Example:
On any Element you have to add an attribute ref
with a unique value
<input ref="foo" type="text" >
To target that elemet use this.$refs.foo
this.$refs.foo.focus(); // it will focus the input having ref="foo"
Decision tree between ES5, ES6 and TypeScript
Do you mind having a build step?
Do you want to use types?
ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers
ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.
TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).
Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.
It seems to me that simply: ls -lt mydirectory
does the job...
VSCode is a code editor, not a full IDE. Think of VSCode as a notepad on steroids with IntelliSense code completion, richer semantic code understanding of multiple languages, code refactoring, including navigation, keyboard support with customizable bindings, syntax highlighting, bracket matching, auto indentation, and snippets.
It's not meant to replace Visual Studio, but making "Visual Studio" part of the name in VSCode will of course confuse some people at first.
NodeJS supports http.request as a standard module: http://nodejs.org/docs/v0.4.11/api/http.html#http.request
var http = require('http');
var options = {
host: 'example.com',
port: 80,
path: '/foo.html'
};
http.get(options, function(resp){
resp.on('data', function(chunk){
//do something with chunk
});
}).on("error", function(e){
console.log("Got error: " + e.message);
});
How can I push my tag to the remote repository so that all client computers can see it?
Run this to push mytag
to your git origin (eg: GitHub or GitLab)
git push origin refs/tags/mytag
It's better to use the full "refspec" as shown above (literally refs/tags/mytag
) just in-case mytag
is actually v1.0.0
and is ambiguous (eg: because there's a branch also named v1.0.0
).
I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?
If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.
Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.
var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;
I appreciate this is an old post, but it may be useful for people to know that the Azure Migration Wizard (available on Codeplex - can't link to is as Codeplex is at the moment I'm typing this) will do this easily.
It seems you're actually talking about an MVC (Model-View-Controller) pattern, where logic is separated into various "tiers". Django, as a framework, follows MVC (loosely). You have models that contain your business logic and relate directly to tables in your database, views which in effect act like the controller, handling requests and returning responses, and finally, templates which handle presentation.
Django isn't just one of these, it is a complete framework for application development and provides all the tools you need for that purpose.
Frontend vs Backend is all semantics. You could potentially build a Django app that is entirely "backend", using its built-in admin contrib package to manage the data for an entirely separate application. Or, you could use it solely for "frontend", just using its views and templates but using something else entirely to manage the data. Most usually, it's used for both. The built-in admin (the "backend"), provides an easy way to manage your data and you build apps within Django to present that data in various ways. However, if you were so inclined, you could also create your own "backend" in Django. You're not forced to use the default admin.
In java you don't check if a key is pressed, instead you listen to KeyEvent
s.
The right way to achieve your goal is to register a KeyEventDispatcher
, and implement it to maintain the state of the desired key:
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class IsKeyPressed {
private static volatile boolean wPressed = false;
public static boolean isWPressed() {
synchronized (IsKeyPressed.class) {
return wPressed;
}
}
public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
}
break;
}
return false;
}
}
});
}
}
Then you can always use:
if (IsKeyPressed.isWPressed()) {
// do your thing.
}
You can, of course, use same method to implement isPressing("<some key>")
with a map of keys and their state wrapped inside IsKeyPressed
.
In React Native , This worked for me
name = "hi \n\ruser"
name.replace( /[\r\n]+/gm, ""); // hi user
I'm guessing you have two python installs, or two pip installs, one of which has been partially removed.
Why do you use sudo
? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissions issues (e.g. see the warning it gives about "parent directory is not owned by the current user").
What do you get if you run this?
$ head -n1 /usr/local/bin/pip
This will show you which python binary pip
is trying to use. If it's pointing /usr/local/opt/python/bin/python2.7
, then try running this:
$ ls -al /usr/local/opt/python/bin/python2.7
If this says "No such file or directory", then pip is trying to use a python binary that has been removed.
Next, try this:
$ which python
$ which python2.7
To see the path of the python binary that's actually working.
Since it looks like pip was successfully installed somewhere, it could be that /usr/local/bin/pip
is part of an older installation of pip that's higher up on the PATH
. To test that, you may try moving the non-functioning pip
binary out of the way like this (might require sudo
):
$ mv /usr/local/bin/pip /usr/local/bin/pip.old
Then try running your pip --version
command again. Hopefully it picks up the correct version and runs successfully.
Not the best, but whether it is practical method:
Use HijackThis.
Run hijack this, click the "Open the Misc Tools section" button
click "Open Uninstall Manager"
click save list (*.txt), yes to the prompts, notepad will open with your add/remove programs list.
var a = [1,2,3,4,5], b=a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];
So the 50x50 size is a good choice.
Update: in Rails 3.0.9: env method defined in railties/lib/rails.rb
You can remove some extra spacing as well if you place a border-collapse: collapse;
CSS statement on your table.
It's better to use throw
instead of throw ex
.
throw ex reset the original stack trace and can't be found the previous stack trace.
If we use throw, we will get a full stack trace.
I know this is a bit late, but if this helps anybody, I think you could add a column to your data that calculates if the probability is ">='PivotSheet'$D$2"
(reference a cell on the pivot table
sheet).
Then, add that column to your pivot table and use the new column as a true/false
filter.
You can then change the value stored in the referenced cell to update your probability threshold.
If I understood your question right, this may get you what you wanted. The filter value would be displayed on the sheet with the pivot and can be changed to suit any quick changes to your probability threshold. The T/F Filter can be labeled "Above/At Probability Threshold" or something like that.
I've used this to do something similar. It was handy to have the cell reference on the Pivot table sheet so I could update the value and refresh the pivot to quickly modify the results. The people I did that for couldn't make up their minds on what that threshold should be.
The first thing that we need to do is install NVM.
To upgrade, run the new installer. It will safely overwrite the files it needs to update without touching your node.js installations. Make sure you use the same installation and symlink folder. If you originally installed to the default locations, you just need to click “next” on each window until it finishes.
Credits Directly copied from : https://digitaldrummerj.me/windows-running-multiple-versions-of-node/
you can try below code
public class UploadImage
{
public string ImageFile { get; set; }
public string ImageName { get; set; }
public string ImageDescription { get; set; }
}
<form class="form-horizontal" asp-controller="Image" asp-action="UploadImage" method="POST" enctype="multipart/form-data">
<input type="file" asp-for="ImageFile">
<input type="text" asp-for="ImageName">
<input type="text" asp-for="ImageDescription">
</form>
public class Image
{
private IHostingEnvironment _hostingEnv;
public Image(IHostingEnvironment hostingEnv)
{
_hostingEnv = hostingEnv;
}
[HttpPost]
public async Task<IActionResult> UploadImage(UploadImage model, IFormFile ImageFile)
{
if (ModelState.IsValid)
{
var filename = ContentDispositionHeaderValue.Parse(ImageFile.ContentDisposition).FileName.Trim('"');
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", ImageFile.FileName);
using (System.IO.Stream stream = new FileStream(path, FileMode.Create))
{
await ImageFile.CopyToAsync(stream);
}
model.ImageFile = filename;
_context.Add(model);
_context.SaveChanges();
}
return RedirectToAction("Index","Home");
}
Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so
import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')
to yield,
0 58
1 3
2 8
dtype: float64
DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin
select * from users
where id=UserId ;
END $$
DELIMITER ;
No, Depends on the situation, sometimes it is legitimate and good design.
To understand why and when you need to call destructors explicitly, let's look at what happening with "new" and "delete".
To created an object dynamically, T* t = new T;
under the hood: 1. sizeof(T) memory is allocated. 2. T's constructor is called to initialize the allocated memory. The operator new does two things: allocation and initialization.
To destroy the object delete t;
under the hood: 1. T's destructor is called. 2. memory allocated for that object is released. the operator delete also does two things: destruction and deallocation.
One writes the constructor to do initialization, and destructor to do destruction. When you explicitly call the destructor, only the destruction is done, but not the deallocation.
A legitimate use of explicitly calling destructor, therefore, could be, "I only want to destruct the object, but I don't (or can't) release the memory allocation (yet)."
A common example of this, is pre-allocating memory for a pool of certain objects which otherwise have to be allocated dynamically.
When creating a new object, you get the chunk of memory from the pre-allocated pool and do a "placement new". After done with the object, you may want to explicitly call the destructor to finish the cleanup work, if any. But you won't actually deallocate the memory, as the operator delete would have done. Instead, you return the chunk to the pool for reuse.
Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:
Prevent Back button from showing POST confirmation alert
Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.
Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.
td {
padding: npx; /* For cellpadding */
margin: npx; /* For cellspacing */
border-collapse: collapse; /* For showing borders in a better shape. */
}
If margin
didn't work, try to set display
of tr
to block
and then margin will work.
In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.
In the second example, the address is set when you say ptr = &q, so you're OK.
There is no functional or performance difference between the two. Use whichever syntax appeals to you.
It's just like the use of AS and IS when declaring a function or procedure. They are completely interchangeable.
In your invoke web request just use the parameter -UseBasicParsing
e.g. in your script (line 2) you should use:
$rss = Invoke-WebRequest -UseBasicParsing
According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.
Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.
To clone on windows while setting SSL verify to false:
git -c http.sslVerify=false clone http://example.com/e.git
If you want to clone without borfing your global settings.
Apparently you can find it in the header of the portable executable. The corflags.exe utility is able to show you whether or not it targets x64. Hopefully this helps you find more information about it.
window.open
doesn't work across all browsers, Google it and you will find a way of detecting the correct dialog type.
Also, move the onclick call to the input button for it to only fire when the user submits.
Use ng-disabled or a special CSS class with ng-class
<input data-ng-model="userInf.username"
class="span12 editEmail"
type="text"
placeholder="[email protected]"
pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}"
required
ng-disabled="{expression or condition}"
/>
This will compare full string XMLs (reformatting them on the way). It makes it easy to work with your IDE (IntelliJ, Eclipse), cos you just click and visually see the difference in the XML files.
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.w3c.dom.Element;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.StringReader;
import static org.apache.xml.security.Init.init;
import static org.junit.Assert.assertEquals;
public class XmlUtils {
static {
init();
}
public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {
Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());
return new String(canonXmlBytes);
}
public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {
InputSource src = new InputSource(new StringReader(input));
Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
Boolean keepDeclaration = input.startsWith("<?xml");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
return writer.writeToString(document);
}
public static void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
String canonicalExpected = prettyFormat(toCanonicalXml(expected));
String canonicalActual = prettyFormat(toCanonicalXml(actual));
assertEquals(canonicalExpected, canonicalActual);
}
}
I prefer this to XmlUnit because the client code (test code) is cleaner.
C++17 (N4659
) includes a proposal Refining Expression Evaluation Order for Idiomatic C++
which defines a stricter order of expression evaluation.
In particular, the following sentence
8.18 Assignment and compound assignment operators:
....In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.
together with the following clarification
An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.
make several cases of previously undefined behavior valid, including the one in question:
a[++i] = i;
However several other similar cases still lead to undefined behavior.
In N4140
:
i = i++ + 1; // the behavior is undefined
But in N4659
i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined
Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.
output.path
Local disk directory to store all your output files (Absolute path).
Example: path.join(__dirname, "build/")
Webpack will output everything into localdisk/path-to-your-project/build/
output.publicPath
Where you uploaded your bundled files. (absolute path, or relative to main HTML file)
Example: /assets/
Assumed you deployed the app at server root http://server/
.
By using /assets/
, the app will find webpack assets at: http://server/assets/
. Under the hood, every urls that webpack encounters will be re-written to begin with "/assets/
".
src="picture.jpg"
Re-writes ?src="/assets/picture.jpg"
Accessed by: (
http://server/assets/picture.jpg
)
src="/img/picture.jpg"
Re-writes ?src="/assets/img/picture.jpg"
Accessed by: (
http://server/assets/img/picture.jpg
)
To convert an integer to a string also involves char
array or memory management.
To handle that part for such short arrays, code could use a compound literal, since C99, to create array space, on the fly. The string is valid until the end of the block.
#define UNS_HEX_STR_SIZE ((sizeof (unsigned)*CHAR_BIT + 3)/4 + 1)
// compound literal v--------------------------v
#define U2HS(x) unsigned_to_hex_string((x), (char[UNS_HEX_STR_SIZE]) {0}, UNS_HEX_STR_SIZE)
char *unsigned_to_hex_string(unsigned x, char *dest, size_t size) {
snprintf(dest, size, "%X", x);
return dest;
}
int main(void) {
// 3 array are formed v v v
printf("%s %s %s\n", U2HS(UINT_MAX), U2HS(0), U2HS(0x12345678));
char *hs = U2HS(rand());
puts(hs);
// `hs` is valid until the end of the block
}
Output
FFFFFFFF 0 12345678
5851F42D
The value returned by Date.prototype.toLocaleString is implementation dependent, so you get what you get. You can try to parse the string to remove seconds, but it may be different in different browsers so you'd need to make allowance for every browser in use.
Creating your own, unambiguous format isn't difficult using Date methods. For example:
function formatTimeHHMMA(d) {
function z(n){return (n<10?'0':'')+n}
var h = d.getHours();
return (h%12 || 12) + ':' + z(d.getMinutes()) + ' ' + (h<12? 'AM' :'PM');
}
Another thing - if you're using python3, make sure you are starting your server with python3 server.py
, not python server.py
The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html
In Bootstrap 3, .form-control
(the class you give your inputs) has a width of 100%, which allows you to wrap them into col-lg-X divs for arrangement. Example from the docs:
<div class="row">
<div class="col-lg-2">
<input type="text" class="form-control" placeholder=".col-lg-2">
</div>
<div class="col-lg-3">
<input type="text" class="form-control" placeholder=".col-lg-3">
</div>
<div class="col-lg-4">
<input type="text" class="form-control" placeholder=".col-lg-4">
</div>
</div>
See under Column sizing.
It's a bit different than in Bootstrap 2.3.2, but you get used to it quickly.
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
Restarting Visual Studio did the trick for me. I am using VS 2015.
docker container list -f "status=exited"
or
docker container ls -f "status=exited"
or
docker ps -f "status=exited"
Absence of Submit field element in the form also causes this error. In the case of "button" field handled by JS to submit form lacks the necessity of Submit button hence Required doesn't Work
VLC should be able to do this.
To get an array of values from multiple checked checkboxes, use jQuery map/get functions:
$('input[type=checkbox]:checked').map(function(_, el) {
return $(el).val();
}).get();
This will return array with checked values, like this one: ['1', '2']
Here is working example on jsfiddle: http://jsfiddle.net/7PV2e/
import cv2
camera = cv2.VideoCapture(0)
while True:
return_value,image = camera.read()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow('image',gray)
if cv2.waitKey(1)& 0xFF == ord('s'):
cv2.imwrite('test.jpg',image)
break
camera.release()
cv2.destroyAllWindows()
The easiest way is this:
import jinja2
print jinja2.__version__
Almost every database table, there's an auto_increment column(generally id )
If you want the last of all the rows in the table,
SELECT columns FROM table ORDER BY id DESC LIMIT 1;
OR
You can combine two queries into single query that looks like this:
SELECT columns FROM table WHERE id=(SELECT MAX(id) FROM table);
Vertical align only works in some select cases. The easiest way to make it function is to set display: table
in the parent element's CSS and display: table-cell;
to the child element and then apply your vertical align attribute.
Use npm update
or,
Run `npm install --save-dev @angular-devkit/build-angular
`
Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this
HttpServletRequest request;
request.setAttribute("param", "value")
now your parametrs will not be shown in your url header hope it works :)
check the command : NA!=NA
: you'll get the result NA
, hence the error message.
You have to use the function is.na
for your if
statement to work (in general, it is always better to use this function to check for NA
values) :
comments = c("no","yes",NA)
for (l in 1:length(comments)) {
if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"
First you need to set equal width and height for getting Circular ImageView.Below I set width and height as 100,100.If you want to set equal width and height according to your required size,set here.
var imageCircle = UIImageView(frame: CGRectMake(0, 0, 100, 100))
Then you need to set height/2 for corner radius
imageCircle.layer.cornerRadius = imageCircle.frame.size.height/2
imageCircle.layer.borderWidth = 1
imageCircle.layer.borderColor = UIColor.blueColor().CGColor
imageCircle.clipsToBounds = true
self.view.addSubview(imageCircle)
Here comes the improved and recursive version of AgileJon's solution (demo):
function loopThrough(obj){
for(var key in obj){
// skip loop if the property is from prototype
if(!obj.hasOwnProperty(key)) continue;
if(typeof obj[key] !== 'object'){
//your code
console.log(key+" = "+obj[key]);
} else {
loopThrough(obj[key]);
}
}
}
loopThrough(validation_messages);
This solution works for all kinds of different depths.
Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.
Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.
Javascript:
$("#startTransition").on("click", function()
{
if( $(".boxOne").is(":visible"))
{
$(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
$(".boxTwo").css({ x: '100%' });
$(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
return;
}
$(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
$(".boxOne").css({ x: '100%' });
$(".boxOne").show().transition({ x: '0%', opacity: 1.0 });
});
Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.
In Python 2, raw_input()
returns a string, and input()
tries to run the input as a Python expression.
Since getting a string was almost always what you wanted, Python 3 does that with input()
. As Sven says, if you ever want the old behaviour, eval(input())
works.
The following line of JavaScript code will give you the file name.
var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);
If you have the developer console (JavaScript) in your browser, you can type this code in:
urls = document.querySelectorAll('a'); for (url in urls) console.log(urls[url].href);
Shortened:
n=$$('a');for(u in n)console.log(n[u].href)
Strings are mutable because .NET use string pool behind the scene. It means :
string name = "My Country";
string name2 = "My Country";
Both name and name2 are referring to same memory location from string pool. Now suppose you want to change name2 to :
name2 = "My Loving Country";
It will look in to string pool for the string "My Loving Country", if found you will get the reference of it other wise new string "My Loving Country" will be created in string pool and name2 will get reference of it. But it this whole process "My Country" was not changed because other variable like name is still using it. And that is the reason why string are IMMUTABLE.
StringBuilder works in different manner and don't use string pool. When we create any instance of StringBuilder :
var address = new StringBuilder(500);
It allocate memory chunk of size 500 bytes for this instance and all operation just modify this memory location and this memory not shared with any other object. And that is the reason why StringBuilder is MUTABLE.
I hope it will help.
This method is even easier if you're ok with fewer options:
FileCopy source, destination
Ok. So I think you just need to implement Pagination.
$perPage = 10;
$pageNo = $_GET['page'];
Now find total rows in database.
$totalRows = Get By applying sql query;
$pages = ceil($totalRows/$perPage);
$offset = ($pageNo - 1) * $perPage + 1
$sql = "SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT ".$offset." ,".$perPage
You can use new Property Animation Api for color animation:
int colorFrom = getResources().getColor(R.color.red);
int colorTo = getResources().getColor(R.color.blue);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(250); // milliseconds
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
textView.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
For backward compatibility with Android 2.x use Nine Old Androids library from Jake Wharton.
The getColor
method was deprecated in Android M, so you have two choices:
If you use the support library, you need to replace the getColor
calls with:
ContextCompat.getColor(this, R.color.red);
if you don't use the support library, you need to replace the getColor
calls with:
getColor(R.color.red);
There is no reason at all for an individual to update the copyright year, because in the U.S. and Europe the life of copyright is the life of the author plus 70 years (50 years in some other countries like Canada and Australia). Extending the date does not extend the copyright. This also applies when a page has multiple contributors none of which are corporations.
As for corporations, Google doesn't update their copyright dates because they don't care whether some page they started in 1999 and updated this year falls into the public domain in 2094 or 2109. And if they don't, why should you? (As a Googler, now an ex-Googler, I was told this was the policy for internal source code as well.)
First mark the directory as the source root. Then go to the pom excel and right click on it. select add as maven project .
It's answer for my self-answered question UIScrollView + Centered View + Ambigous Scrollable Content Size + many iPhone sizes.
But it fully cover your case too!
Has ambiguous scrollable content width
and Has ambiguous scrollable content height
.Important: you have to add trailing and/or bottom constraints. Not "leading and top" - it's not works!
You can check it in my example project, that demonstrating how to fix this issue.
P.S.
According logic - this action should cause "conflicting constraints". But no!
I don't know why it works and how Xcode detects which constraint is more prioritised (because I'm not set priority for these constraints explicity). I'll be thankful if someone explain, why it works in comments below.
I am also new to MVC and I received the same error and found that it is not passing proper routeValues
in the Index
view or whatever view is present to view the all data.
It was as below
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
I changed it to the as show below and started to work properly.
<td>
@Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
Basically this error can also come because of improper navigation also.
This is a more general answer meant to be a quick reference for future viewers.
Example
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Explanation from the documentation
table
String: The table name to compile the query against.columns
String: A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.selection
String: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.selectionArgs
String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.groupBy
String: A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.having
String: A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.orderBy
String: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.limit
String: Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
select convert(nvarchar(255), 4343)
Should do the trick.
In addition to above answers,
Just make sure you set estimatedItemSize property of UICollectionViewFlowLayout to some size and do not implement sizeForItem:atIndexPath delegate method.
That's it.
In this case , this code
{<td><span onClick={this.toggle()}>Details</span></td>}
causes toggle function to call immediately and re render it again and again thus making infinite calls.
so passing only the reference to that toggle method will solve the problem.
so ,
{<td><span onClick={this.toggle}>Details</span></td>}
will be the solution code.
If you want to use the () , you should use an arrow function like this
{<td><span onClick={()=> this.toggle()}>Details</span></td>}
In case you want to pass parameters you should choose the last option and you can pass parameters like this
{<td><span onClick={(arg)=>this.toggle(arg)}>Details</span></td>}
In the last case it doesn't call immediately and don't cause the re render of the function, hence avoiding infinite calls.
To add the the other answers, the POxx terms all appear to stem from POTS (Plain old telephone services).
The POX, used to define simple (plain old) XML, rather than the complex multi-layered stuff associated with REST, SOAP etc, was a useful, and vaguely amusing, term. PO(insert language of choice)O terms have rather worn the joke thin.
You can use the str.split
method: string.split('__')
>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']
You can get where you are through
new File(".").getAbsolutePath()
then you can derive path to src/test/resources
usually it is just
new File("src/test/resources")
If you can not see the "Prevent saving changes that required table re-creation" in list like that The image
You need to enable change tracking.
The short answer is adb is used via command line. find adb.exe on your machine, add it to the path and use it from cmd on windows.
"adb devices" will give you a list of devices adb can talk to. your emulation platform should be on the list. just type adb to get a list of commands and what they do.
Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.
http://www.w3schools.com/jsref/jsref_substr.asp
The substr
function will allow you to extract certain parts of the string.
Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well. http://www.w3schools.com/jsref/jsref_IndexOf.asp
The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?
Use the code
x = seq(0,100,5) #this means (starting number, ending number, interval)
the output will be
[1] 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
[17] 80 85 90 95 100
The first example nearly always wins in my book:
if(foo)
{
}
It's shorter and more concise. Why add an extra check to something when it's absolutely not needed? Just wasting cycles...
I do agree, though, that sometimes the more verbose syntax makes things more readable (which is ultimately more important as long as performance is acceptable) in situations where variables are poorly named.
I ran into this problem today. Based on the solutions above, this worked for me:
<div style="width:100%;">
<div style="float:left;">Content left div</div>
<div style="float:right;">Content right div</div>
</div>
Simply make the parent div span the full width and float the divs contained within.
Does this not work (assuming "ROUTERNAME" is the user name the router expects)?
net use Z: "\\10.0.1.1\DRIVENAME" /user:"ROUTERNAME" "PW"
Alternatively, you can use use a small VBScript:
Option Explicit
Dim u, p, s, l
Dim Network: Set Network= CreateObject("WScript.Network")
l = "Z:"
s = "\\10.0.1.1\DRIVENAME"
u = "ROUTERNAME"
p = "PW"
Network.MapNetworkDrive l, s, False, u, p
No. JavaScript is a client-side technology and cannot do anything on the server. You could however use AJAX to call a server-side script (e.g. PHP) which could return the information you need.
If you want to use AJAX, the easiest way will be to utilise jQuery:
$.post("someScript.php", function(data) {
console.log(data); //"data" contains whatever someScript.php returned
});
Maybe you find this simpler
select * from (
select ssn, sum(time) from downloads
group by ssn
order by sum(time) desc
) where rownum <= 10 --top 10 downloaders
Regards
K
Vim :help window
explains the confusion "tabs vs buffers" pretty well.
A buffer is the in-memory text of a file.
A window is a viewport on a buffer.
A tab page is a collection of windows.
Opening multiple files is achieved in vim with buffers. In other editors (e.g. notepad++) this is done with tabs, so the name tab in vim maybe misleading.
Windows are for the purpose of splitting the workspace and displaying multiple files (buffers) together on one screen. In other editors this could be achieved by opening multiple GUI windows and rearranging them on the desktop.
Finally in this analogy vim's tab pages would correspond to multiple desktops, that is different rearrangements of windows.
As vim help: tab-page
explains a tab page can be used, when one wants to temporarily edit a file, but does not want to change anything in the current layout of windows and buffers. In such a case another tab page can be used just for the purpose of editing that particular file.
Of course you have to remember that displaying the same file in many tab pages or windows would result in displaying the same working copy (buffer).
Use int
function with second parameter 16, to convert a hex string to an integer. Finally, use hex
function to convert it back to a hexadecimal number.
print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4
Instead you could directly do
print hex(int("0xAD4", 16) + 0x200) # 0xcd4
I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:
var MyApp = {}; // Globally scoped object
function foo(){
MyApp.color = 'green';
}
function bar(){
alert(MyApp.color); // Alerts 'green'
}
No one should yell at you for doing something like the above.
The return value (aka exit code) is a value in the range 0 to 255 inclusive. It's used to indicate success or failure, not to return information. Any value outside this range will be wrapped.
To return information, like your number, use
echo "$value"
To print additional information that you don't want captured, use
echo "my irrelevant info" >&2
Finally, to capture it, use what you did:
result=$(password_formula)
In other words:
echo "enter: "
read input
password_formula()
{
length=${#input}
last_two=${input:length-2:length}
first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
let sum=$first+$second
sum_len=${#sum}
echo $second >&2
echo $sum >&2
if [ $sum -gt 9 ]
then
sum=${sum:1}
fi
value=$second$sum$first
echo $value
}
result=$(password_formula)
echo "The value is $result"
You are specifying .fixedbutton
in your CSS (a class) and specifying the id
on the element itself.
Change your CSS to the following, which will select the id
fixedbutton
#fixedbutton {
position: fixed;
bottom: 0px;
right: 0px;
}
You could use a div
with a background image instead and this CSS3 property:
background-size: contain
You can check out an example on:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain
To quote Mozilla:
The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.
However, keep in mind that your image will be upscaled if the div
is larger than your original image.
If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:
git log --no-merges --pretty=format:"%s" 'old-tag^'...new-tag > /path/to/changelog.md
--no-merges
omits the merge commits from the listold-tag^
refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).you can type .exit
to quit node js REPL
@GET
does support List of Strings
Setup:
Java : 1.7
Jersey version : 1.9
Resource
@Path("/v1/test")
Subresource:
// receive List of Strings
@GET
@Path("/receiveListOfStrings")
public Response receiveListOfStrings(@QueryParam("list") final List<String> list){
log.info("receieved list of size="+list.size());
return Response.ok().build();
}
Jersey testcase
@Test
public void testReceiveListOfStrings() throws Exception {
WebResource webResource = resource();
ClientResponse responseMsg = webResource.path("/v1/test/receiveListOfStrings")
.queryParam("list", "one")
.queryParam("list", "two")
.queryParam("list", "three")
.get(ClientResponse.class);
Assert.assertEquals(200, responseMsg.getStatus());
}
# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
iptables -A FORWARD -p all -d $ip -j REJECT
done
Enter the original date into a Date
object and then print out the result with a DateFormat
. You may have to split up the string into smaller pieces to create the initial Date
object, if the automatic parse method does not accept your format.
Pseudocode:
Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);
Scope Identity
: Identity of last record added within the stored procedure being executed.
@@Identity
: Identity of last record added within the query batch, or as a result of the query e.g. a procedure that performs an insert, the then fires a trigger that then inserts a record will return the identity of the inserted record from the trigger.
IdentCurrent
: The last identity allocated for the table.
This will do:
/^(apple|banana)$/
to exclude from captured strings (e.g. $1
,$2
):
(?:apple|banana)
All the above solutions worked for me in API 21 or greater, but did not in API 19 (KitKat). Making a small change did the trick for me in the earlier versions. Notice Widget.Holo
instead of Widget.AppCompat
<style name="OverFlowStyle" parent="@android:style/Widget.Holo.ActionButton.Overflow">
<item name="android:src">@drawable/ic_overflow</item>
</style>
In my case, I had to delete all remotes (there were multiple for some unexplained reason), add the remote again, and commit with -f.
$ git remote
origin
upstream
$ git remote remove upstream
$ git remote remove origin
$ git remote add origin <my origin>
$ git push -u -f origin main
I don't know if the -u
flag contributed anything, but it doesn't hurt either.
I believe that @Matthew Crumley is right. They are functionally, if not structurally, equivalent. If you use Firebug to look at the objects that are created using new
, you can see that they are the same. However, my preference would be the following. I'm guessing that it just seems more like what I'm used to in C#/Java. That is, define the class, define the fields, constructor, and methods.
var A = function() {};
A.prototype = {
_instance_var: 0,
initialize: function(v) { this._instance_var = v; },
x: function() { alert(this._instance_var); }
};
EDIT Didn't mean to imply that the scope of the variable was private, I was just trying to illustrate how I define my classes in javascript. Variable name has been changed to reflect this.
$DISPLAY is the standard way. That's how users communicate with programs about which X server to use, if any.
This guide says:
6.1.5 Sending JDBC NULL as an IN parameter
The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.
A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.
So yes they're equivalent.
The \
(backslash) in the .match
call is not properly escaped. It would be easier to use a regex literal though. Either will work:
var regex = "^\\s+$";
var regex = /^\s+$/;
Also note that +
will require at least one space. You may want to use *
.
the best way to concat props/variables:
var sample = "test";
var result = `this is just a ${sample}`;
//this is just a test
You may find that you have to link with the math libraries on whatever system you're using, something like:
gcc -o myprog myprog.c -L/path/to/libs -lm
^^^ - this bit here.
Including headers lets a compiler know about function declarations but it does not necessarily automatically link to the code required to perform that function.
Failing that, you'll need to show us your code, your compile command and the platform you're running on (operating system, compiler, etc).
The following code compiles and links fine:
#include <math.h>
int main (void) {
int max = sqrt (9);
return 0;
}
Just be aware that some compilation systems depend on the order in which libraries are given on the command line. By that, I mean they may process the libraries in sequence and only use them to satisfy unresolved symbols at that point in the sequence.
So, for example, given the commands:
gcc -o plugh plugh.o -lxyzzy
gcc -o plugh -lxyzzy plugh.o
and plugh.o
requires something from the xyzzy
library, the second may not work as you expect. At the point where you list the library, there are no unresolved symbols to satisfy.
And when the unresolved symbols from plugh.o
do appear, it's too late.
As in this forum post by Gonzalo Medina, a third way may be:
\documentclass{article}
\usepackage{caption}
\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}
\begin{document}
Some text
\begin{equ}[!ht]
\begin{equation}
a=b+c
\end{equation}
\caption{Caption of the equation}
\end{equ}
Some other text
\end{document}
More details of the commands used from package caption
: here.
A screenshot of the output of the above code:
If you install a new Eclipse version it will work. Here's what I did:
Not really a "Linq to SQL"
equivalent for Java. but something close to it . Query DSL