<video width="400" controls="controls" preload="metadata">_x000D_
<source src="https://www.youtube.com/watch?v=Ulp1Kimblg0">_x000D_
</video>
_x000D_
Maybe you can think about removing the attribute to a function. I mean something like this:
var obj = {_x000D_
key1: "it ",_x000D_
key2: function() {_x000D_
return this.key1 + " works!";_x000D_
}_x000D_
};_x000D_
_x000D_
alert(obj.key2());
_x000D_
To read binary ASCII characters with great speed using only your head:
Letters start with leading bits 01. Bit 3 is on (1) for lower case, off (0) for capitals. Scan the following bits 4–8 for the first that is on, and select the starting letter from the same index in this string: “PHDBA” (think P.H.D., Bachelors in Arts). E.g. 1xxxx = P, 01xxx = H, etc. Then convert the remaining bits to an integer value (e.g. 010 = 2), and count that many letters up from your starting letter. E.g. 01001010 => H+2 = J.
SELECT DATABASEPROPERTYEX('DBName', 'Collation') SQLCollation;
Where DBName is your database name.
In version 5.2.7 I use this to send plain text:
$mail->set('Body', $Body);
I had faced the similar issue while using Convert.ToSingle(my_value) If the OS language settings is English 2.5 (example) will be taken as 2.5 If the OS language is German, 2.5 will be treated as 2,5 which is 25 I used the invariantculture IFormat provided and it works. It always treats '.' as '.' instead of ',' irrespective of the system language.
float var = Convert.ToSingle(my_value, System.Globalization.CultureInfo.InvariantCulture);
Beside other answers, I think the main reason to "why using Functional Interface other than directly with lambda expressions" can be related to nature of Java language which is Object Oriented.
The main attributes of Lambda expressions are: 1. They can be passed around 2. and they can executed in future in specific time (several times). Now to support this feature in languages, some other languages deal simply with this matter.
For instance in Java Script, a function (Anonymous function, or Function literals) can be addressed as a object. So, you can create them simply and also they can be assigned to a variable and so forth. For example:
var myFunction = function (...) {
...;
}
alert(myFunction(...));
or via ES6, you can use an arrow function.
const myFunction = ... => ...
Up to now, Java language designers have not accepted to handle mentioned features via these manner (functional programming techniques). They believe that Java language is Object Oriented and therefore they should solve this problem via Object Oriented techniques. They don't want to miss simplicity and consistency of Java language.
Therefore, they use interfaces, as when an object of an interface with just one method (I mean functional interface) is need you can replace it with a lambda expression. Such as:
ActionListener listener = event -> ...;
Who needs distributed, sharded forums? Maybe Facebook, but unless you're creating a Facebook-competitor, just use Mysql, Postgres or whatever you are most comfortable with. If you want to try MongoDB, ok, but don't expect it to do magic for you. It'll have its quirks and general nastiness, just as everything else, as I'm sure you've already discovered if you really have been working on it already.
Sure, MongoDB may be hyped and seem easy on the surface, but you'll run into problems which more mature products have already overcome. Don't be lured so easily, but rather wait until "nosql" matures, or dies.
Personally, I think "nosql" will wither and die from fragmentation, as there are no set standards (almost by definition). So I will not personally bet on it for any long-term projects.
Only thing that can save "nosql" in my book, is if it can integrate into Ruby or similar languages seamlessly, and make the language "persistent", almost without any overhead in coding and design. That may come to pass, but I'll wait until then, not now, AND it needs to be more mature of course.
Btw, why are you creating a forum from scratch? There are tons of open source forums which can be tweaked to fit most requirements, unless you really are creating The Next Generation of Forums (which I doubt).
innerHTML
is a string representing the contents of the element.
You want to modify the element itself. Drop the .innerHTML
part.
String string = String.format("%02d:%02d:%02d.%03d",
TimeUnit.MILLISECONDS.toHours(millisecend), TimeUnit.MILLISECONDS.toMinutes(millisecend) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisecend)),
TimeUnit.MILLISECONDS.toSeconds(millisecend) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisecend)), millisecend - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisecend)));
Format: 00:00:00.000
Example: 615605 Millisecend
00:10:15.605
Here is my solution by grabbing help from various sources. It takes full web page screen capture and it crops it (optional) and generates thumbnail from the cropped image also. Following are the requirements:
Requirements:
npm -g install phantomjs
import os
from subprocess import Popen, PIPE
from selenium import webdriver
abspath = lambda *p: os.path.abspath(os.path.join(*p))
ROOT = abspath(os.path.dirname(__file__))
def execute_command(command):
result = Popen(command, shell=True, stdout=PIPE).stdout.read()
if len(result) > 0 and not result.isspace():
raise Exception(result)
def do_screen_capturing(url, screen_path, width, height):
print "Capturing screen.."
driver = webdriver.PhantomJS()
# it save service log file in same directory
# if you want to have log file stored else where
# initialize the webdriver.PhantomJS() as
# driver = webdriver.PhantomJS(service_log_path='/var/log/phantomjs/ghostdriver.log')
driver.set_script_timeout(30)
if width and height:
driver.set_window_size(width, height)
driver.get(url)
driver.save_screenshot(screen_path)
def do_crop(params):
print "Croping captured image.."
command = [
'convert',
params['screen_path'],
'-crop', '%sx%s+0+0' % (params['width'], params['height']),
params['crop_path']
]
execute_command(' '.join(command))
def do_thumbnail(params):
print "Generating thumbnail from croped captured image.."
command = [
'convert',
params['crop_path'],
'-filter', 'Lanczos',
'-thumbnail', '%sx%s' % (params['width'], params['height']),
params['thumbnail_path']
]
execute_command(' '.join(command))
def get_screen_shot(**kwargs):
url = kwargs['url']
width = int(kwargs.get('width', 1024)) # screen width to capture
height = int(kwargs.get('height', 768)) # screen height to capture
filename = kwargs.get('filename', 'screen.png') # file name e.g. screen.png
path = kwargs.get('path', ROOT) # directory path to store screen
crop = kwargs.get('crop', False) # crop the captured screen
crop_width = int(kwargs.get('crop_width', width)) # the width of crop screen
crop_height = int(kwargs.get('crop_height', height)) # the height of crop screen
crop_replace = kwargs.get('crop_replace', False) # does crop image replace original screen capture?
thumbnail = kwargs.get('thumbnail', False) # generate thumbnail from screen, requires crop=True
thumbnail_width = int(kwargs.get('thumbnail_width', width)) # the width of thumbnail
thumbnail_height = int(kwargs.get('thumbnail_height', height)) # the height of thumbnail
thumbnail_replace = kwargs.get('thumbnail_replace', False) # does thumbnail image replace crop image?
screen_path = abspath(path, filename)
crop_path = thumbnail_path = screen_path
if thumbnail and not crop:
raise Exception, 'Thumnail generation requires crop image, set crop=True'
do_screen_capturing(url, screen_path, width, height)
if crop:
if not crop_replace:
crop_path = abspath(path, 'crop_'+filename)
params = {
'width': crop_width, 'height': crop_height,
'crop_path': crop_path, 'screen_path': screen_path}
do_crop(params)
if thumbnail:
if not thumbnail_replace:
thumbnail_path = abspath(path, 'thumbnail_'+filename)
params = {
'width': thumbnail_width, 'height': thumbnail_height,
'thumbnail_path': thumbnail_path, 'crop_path': crop_path}
do_thumbnail(params)
return screen_path, crop_path, thumbnail_path
if __name__ == '__main__':
'''
Requirements:
Install NodeJS
Using Node's package manager install phantomjs: npm -g install phantomjs
install selenium (in your virtualenv, if you are using that)
install imageMagick
add phantomjs to system path (on windows)
'''
url = 'http://stackoverflow.com/questions/1197172/how-can-i-take-a-screenshot-image-of-a-website-using-python'
screen_path, crop_path, thumbnail_path = get_screen_shot(
url=url, filename='sof.png',
crop=True, crop_replace=False,
thumbnail=True, thumbnail_replace=False,
thumbnail_width=200, thumbnail_height=150,
)
These are the generated images:
Whenever you have heavyweight initialization that should be done once for many
RDD
elements rather than once perRDD
element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), usemapPartitions()
instead ofmap()
.mapPartitions()
provides for the initialization to be done once per worker task/thread/partition instead of once perRDD
data element for example : see below.
val newRd = myRdd.mapPartitions(partition => {
val connection = new DbConnection /*creates a db connection per partition*/
val newPartition = partition.map(record => {
readMatchingFromDB(record, connection)
}).toList // consumes the iterator, thus calls readMatchingFromDB
connection.close() // close dbconnection here
newPartition.iterator // create a new iterator
})
Q2. does
flatMap
behave like map or likemapPartitions
?
Yes. please see example 2 of flatmap
.. its self explanatory.
Q1. What's the difference between an RDD's
map
andmapPartitions
map
works the function being utilized at a per element level whilemapPartitions
exercises the function at the partition level.
Example Scenario : if we have 100K elements in a particular RDD
partition then we will fire off the function being used by the mapping transformation 100K times when we use map
.
Conversely, if we use mapPartitions
then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.
There will be performance gain since map
works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions
).
Applies a transformation function on each item of the RDD and returns the result as a new RDD.
Listing Variants
def map[U: ClassTag](f: T => U): RDD[U]
Example :
val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
val b = a.map(_.length)
val c = a.zip(b)
c.collect
res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8))
This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.
preservesPartitioning
indicates whether the input function preserves the partitioner, which should befalse
unless this is a pair RDD and the input function doesn't modify the keys.Listing Variants
def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]
Example 1
val a = sc.parallelize(1 to 9, 3)
def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
var res = List[(T, T)]()
var pre = iter.next
while (iter.hasNext)
{
val cur = iter.next;
res .::= (pre, cur)
pre = cur;
}
res.iterator
}
a.mapPartitions(myfunc).collect
res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8))
Example 2
val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
var res = List[Int]()
while (iter.hasNext) {
val cur = iter.next;
res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
}
res.iterator
}
x.mapPartitions(myfunc).collect
// some of the number are not outputted at all. This is because the random number generated for it is zero.
res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10)
The above program can also be written using flatMap as follows.
Example 2 using flatmap
val x = sc.parallelize(1 to 10, 3)
x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect
res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10)
mapPartitions
transformation is faster than map
since it calls your function once/partition, not once/element..
Further reading : foreach Vs foreachPartitions When to use What?
You can use .scrollIntoView()
for this. It will bring a specific element into the viewport.
Example:
document.getElementById( 'bottom' ).scrollIntoView();
Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/
Script:
function top() {
document.getElementById( 'top' ).scrollIntoView();
};
function bottom() {
document.getElementById( 'bottom' ).scrollIntoView();
window.setTimeout( function () { top(); }, 2000 );
};
bottom();
HTML:
<div id="top">top</div>
<div id="bottom">bottom</div>
CSS:
#top {
border: 1px solid black;
height: 3000px;
}
#bottom {
border: 1px solid red;
}
You can use this to get border on one side
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
EDITED
As many including me wanted to have a one side border with transparent background, I have implemented a BorderDrawable
which could give me borders with different size and color in the same way as we use css. But this could not be used via xml. For supporting XML, I have added a BorderFrameLayout
in which your layout can be wrapped.
See my github for the complete source.
There is also a tool that oracle made called mysqlshow
If you run it with the --k keys $table_name
option it will display the keys.
SYNOPSIS
mysqlshow [options] [db_name [tbl_name [col_name]]]
.......
.......
.......
· --keys, -k
Show table indexes.
example:
?-? mysqlshow -h 127.0.0.1 -u root -p --keys database tokens
Database: database Table: tokens
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id | int(10) unsigned | | NO | PRI | | auto_increment | select,insert,update,references | |
| token | text | utf8mb4_unicode_ci | NO | | | | select,insert,update,references | |
| user_id | int(10) unsigned | | NO | MUL | | | select,insert,update,references | |
| expires_in | datetime | | YES | | | | select,insert,update,references | |
| created_at | timestamp | | YES | | | | select,insert,update,references | |
| updated_at | timestamp | | YES | | | | select,insert,update,references | |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tokens | 0 | PRIMARY | 1 | id | A | 2 | | | | BTREE | | |
| tokens | 1 | tokens_user_id_foreign | 1 | user_id | A | 2 | | | | BTREE | | |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
It's easier to use the timestamp for this things since Tweepy gets both
import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))
.md
stands for markdown and is generated at the bottom of your github page as html.
Typical syntax includes:
Will become a heading
==============
Will become a sub heading
--------------
*This will be Italic*
**This will be Bold**
- This will be a list item
- This will be a list item
Add a indent and this will end up as code
For more details: http://daringfireball.net/projects/markdown/
We can try by using latest jQuery library. I got the same issue. I used jQuery-1.4.2.min before and getting the error. After that I used version 1.9.1 and it works. Thanks
3D case
Modifying Mohsen's answer for 3D array:
[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)
:.,$d
This will delete all content from current line to end of the file. This is very useful when you're dealing with test vector generation or stripping.
[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]
Imagine you are working on a machine where n
was just the right value for it only to be possible to hold two of your arrays in memory at one time, but the total memory available, via disk caching, was still sufficient to hold all four.
Assuming a simple LIFO caching policy, this code:
for(int j=0;j<n;j++){
a[j] += b[j];
}
for(int j=0;j<n;j++){
c[j] += d[j];
}
would first cause a
and b
to be loaded into RAM and then be worked on entirely in RAM. When the second loop starts, c
and d
would then be loaded from disk into RAM and operated on.
the other loop
for(int j=0;j<n;j++){
a[j] += b[j];
c[j] += d[j];
}
will page out two arrays and page in the other two every time around the loop. This would obviously be much slower.
You are probably not seeing disk caching in your tests but you are probably seeing the side effects of some other form of caching.
There seems to be a little confusion/misunderstanding here so I will try to elaborate a little using an example.
Say n = 2
and we are working with bytes. In my scenario we thus have just 4 bytes of RAM and the rest of our memory is significantly slower (say 100 times longer access).
Assuming a fairly dumb caching policy of if the byte is not in the cache, put it there and get the following byte too while we are at it you will get a scenario something like this:
With
for(int j=0;j<n;j++){
a[j] += b[j];
}
for(int j=0;j<n;j++){
c[j] += d[j];
}
cache a[0]
and a[1]
then b[0]
and b[1]
and set a[0] = a[0] + b[0]
in cache - there are now four bytes in cache, a[0], a[1]
and b[0], b[1]
. Cost = 100 + 100.
a[1] = a[1] + b[1]
in cache. Cost = 1 + 1.c
and d
.Total cost = (100 + 100 + 1 + 1) * 2 = 404
With
for(int j=0;j<n;j++){
a[j] += b[j];
c[j] += d[j];
}
cache a[0]
and a[1]
then b[0]
and b[1]
and set a[0] = a[0] + b[0]
in cache - there are now four bytes in cache, a[0], a[1]
and b[0], b[1]
. Cost = 100 + 100.
a[0], a[1], b[0], b[1]
from cache and cache c[0]
and c[1]
then d[0]
and d[1]
and set c[0] = c[0] + d[0]
in cache. Cost = 100 + 100.(100 + 100 + 100 + 100) * 2 = 800
This is a classic cache thrash scenario.
If you are using OpenLDAP (i.e. slapd) which is common on Linux servers, then you must enable the memberof overlay to be able to match against a filter using the (memberOf=XXX) attribute.
Also, once you enable the overlay, it does not update the memberOf attributes for existing groups (you will need to delete out the existing groups and add them back in again). If you enabled the overlay to start with, when the database was empty then you should be OK.
If you have just a pair of brackets ( []
) in your string, you can use indexOf()
:
String str = "ABC[ This is the text to be extracted ]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
this will be work in my case when in tabs i switch from one fragment to another fragments
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
try {
InputMethodManager mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
Log.e(TAG, "setUserVisibleHint: ", e);
}
}
}
On Ubuntu, You can follow these steps to resolve the issue:
$HOME/.mozilla
, if it doesn't exist alreadyCreate a symlink to libnpjp2.so inside this directory using this command:
ln -s $JAVA_HOME/jre/lib/i386/libnpjp2.so $MOZILLA_HOME/plugins
-or-
ln -s $JAVA_HOME/jre/lib/amd64/libnpjp2.so $MOZILLA_HOME/plugins
depending on whether you're using a 32 or 64 bit JVM installation. Moreover, $JAVA_HOME is the location of your JVM installation.
More detailed instructions can be found here.
I was reading path from a properties file and didn't mention there was a space in the end. Make sure you don't have one.
You could do it in either of this ways , triggering an onclick
on a form button like this,
<form id="myform" name="myform" method="post" action="demo2.jsp">
<input type="text" name="usnername" />
<input type="text" name="password"/>
<input type="button" value="go" onclick="submitForm" />
</form>
And using javascript
,
function submitForm() {
document.forms[0].submit();
return true;
}
or you could also try Ajax
to post your page
here is the link jQueryAjax
And also nice startup examples using Ajax and here
Hope this helps !!
Since the original solution was provided for very early version of react, here is an update:
constructor(props) {
super(props)
this.myRef = React.createRef() // Create a ref object
}
componentDidMount() {
this.myRef.current.scrollTo(0, 0);
}
render() {
return <div ref={this.myRef}></div>
} // attach the ref property to a dom element
This is a bit of a pain on Windows. Here's what I do.
Install latest Sun JDK, e.g. 6u11, in path like c:\install\jdk\sun\6u11
, then let the installer install public JRE in the default place (c:\program files\blah
). This will setup your default JRE for the majority of things.
Install older JDKs as necessary, like 5u18 in c:\install\jdk\sun\5u18
, but don't install the public JREs.
When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set JAVA_HOME=c:\jdk\sun\JDK_DESIRED
and then set PATH=%JAVA_HOME%\bin;%PATH%
. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the JAVA_HOME
variable.
The path is important because most public JRE installs put a linked executable at c:\WINDOWS\System32\java.exe
, which usually overrides most other settings.
They changed print
in Python 3. In 2 it was a statement, now it is a function and requires parenthesis.
Here's the docs from Python 3.0.
Just for the record in modern times,
1 - Just have updated Xcode on your machine as you normally do
2 - Open terminal and
$ xcode-select --install
it will perform a short install of a minute or two.
3 - Launch Xcode. "New" "Project" ... you have to choose "Command line tool"
Note - confusingly this is under the "macOS" tab.
Select "C" language on the next screen...
4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.
5 - You're golden! You can now enjoy c with Mac and Xcode.
Another good method for setting a DropDownList style combobox:
Combox1.SelectedIndex = Combox1.FindStringExact("test1")
There are some great answers mentioned here. Another approach you could take would be to use some free SDKs available online like Atooma, tranql and Neura, that can be integrated with your Android application (it takes less than 20 min to integrate). Along with giving you the accurate location of your user, it can also give you good insights about your user’s activities. Also, some of them consume less than 1% of your battery
Import numpy as np
FOR INDEX
S=[11,2,44,55,66,0,10,3,33]
r=np.argsort(S)
[output]=array([5, 1, 7, 6, 0, 8, 2, 3, 4])
argsort Returns the indices of S in sorted order
FOR VALUE
np.sort(S)
[output]=array([ 0, 2, 3, 10, 11, 33, 44, 55, 66])
A simple way of keeping the values of fields in different fragments in an activity
Create the Instances of fragments and add instead of replace and remove
FragA fa= new FragA();
FragB fb= new FragB();
FragC fc= new FragB();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmnt_container, fa);
fragmentTransaction.add(R.id.fragmnt_container, fb);
fragmentTransaction.add(R.id.fragmnt_container, fc);
fragmentTransaction.show(fa);
fragmentTransaction.hide(fb);
fragmentTransaction.hide(fc);
fragmentTransaction.commit();
Then just show and hide the fragments instead of adding and removing those again
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(fa);
fragmentTransaction.show(fb);
fragmentTransaction.hide(fc);
fragmentTransaction.commit()
;
You can still use map
if you can afford to create a makeshift array:
{
new Array(this.props.level).fill(0).map((_, index) => (
<span className='indent' key={index}></span>
))
}
This works because new Array(n).fill(x)
creates an array of size n
filled with x
, which can then aid map
.
The first result in your MSDN search said:
The method group identifies the one method to invoke or the set of overloaded methods from which to choose a specific method to invoke
my understanding is that basically because when you just write someInteger.ToString
, it may refer to:
Int32.ToString(IFormatProvider)
or it can refer to:
Int32.ToString()
so it is called a method group.
so it's easy)))
Watch this...
var stuff = {};
$('input[type=checkbox]').each(function(i, e) {
stuff[i] = e.checked;
});
And you will have:
Object {0: true, 1: false, 2: false, 3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff['row'+i] = e.checked;
});
You will have:
Object {row0: true, row1: false, row2: false, row3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff[e.className+i] = e.checked;
});
You will have:
Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
You can also use echo
to remove blank spaces, either at the beginning or at the end of the string, but also repeating spaces inside the string.
$ myVar=" kokor iiij ook "
$ echo "$myVar"
kokor iiij ook
$ myVar=`echo $myVar`
$
$ # myVar is not set to "kokor iiij ook"
$ echo "$myVar"
kokor iiij ook
Facing the same issue with the error described by Garrett above. 1. MongoDB Server with journaling enabled is running as seen using ps command 2. Mongo client or Mongoose driver are unable to connect to the database.
Solution : 1. Deleting the Mongo.lock file seems to bring life back to normal on the CentOS server. 2. We are fairly new in running MongoDB in production and have been seeing the same issue cropping up a couple of times a week. 3. We've setup a cron schedule to regularly cleanup the lock file and intimate the admin that an incident has occurred.
Searching for a bug fix to this issue or any other more permanent way to resolve it.
$(":text[value='']").doStuff();
?
By the way, your call of:
$('input[id=cmdSubmit]')...
can be greatly simplified and speeded up with:
$('#cmdSubmit')...
This works better when the id = container (which is the outer div) and id = contained (which is the inner div). The problem with the highly recommended solution is that it results in some cases into an horizontal scrolling bar when the browser is trying to cater for the left: -50% attribute. There is a good reference for this solution
#container {
text-align: center;
}
#contained {
text-align: left;
display: inline-block;
}
Just add your text between the font tags:
for blue color
<string name="hello_world"><font color='blue'>Hello world!</font></string>
or for red color
<string name="hello_world"><font color='red'>Hello world!</font></string>
Since you asked a similar question, let's take it to step by step. It's a bit longer, but it may save you much more time than I have spent on writing this:
Property is an OOP feature designed for clean separation of client code. For example, in some e-shop you might have objects like this:
function Product(name,price) {
this.name = name;
this.price = price;
this.discount = 0;
}
var sneakers = new Product("Sneakers",20); // {name:"Sneakers",price:20,discount:0}
var tshirt = new Product("T-shirt",10); // {name:"T-shirt",price:10,discount:0}
Then in your client code (the e-shop), you can add discounts to your products:
function badProduct(obj) { obj.discount+= 20; ... }
function generalDiscount(obj) { obj.discount+= 10; ... }
function distributorDiscount(obj) { obj.discount+= 15; ... }
Later, the e-shop owner might realize that the discount can't be greater than say 80%. Now you need to find EVERY occurrence of the discount modification in the client code and add a line
if(obj.discount>80) obj.discount = 80;
Then the e-shop owner may further change his strategy, like "if the customer is reseller, the maximal discount can be 90%". And you need to do the change on multiple places again plus you need to remember to alter these lines anytime the strategy is changed. This is a bad design. That's why encapsulation is the basic principle of OOP. If the constructor was like this:
function Product(name,price) {
var _name=name, _price=price, _discount=0;
this.getName = function() { return _name; }
this.setName = function(value) { _name = value; }
this.getPrice = function() { return _price; }
this.setPrice = function(value) { _price = value; }
this.getDiscount = function() { return _discount; }
this.setDiscount = function(value) { _discount = value; }
}
Then you can just alter the getDiscount
(accessor) and setDiscount
(mutator) methods. The problem is that most of the members behave like common variables, just the discount needs special care here. But good design requires encapsulation of every data member to keep the code extensible. So you need to add lots of code that does nothing. This is also a bad design, a boilerplate antipattern. Sometimes you can't just refactor the fields to methods later (the eshop code may grow large or some third-party code may depend on the old version), so the boilerplate is lesser evil here. But still, it is evil. That's why properties were introduced into many languages. You could keep the original code, just transform the discount member into a property with get
and set
blocks:
function Product(name,price) {
this.name = name;
this.price = price;
//this.discount = 0; // <- remove this line and refactor with the code below
var _discount; // private member
Object.defineProperty(this,"discount",{
get: function() { return _discount; },
set: function(value) { _discount = value; if(_discount>80) _discount = 80; }
});
}
// the client code
var sneakers = new Product("Sneakers",20);
sneakers.discount = 50; // 50, setter is called
sneakers.discount+= 20; // 70, setter is called
sneakers.discount+= 20; // 80, not 90!
alert(sneakers.discount); // getter is called
Note the last but one line: the responsibility for correct discount value was moved from the client code (e-shop definition) to the product definition. The product is responsible for keeping its data members consistent. Good design is (roughly said) if the code works the same way as our thoughts.
So much about properties. But javascript is different from pure Object-oriented languages like C# and codes the features differently:
In C#, transforming fields into properties is a breaking change, so public fields should be coded as Auto-Implemented Properties if your code might be used in the separately compiled client.
In Javascript, the standard properties (data member with getter and setter described above) are defined by accessor descriptor (in the link you have in your question). Exclusively, you can use data descriptor (so you can't use i.e. value and set on the same property):
Both descriptors can have these members:
for(var i in theObject)
; if false, it will not be iterated, but it is still accessible as public* unless in strict mode - in that case JS stops execution with TypeError unless it is caught in try-catch block
To read these settings, use Object.getOwnPropertyDescriptor()
.
Learn by example:
var o = {};
Object.defineProperty(o,"test",{
value: "a",
configurable: true
});
console.log(Object.getOwnPropertyDescriptor(o,"test")); // check the settings
for(var i in o) console.log(o[i]); // nothing, o.test is not enumerable
console.log(o.test); // "a"
o.test = "b"; // o.test is still "a", (is not writable, no error)
delete(o.test); // bye bye, o.test (was configurable)
o.test = "b"; // o.test is "b"
for(var i in o) console.log(o[i]); // "b", default fields are enumerable
If you don't wish to allow the client code such cheats, you can restrict the object by three levels of confinement:
Object.isExtensible(<yourObject>)
to check if the method was used on the object. The prevention is shallow (read below).configurable: false
to all properties). Use Object.isSealed(<yourObject>)
to detect this feature on the object. The seal is shallow (read below).writable: false
to all properties with data descriptor). Setter's writable property is not affected (since it doesn't have one). The freeze is shallow: it means that if the property is Object, its properties ARE NOT frozen (if you wish to, you should perform something like "deep freeze", similar to deep copy - cloning). Use Object.isFrozen(<yourObject>)
to detect it.You don't need to bother with this if you write just a few lines fun. But if you want to code a game (as you mentioned in the linked question), you should care about good design. Try to google something about antipatterns and code smell. It will help you to avoid situations like "Oh, I need to completely rewrite my code again!", it can save you months of despair if you want to code a lot. Good luck.
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
Real VNC Viewer (5.0.3) - Free :
Options->Expert->UseAllMonitors = True
NOTE: When I first spent time reading about REST, idempotence was a confusing concept to try to get right. I still didn't get it quite right in my original answer, as further comments (and Jason Hoetger's answer) have shown. For a while, I have resisted updating this answer extensively, to avoid effectively plagiarizing Jason, but I'm editing it now because, well, I was asked to (in the comments).
After reading my answer, I suggest you also read Jason Hoetger's excellent answer to this question, and I will try to make my answer better without simply stealing from Jason.
As you noted in your RFC 2616 citation, PUT is considered idempotent. When you PUT a resource, these two assumptions are in play:
You are referring to an entity, not to a collection.
The entity you are supplying is complete (the entire entity).
Let's look at one of your examples.
{ "username": "skwee357", "email": "[email protected]" }
If you POST this document to /users
, as you suggest, then you might get back an entity such as
## /users/1
{
"username": "skwee357",
"email": "[email protected]"
}
If you want to modify this entity later, you choose between PUT and PATCH. A PUT might look like this:
PUT /users/1
{
"username": "skwee357",
"email": "[email protected]" // new email address
}
You can accomplish the same using PATCH. That might look like this:
PATCH /users/1
{
"email": "[email protected]" // new email address
}
You'll notice a difference right away between these two. The PUT included all of the parameters on this user, but PATCH only included the one that was being modified (email
).
When using PUT, it is assumed that you are sending the complete entity, and that complete entity replaces any existing entity at that URI. In the above example, the PUT and PATCH accomplish the same goal: they both change this user's email address. But PUT handles it by replacing the entire entity, while PATCH only updates the fields that were supplied, leaving the others alone.
Since PUT requests include the entire entity, if you issue the same request repeatedly, it should always have the same outcome (the data you sent is now the entire data of the entity). Therefore PUT is idempotent.
What happens if you use the above PATCH data in a PUT request?
GET /users/1
{
"username": "skwee357",
"email": "[email protected]"
}
PUT /users/1
{
"email": "[email protected]" // new email address
}
GET /users/1
{
"email": "[email protected]" // new email address... and nothing else!
}
(I'm assuming for the purposes of this question that the server doesn't have any specific required fields, and would allow this to happen... that may not be the case in reality.)
Since we used PUT, but only supplied email
, now that's the only thing in this entity. This has resulted in data loss.
This example is here for illustrative purposes -- don't ever actually do this. This PUT request is technically idempotent, but that doesn't mean it isn't a terrible, broken idea.
In the above example, PATCH was idempotent. You made a change, but if you made the same change again and again, it would always give back the same result: you changed the email address to the new value.
GET /users/1
{
"username": "skwee357",
"email": "[email protected]"
}
PATCH /users/1
{
"email": "[email protected]" // new email address
}
GET /users/1
{
"username": "skwee357",
"email": "[email protected]" // email address was changed
}
PATCH /users/1
{
"email": "[email protected]" // new email address... again
}
GET /users/1
{
"username": "skwee357",
"email": "[email protected]" // nothing changed since last GET
}
I originally had examples that I thought were showing non-idempotency, but they were misleading / incorrect. I am going to keep the examples, but use them to illustrate a different thing: that multiple PATCH documents against the same entity, modifying different attributes, do not make the PATCHes non-idempotent.
Let's say that at some past time, a user was added. This is the state that you are starting from.
{
"id": 1,
"name": "Sam Kwee",
"email": "[email protected]",
"address": "123 Mockingbird Lane",
"city": "New York",
"state": "NY",
"zip": "10001"
}
After a PATCH, you have a modified entity:
PATCH /users/1
{"email": "[email protected]"}
{
"id": 1,
"name": "Sam Kwee",
"email": "[email protected]", // the email changed, yay!
"address": "123 Mockingbird Lane",
"city": "New York",
"state": "NY",
"zip": "10001"
}
If you then repeatedly apply your PATCH, you will continue to get the same result: the email was changed to the new value. A goes in, A comes out, therefore this is idempotent.
An hour later, after you have gone to make some coffee and take a break, someone else comes along with their own PATCH. It seems the Post Office has been making some changes.
PATCH /users/1
{"zip": "12345"}
{
"id": 1,
"name": "Sam Kwee",
"email": "[email protected]", // still the new email you set
"address": "123 Mockingbird Lane",
"city": "New York",
"state": "NY",
"zip": "12345" // and this change as well
}
Since this PATCH from the post office doesn't concern itself with email, only zip code, if it is repeatedly applied, it will also get the same result: the zip code is set to the new value. A goes in, A comes out, therefore this is also idempotent.
The next day, you decide to send your PATCH again.
PATCH /users/1
{"email": "[email protected]"}
{
"id": 1,
"name": "Sam Kwee",
"email": "[email protected]",
"address": "123 Mockingbird Lane",
"city": "New York",
"state": "NY",
"zip": "12345"
}
Your patch has the same effect it had yesterday: it set the email address. A went in, A came out, therefore this is idempotent as well.
I want to draw an important distinction (something I got wrong in my original answer). Many servers will respond to your REST requests by sending back the new entity state, with your modifications (if any). So, when you get this response back, it is different from the one you got back yesterday, because the zip code is not the one you received last time. However, your request was not concerned with the zip code, only with the email. So your PATCH document is still idempotent - the email you sent in PATCH is now the email address on the entity.
For a full treatment of this question, I again refer you to Jason Hoetger's answer. I'm just going to leave it at that, because I honestly don't think I can answer this part better than he already has.
Have a look at this article: Tracing python memory leaks
Also, note that the garbage collection module actually can have debug flags set. Look at the set_debug
function. Additionally, look at this code by Gnibbler for determining the types of objects that have been created after a call.
Judging from the error message the value of i was the empty string when you executed it, not 0.
I recently embraced modules as independent mini-apps.
|-- src
|--module1
|--module2
|--www
|--img
|--js
|--css
|--#.js
|--index.ejs
|--module3
|--www
|--bower_components
|--img
|--js
|--css
|--#.js
|--header.ejs
|--index.ejs
|--footer.ejs
Now for any module routing (#.js), views (*.ejs), js, css and assets are next to each other. submodule routing is set up in the parent #.js with two additional lines
router.use('/module2', opt_middleware_check, require('./module2/#'));
router.use(express.static(path.join(__dirname, 'www')));
This way even subsubmodules are possible.
Don't forget to set view to the src directory
app.set('views', path.join(__dirname, 'src'));
jQuery UI Datepicker is coded to always highlight the user's local date using the class ui-state-highlight
. There is no built-in option to change this.
One method, described similarly in other answers to related questions, is to override the CSS for that class to match ui-state-default
of your theme, for example:
.ui-state-highlight {
border: 1px solid #d3d3d3;
background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;
color: #555555;
}
However this isn't very helpful if you are using dynamic themes, or if your intent is to highlight a different day (e.g., to have "today" be based on your server's clock rather than the client's).
An alternative approach is to override the datepicker prototype that is responsible for highlighting the current day.
Assuming that you are using a minimized version of the UI javascript, the following snippets can address these concerns.
If your goal is to prevent highlighting the current day altogether:
// copy existing _generateHTML method
var _generateHTML = jQuery.datepicker.constructor.prototype._generateHTML;
// remove the string "ui-state-highlight"
_generateHtml.toString().replace(' ui-state-highlight', '');
// and replace the prototype method
eval('jQuery.datepicker.constructor.prototype._generateHTML = ' + _generateHTML);
This changes the relevant code (unminimized for readability) from:
[...](printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + [...]
to
[...](printDate.getTime() == today.getTime() ? '' : '') + [...]
If your goal is to change datepicker's definition of "today":
var useMyDateNotYours = '07/28/2014';
// copy existing _generateHTML method
var _generateHTML = jQuery.datepicker.constructor.prototype._generateHTML;
// set "today" to your own Date()-compatible date
_generateHTML.toString().replace('new Date,', 'new Date(useMyDateNotYours),');
// and replace the prototype method
eval('jQuery.datepicker.constructor.prototype._generateHTML = ' + _generateHTML);
This changes the relevant code (unminimized for readability) from:
[...]var today = new Date();[...]
to
[...]var today = new Date(useMyDateNotYours);[...]
// Note that in the minimized version, the line above take the form `L=new Date,`
// (part of a list of variable declarations, and Date is instantiated without parenthesis)
Instead of useMyDateNotYours
you could of course also instead inject a string, function, or whatever suits your needs.
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
You can use this : http://jsbeautifier.org/ But it depends on the minify method you are using, this one only formats the code, it doesn't change variable names, nor uncompress base62 encoding.
edit: in fact it can unpack "packed" scripts (packed with Dean Edward's packer : http://dean.edwards.name/packer/)
If you're using a version of Java prior to 8... you can use Joda Time and PeriodFormatter
. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using Duration
for the most part - you can then call toPeriod
(specifying whatever PeriodType
you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a Period
which you can format.
If you're using Java 8 or later: I'd normally suggest using java.time.Duration
to represent the duration. You can then call getSeconds()
or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a single negative sign in the output string. So something like:
public static String formatDuration(Duration duration) {
long seconds = duration.getSeconds();
long absSeconds = Math.abs(seconds);
String positive = String.format(
"%d:%02d:%02d",
absSeconds / 3600,
(absSeconds % 3600) / 60,
absSeconds % 60);
return seconds < 0 ? "-" + positive : positive;
}
Formatting this way is reasonably simple, if annoyingly manual. For parsing it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.
That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.
Of course, if you're also getting an error along the lines of can't find lPI-Http
then you have a problem :-)
It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:
CFLAGS
rather than
CTAGS
- are you sure this is
correct? (What you have may be correct - this will depend on your build system!)LDFLAGS
If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx
etc) that was being executed?
I had this problem on Ubuntu 18.04. I updated the gem
sudo gem install rails
sudo gem install jekyll
sudo gem install jekyll bundler
cd ~/desiredFolder
jekyll new <foldername>
cd <foldername> OR
bundle init
bundle install
bundle add jekyll
bundle exec jekyll serve
All worked and goto your browser just go to http://127.0.0.1:4000/ and it really should be running
@throw([NSException exceptionWith…])
Xcode recognizes @throw
statements as function exit points, like return
statements. Using the @throw
syntax avoids erroneous "Control may reach end of non-void function" warnings that you may get from [NSException raise:…]
.
Also, @throw
can be used to throw objects that are not of class NSException.
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
res/drawable
folderOpen manifest file and set
Run program
Some others figured out that this is wrong. In the meantime i share their opinion. I'm sorry.
Old WRONG answer:
In my opinion this is barely possible.
Your Computer identifies any USB device with the USB device descriptor or the usb interface descriptor. To be able to use your android device as a keyboard, you would have to change these. Actually i think these are saved on a ROM in the device, so you would have to change hardware. The device needs to identifiy itself with the host even if its only charging in turned off state (has to tell usb host about the power consumption, otherwise only a few mA max). For me this points into the direction, that you would have to change hardware
"Easiest" way would proabably be assemble an adapter containing a usb host chip with a µC that converts the received data (which you still had to send via usb) to ps/2 or usb-client signals that u send to the computer.
In my opinion the easiest way would be: Buy one of these Keyboards you can roll and put them in your bag too.
Use DATEPART to pull apart your interval, and DATEADD to subtract the parts:
select dateadd(
hh,
-1 * datepart(hh, cast('1:15' as datetime)),
dateadd(
mi,
-1 * datepart(mi, cast('1:15' as datetime)),
'2000-01-01 08:30:00'))
or, we can convert to minutes first (though OP would prefer not to):
declare @mins int
select @mins = datepart(mi, cast('1:15' as datetime)) + 60 * datepart(hh, cast('1:15' as datetime))
select dateadd(mi, -1 * @mins, '2000-01-01 08:30:00')
You need some tools like pdf2text to first convert your pdf to a text file and then search inside the text. (You will probably miss some information or symbols).
If you are using a programming language there are probably pdf libraries written for this purpose. e.g. http://search.cpan.org/dist/CAM-PDF/ for Perl
I also came across the same error. Here is the fix: If you are using Cmake-GUI:
If you missed the 3rd step:
*** No rule to make target `install'. Stop.
error will occur.
You can directly use curl to upgrade node to the latest version. Run the following command:
curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg</a>.*|\1|p')}.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/"
Reference: https://nodejs.org/en/download/package-manager/#macos
Both Chrome and Firefox now have built-in emulators. They aren't perfect but are good enough that can get you almost all of the way before testing on an actual device. The best part is if you like the browser's developer tools (Chrome, Firefox), you can use them while emulating.
To get the emulator: [Ctrl+Shift+M] and select the device that you want to emulate. You might have to refresh the page, esp if you have anything that depends on script that executes on page load.
Internet Explorer also has a device emulation mode. F12, then CTRL+8. It's not quite as straight forward as the Chrome Mobile Device emulation, but does allow you to simulate geolocation:
Be careful, you can not modify the preflight. In addition, the browser (at least chrome) removes the "authorization" header ... this results in some problems that may arise according to the route design. For example, a preflight will never enter the passport route sheet since it does not have the header with the token.
In case you are designing a file with an implementation of the options method, you must define in the route file web.php one (or more than one) "trap" route so that the preflght (without header authorization) can resolve the request and Obtain the corresponding CORS headers. Because they can not return in a middleware 200 by default, they must add the headers on the original request.
only variable/object declaration statement are written outside of method
public class details{
public static void main(String arg[]){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
here is example try to learn java book and see the syntax then try to develop the program
Something like this should work
var text = $('#toptitle').text();
if (text == 'Profil'){
$('#toptitle').text('New Word');
}
This is not supported by default, but you can make it work quite easily! There are several things you'll want to encode if you want the exact same data back:
obj.tolist()
as @travelingbones mentioned. Sometimes this may be good enough.Furthermore, your numpy array could part of your data structure, e.g. you have a list with some matrices inside. For that you could use a custom encoder which basically does the above.
This should be enough to implement a solution. Or you could use json-tricks which does just this (and supports various other types) (disclaimer: I made it).
pip install json-tricks
Then
data = [
arange(0, 10, 1, dtype=int).reshape((2, 5)),
datetime(year=2017, month=1, day=19, hour=23, minute=00, second=00),
1 + 2j,
Decimal(42),
Fraction(1, 3),
MyTestCls(s='ub', dct={'7': 7}), # see later
set(range(7)),
]
# Encode with metadata to preserve types when decoding
print(dumps(data))
had this problem as output from Azure DevOps after setting to build the .csproj instead of the .sln in the Build Pipeline.
The solution for me: Edit .csproj of the affected project, then copy your whole
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCpu' ">
Node, paste it, and then change the first line as followed:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|any cpu' ">
The reason is, that in my case the error said
Please check to make sure that you have specified a valid combination of Configuration and Platform for this project. Configuration='release' Platform='any cpu'.
Why Azure wants to use "any cpu" instead of the default "AnyCpu" is a mystery for me, but this hack works.
int[] a = {1,2,3,4,5};
int [] b= new int[a.length]; //New Array and the size of a which is 4
Array.Copy(a,b,a.length);
Where Array is class having method Copy, which copies the element of a array to b array.
While copying from one array to another array, you have to provide same data type to another array of which you are copying.
@tieuminh2510 answer is perfect. But in newer versions of VSC you will not find thhe option to edit or paste that command in User Settings. Now in newer version to add that code follow this steps :
Press ctr+sft+P to open the the Command Palette. Now in command palette type Preferences: Configure Language Specific Settings. Now select Python. Here in right side paste this code
"python.linting.pylintArgs": [
"--load-plugins=pylint_django",
]
Inside the first curly braces. Make sure that pylint-django is also installed.
Hope this will help!
You can also use the following alternative realpath.
Create a file called path.php
Put the following code inside by specifying the name of the created file.
<?php
echo realpath('path.php');
?>
A php file that you can move to all your folders to always have the absolute path from where the executed file is located.
;-)
Decorators seem better suited to modify the functionality of an entire object (including function objects) versus the functionality of an object method which in general will depend on instance attributes. For example:
def mod_bar(cls):
# returns modified class
def decorate(fcn):
# returns decorated function
def new_fcn(self):
print self.start_str
print fcn(self)
print self.end_str
return new_fcn
cls.bar = decorate(cls.bar)
return cls
@mod_bar
class Test(object):
def __init__(self):
self.start_str = "starting dec"
self.end_str = "ending dec"
def bar(self):
return "bar"
The output is:
>>> import Test
>>> a = Test()
>>> a.bar()
starting dec
bar
ending dec
Yes.
Map.Entry
can be used as a Pair
.
Unfortunately it does not help with Java 8 streams as the problem is that even though lambdas can take multiple arguments, the Java language only allows for returning a single value (object or primitive type). This implies that whenever you have a stream you end up with being passed a single object from the previous operation. This is a lack in the Java language, because if multiple return values was supported AND streams supported them we could have much nicer non-trivial tasks done by streams.
Until then, there is only little use.
EDIT 2018-02-12: While working on a project I wrote a helper class which helps handling the special case of having an identifier earlier in the stream you need at a later time but the stream part in between does not know about it. Until I get around to release it on its own it is available at IdValue.java with a unit test at IdValueTest.java
R has a number of (undocumented) convenience functions for converting factors:
as.character.factor
as.data.frame.factor
as.Date.factor
as.list.factor
as.vector.factor
But annoyingly, there is nothing to handle the factor -> numeric conversion. As an extension of Joshua Ulrich's answer, I would suggest to overcome this omission with the definition of your own idiomatic function:
as.numeric.factor <- function(x) {as.numeric(levels(x))[x]}
that you can store at the beginning of your script, or even better in your .Rprofile
file.
I used encoding filter which has solved my all encoding problem...
package com.dina.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
*
* @author DINANATH
*/
public class EncodingFilter implements Filter {
private String encoding = "utf-8";
public void doFilter(ServletRequest request,ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
// response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String encodingParam = filterConfig.getInitParameter("encoding");
if (encodingParam != null) {
encoding = encodingParam;
}
}
public void destroy() {
// nothing todo
}
}
in web.xml
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>
com.dina.filter.EncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;
Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.
N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.
Use the following:
SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'
Just for reference I have a 2 million record table, I ran a similar query. Salils answer took 4.48 seconds, the above took 2.25 seconds.
So if the table is BIG I would suggest this rather.
Using domain Name may solve the problem (get domain name using powershell: $env:userdomain):
Hashtable<String, Object> env = new Hashtable<String, Object>();
String principalName = "domainName\\userName";
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://URL:389/OU=ou-xx,DC=fr,DC=XXXXXX,DC=com");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principalName);
env.put(Context.SECURITY_CREDENTIALS, "Your Password");
try {
DirContext authContext = new InitialDirContext(env);
// user is authenticated
System.out.println("USER IS AUTHETICATED");
} catch (AuthenticationException ex) {
// Authentication failed
System.out.println("AUTH FAILED : " + ex);
} catch (NamingException ex) {
ex.printStackTrace();
}
You can put the control you want to center inside a Panel and set the left and right padding values to something larger than the default. As long as they are equal and your control is anchored to the sides of the Panel, then it will appear centered in that Panel. Then you can anchor the container Panel to its parent as needed.
Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read.
http://www.nvidia.com/object/cuda_home.html
Hello world would be to do any kind of calculation using GPU.
Hope that helps.
If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:
select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;
Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.
If the function you called returns null, it means your phone number is not registered in your contact list.
If instead of the phone number you just need an unique number, you may use the sim card's serial number:
TelephonyManager telemamanger = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
You need to define the enum outside of the class.
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
// ...
That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.
you can do like this
<a href="http://www.w3c.org/" target="_blank">W3C Home Page</a>
find this page
http://www.corelangs.com/html/links/new-window.html
goreb
If it were about committed changes, you should have a look at git-rebase, but as pointed out in comment by VonC, as you're talking about local changes, git-stash would certainly be the good way to do this.
This will
/\bword\b/.test("Thisword is not valid");
return false
, when this one
/\bword\b/.test("This word is valid");
will return true
.
You can use either Picasso
or Glide
.
Picasso.with(context)
.load(your_url)
.into(imageView);
Glide.with(context)
.load(your_url)
.into(imageView);
In C# 6 you can use string interpolation:
string name = "John";
string result = $"Hello {name}";
The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.
HTML5 introduces a number of APIs that help in creating Web applications. These can be used together with the new elements introduced for applications:
contenteditable
attribute.draggable
attribute.borrowed this shamely from here
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
More information here
Normally svn add *
works. But if you get message like svn: warning: W150002:
due to mix off versioned and non-versioned files in working copy. Use this command:
svn add <path to directory> --force
or
svn add * --force
The bash way - convert the dates into %y%m%d format and then you can do this straight from the command line:
echo $(( ($(date --date="031122" +%s) - $(date --date="021020" +%s) )/(60*60*24) ))
Your solution is ok. only try it in this way:
files=$(grep -rl oldstr path) && echo $files | xargs sed....
so execute the xargs
only when grep return 0
, e.g. when found the string in some files.
In Node.js, you could use:
console.log('Current directory: ' + process.cwd());
Using Guava
List<Object> lst ...
List<String> ls = Lists.transform(lst, Functions.toStringFunction());
As Anton Gogolev noted, FileStream reads 4096 bytes at a time by default, But you can specify any other value using the FileStream constructor:
new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 16 * 1024 * 1024)
Note that Brad Abrams from Microsoft wrote in 2004:
there is zero benefit from wrapping a BufferedStream around a FileStream. We copied BufferedStream’s buffering logic into FileStream about 4 years ago to encourage better default performance
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
Java is programming language but Core java is just a part of java. Core java is the basic of java. If you are new to JAVA then you have to start with core java.
Java is basically categories in 3 parts :
1.) J2SE / Core java stands for Java 2 standard edition and is normally for developing desktop applications, forms the core/base API.
2.) J2EE stands for Java 2 enterprise edition for applications which run on servers, for example web sites. (Spring, Struts are the java frameworks mainly used for J2EE)
3.) J2ME stands for Java 2 micro edition for applications which run on resource constrained devices (small scale devices) like cell phones, for example games.
To learn J2EE or J2ME, you should know core java.
You can also use the [NonSerialized]
attribute
[Serializable]
public struct MySerializableStruct
{
[NonSerialized]
public string hiddenField;
public string normalField;
}
Indicates that a field of a serializable class should not be serialized. This class cannot be inherited.
If you're using Unity for example (this isn't only for Unity) then this works with UnityEngine.JsonUtility
using UnityEngine;
MySerializableStruct mss = new MySerializableStruct
{
hiddenField = "foo",
normalField = "bar"
};
Debug.Log(JsonUtility.ToJson(mss)); // result: {"normalField":"bar"}
You could use module scope. Say you have a module called utils
:
f_value = 'foo'
def f():
return f_value
f_value
is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils
from one module will be accessible to all other modules that have it imported:
>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'
Note that you can import the function by name:
>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'
But not the attribute:
>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'
This is because you're labeling the object referenced by the module attribute as f_value
in the local scope, but then rebinding it to the string bar
, while the function f
is still referring to the module attribute.
The default location to put all the web projects in ubuntu
with LAMPP
is :
/var/www/
You may make symbolic link to public_html directory from this directory.Refered. Hope this is helpful.
ORA-12154: TNS:could not resolve the connect identifier specified?
In case the TNS is not defined you can also try this one:
If you are using C#.net 2010
or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:
static string constr = @"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
User Id=system ;Password=yourpasswrd";
After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified
then first you have to do restart your system and run your project.
And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:
Oracle Data Provider for .NET 2.0
Oracle Providers for ASP.NET
Oracle Developer Tools for Visual Studio
Oracle Instant Client
And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......
In my opinion you have two options:
Just try to convert it to an int
, but catch the exception:
try:
value = int(value)
except ValueError:
pass # it was a string, not an int.
This is the Ask Forgiveness approach.
Explicitly test if there are only digits in the string:
value.isdigit()
str.isdigit()
returns True
only if all characters in the string are digits (0
-9
).
The unicode
/ Python 3 str
type equivalent is unicode.isdecimal()
/ str.isdecimal()
; only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).
This is often called the Ask Permission approach, or Look Before You Leap.
The latter will not detect all valid int()
values, as whitespace and +
and -
are also allowed in int()
values. The first form will happily accept ' +10 '
as a number, the latter won't.
If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.
The answer are accepted but one thing you could also do is to define the libraries from your project structure. What you can do is :
What happens is the predefined libraries as off now now I'm taking the appcompat:26.0.0-alpha1 it uses the older version of the things when you add something new and tries to resolve it with the old stuffs. When you add it from your project structure, it'll add the same thing but with the new stuffs to resolve it. Your problem would be resolved.
You can't do a bulk-update in SSIS within a dataflow task with the OOB components.
The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.
Stage data
Set based updates
You'll get much better performance with a pattern like this versus using the OLE DB Command
transformation for anything but trivial amounts of data.
If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.
Test if you can request from other apps (like safari). If not might be something on your computer. In my case I had this problem with Avast Antivirus, which was blocking my simulators request (don't ask me why).
To turn on "Install via USB" and "USB Debugging(Security changes)" need to sign in to xiaomi account then these 2 can be turned on and work with redmi as developer
Note:When turning on USB Debugging(Security changes) few security alerts will be poped up all need to be accepted to work on developer mode
I thought I will post my answer as I recently got into a similar issue (as of September 2019). The App is free for all users in all countries.
For me, after I received a confirmation email from Apple saying that my app is ready for sale (the email did not mention any 24 hours waiting period), I could not find my App in the App Store.
The link to view the App in the App Store in the iTunes Connect (under the App Information section at the bottom page) was broken.
After reading your comments in this thread, I went to the Pricing and Availability section of the App and edited the pricing plan again to be 0 GBP and start date Today and finish date No Finish Date.
Then, I unchecked the countries the App is available on and checked them all again and hit Save.
The App became immediately available in the App store. The link in the App information section was directing me to the App Store and no longer broken.
I hope this will help anyone who is having similar issues lately (getting a confirmation email that the App is ready for sale but cannot find it in the App Store).
I think your issue is that Range("H18")
doesn't contain a formula. Also, you could make your code more efficient by eliminating x
. Instead, change your code to
Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")
Take a look at the PDOStatement.fetchAll
method. You could also use fetch
in an iterator pattern.
Code sample for fetchAll
, from the PHP documentation:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
A vast majority of answers here don't answer the edited part, I guess they were added before. It can be done with regex, as one answer mentions. I had a different approach.
This function searches $string and finds the first string between $start and $end strings, starting at $offset position. It then updates the $offset position to point to the start of the result. If $includeDelimiters is true, it includes the delimiters in the result.
If the $start or $end string are not found, it returns null. It also returns null if $string, $start, or $end are an empty string.
function str_between(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?string
{
if ($string === '' || $start === '' || $end === '') return null;
$startLength = strlen($start);
$endLength = strlen($end);
$startPos = strpos($string, $start, $offset);
if ($startPos === false) return null;
$endPos = strpos($string, $end, $startPos + $startLength);
if ($endPos === false) return null;
$length = $endPos - $startPos + ($includeDelimiters ? $endLength : -$startLength);
if (!$length) return '';
$offset = $startPos + ($includeDelimiters ? 0 : $startLength);
$result = substr($string, $offset, $length);
return ($result !== false ? $result : null);
}
The following function finds all strings that are between two strings (no overlaps). It requires the previous function, and the arguments are the same. After execution, $offset points to the start of the last found result string.
function str_between_all(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?array
{
$strings = [];
$length = strlen($string);
while ($offset < $length)
{
$found = str_between($string, $start, $end, $includeDelimiters, $offset);
if ($found === null) break;
$strings[] = $found;
$offset += strlen($includeDelimiters ? $found : $start . $found . $end); // move offset to the end of the newfound string
}
return $strings;
}
Examples:
str_between_all('foo 1 bar 2 foo 3 bar', 'foo', 'bar')
gives [' 1 ', ' 3 ']
.
str_between_all('foo 1 bar 2', 'foo', 'bar')
gives [' 1 ']
.
str_between_all('foo 1 foo 2 foo 3 foo', 'foo', 'foo')
gives [' 1 ', ' 3 ']
.
str_between_all('foo 1 bar', 'foo', 'foo')
gives []
.
I had the same problem, even with no other errors showing on the "Error List" view after "Rebuild Solution". However, on the "Output" view, I saw the error that was behind the issue:
The primary reference "C:...\myproj.dll" could not be resolved because it was built against the ".NETFramework,Version=v4.6.1" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.5"
Once I corrected this, the issue was resolved.
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project. http://tclap.sourceforge.net/
A similar library is available for C as well. http://argtable.sourceforge.net/
SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name
You can change your project XML to add existing subfolders and structures automatically into your project like "node_modules" from NPM:
This is for older MSBuild / Visual Studio versions
<ItemGroup>
<Item Include="$([System.IO.Directory]::GetFiles("$(MSBuildProjectDirectory)\node_modules","*",SearchOption.AllDirectories))"></Item>
</ItemGroup>
For the current MSBuild / Visual Studio versions:
Just put it in the nodes of the xml:
<Project>
</Project>
In this case just change $(MSBuildProjectDirectory)\node_modules to your folder name.
Yes an Untrusted certificate can cause this. Look at the certificate path for the webservice by opening the websservice in a browser and use the browser tools to look at the certificate path. You may need to install one or more intermediate certificates onto the computer calling the webservice. In the browser you may see "Certificate errors" with an option to "Install Certificate" when you investigate further - this could be the certificate you missing.
My particular problem was a Geotrust Geotrust DV SSL CA intermediate certificate missing following an upgrade to their root server in July 2010 https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422
(2020 update deadlink preserved here: https://web.archive.org/web/20140724085537/https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422 )
Also check that
<modules>
<remove name="FormsAuthentication"/>
</modules>
If you found anything like this just remove:
<remove name="FormsAuthentication"/>
Line from web.config and here you go it will work fine I have tested it.
case 1 : if you are running project in your local system like 127.0.01:8000 ,
then
add SESSION_DOMAIN=
in your .env file
or in your config/session.php 'domain' => env('SESSION_DOMAIN', ''),
and then run php artisan cache:clear
case 2: if project is running on server and you have domain like "mydomain.com"
add SESSION_DOMAIN=mydomain.com
in your .env file
or in your config/session.php 'domain' => env('SESSION_DOMAIN', 'mydomain.com'),
and then run php artisan cache:clear
HTML4 specification states that:
Inline elements may contain only data and other inline elements
Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.
HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.
For anyone looking also for a solution for authentication, I would add on the scoped packages solution that you can have multiple lines in your .npmrc
file:
//internal-npm.example.com:8080/:_authToken=xxxxxxxxxxxxxxx
//registry.npmjs.org/:_authToken=yyyyyyyyyy
Each line represents a different NPM registry
the solution was simple -
toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
If you want it outside of loop then use the below code.
<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id );
echo $display_name;
?>
The answers here helped me up to a point, but I had a problem on HTML5 Number input fields when clicking the up/down buttons in Chrome.
If you click one of the buttons, and left the mouse over the button the number would keep changing as if you were holding the mouse button because the mouseup was being thrown away.
I solved this by removing the mouseup handler as soon as it had been triggered as below:
$("input:number").focus(function () {
var $elem = $(this);
$elem.select().mouseup(function (e) {
e.preventDefault();
$elem.unbind(e.type);
});
});
Hope this helps people in the future...
You can also use $.parseJSON(data)
that will explicit convert a string thats come from a PHP script to a real JSON array.
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
date only work with GNU date (usually comes with Linux)
for OS X, two choices:
change command (verified)
#!/bin/sh #DATE=20090801204150 #date -jf "%Y%m%d%H%M%S" $DATE "+date \"%A,%_d %B %Y %H:%M:%S\"" date "Saturday, 1 August 2009 20:41:50"
http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html
Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html
I also had this problem when trying to connect remotely via the Hamachi VPN. I had tried everything available on the internet (including this post) and it still did not work. Note that everything worked fine when the same database was installed on a machine on my local network. Finally I was able to achieve success using the following fix: on the remote machine, enable the IP address on the TCP/IP protocol, like so:
On the remote machine, start SQL Server Configuration Manager, expand SQL Server Network Configuration, select "Protocols for SQLEXPRESS" (or "MSSQLSERVER"), right-click on TCP/IP, on the resulting dialog box go to the IP Addresses tab, and make sure the "IP1" element is Active=Yes
and Enabled=Yes
. Make note of the IP address (for me it wasn't necessary to modify these). Then stop and start the SQL Server Services. After that, ensure that the firewall on the remote machine is either disabled, or an exception is allowed for port 1433 that includes both the local subnet and the subnet for the address noted in the previous dialog box. On your local machine you should be able to connect by setting the server name to 192.168.1.22\SQLEXPRESS
(or [ip address of remote machine]\[SQL server instance name]
).
Hope that helps.
//form/descendant::input[@type='submit']
In this part of your SP:
IF @DateFirst <> '' and @DateLast <> ''
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + @DateFirst
+ ' and convert (Date,DateLog) <=''' + @DateLast
you are trying to concatenate strings and datetimes.
As the datetime
type has higher priority than varchar
/nvarchar
, the +
operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= '''
and others) to datetime or numeric values. And fails.
That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.
To amend the situation, you need to add explicit casting of your datetime variables to strings:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst)
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)
You'll also need to add closing single quotes:
set @FinalSQL = @FinalSQL
+ ' or convert (Date,DateLog) >= ''' + convert(date, @DateFirst) + ''''
+ ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''
Simple and dependency-free. Uses a Promise so that you can await the result. It returns the response body and does not check the response status code.
const https = require('https');
function httpsPost({body, ...options}) {
return new Promise((resolve,reject) => {
const req = https.request({
method: 'POST',
...options,
}, res => {
const chunks = [];
res.on('data', data => chunks.push(data))
res.on('end', () => {
let body = Buffer.concat(chunks);
switch(res.headers['content-type']) {
case 'application/json':
body = JSON.parse(body);
break;
}
resolve(body)
})
})
req.on('error',reject);
if(body) {
req.write(body);
}
req.end();
})
}
Usage:
async function main() {
const res = await httpsPost({
hostname: 'sentry.io',
path: `/api/0/organizations/org/releases/${changesetId}/deploys/`,
headers: {
'Authorization': `Bearer ${process.env.SENTRY_AUTH_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
environment: isLive ? 'production' : 'demo',
})
})
}
main().catch(err => {
console.log(err)
})
When you write an implementation file (.cpp
, .cxx
, etc) your compiler generates a translation unit. This is the source file from your implementation plus all the headers you #include
d in it.
Internal linkage refers to everything only in scope of a translation unit.
External linkage refers to things that exist beyond a particular translation unit. In other words, accessible through the whole program, which is the combination of all translation units (or object files).
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:-
Security concern using express.bodyParser()
While all the other answers currently recommend using the express.bodyParser()
middleware, this is actually a wrapper around the express.json()
, express.urlencoded()
, and express.multipart()
middlewares (http://expressjs.com/api.html#bodyParser). The parsing of form request bodies is done by the express.urlencoded()
middleware and is all that you need to expose your form data on req.body
object.
Due to a security concern with how express.multipart()
/connect.multipart()
creates temporary files for all uploaded files (and are not garbage collected), it is now recommended not to use the express.bodyParser()
wrapper but instead use only the middlewares you need.
Note: connect.bodyParser()
will soon be updated to only include urlencoded
and json
when Connect 3.0 is released (which Express extends).
So in short, instead of ...
app.use(express.bodyParser());
...you should use
app.use(express.urlencoded());
app.use(express.json()); // if needed
and if/when you need to handle multipart forms (file uploads), use a third party library or middleware such as multiparty, busboy, dicer, etc.
Create links using JavaScript:
<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>
OR
<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>
OR
<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>
I found a lot of answers, but probably the best solution for me is
.parent {
overflow: hidden;
}
.parent .floatLeft {
# your other styles
float: left;
margin-bottom: -99999px;
padding-bottom: 99999px;
}
You can check other solutions here http://css-tricks.com/fluid-width-equal-height-columns/
The solution is to use JS to horizontally scroll the top div so that it matches the bottom div.
You must be very careful to make sure the top and bottom are exactly the same sizes, for example you might need to make the TD and TH use fixed widths.
Here is a fiddle https://jsfiddle.net/jdhenckel/yzjhk08h/5/
The important parts: CSS use
.head {
overflow-x: hidden;
overflow-y: scroll;
width: 500px;
}
.lower {
overflow-x: auto;
overflow-y: scroll;
width: 500px;
height: 400px;
}
Notice overflow-y
must be the same on both head and lower.
And the Javascript...
var head = document.querySelector('.head');
var lower = document.querySelector('.lower');
lower.addEventListener('scroll', function (e) {
console.log(lower.scrollLeft);
head.scrollLeft = lower.scrollLeft;
});
Just got the same problem and I have a relatively simple solution that does not require any change in the page character encoding(wich is a pain in the ass).
For example, your site is in utf-8 and you want to post a form to a site in iso-8859-1. Just change the action of the post to a page on your site that will convert the posted values from utf-8 to iso-8859-1.
this could be done easily in php with something like this:
<?php
$params = array();
foreach($_POST as $key=>$value) {
$params[] = $key."=".rawurlencode(utf8_decode($value));
}
$params = implode("&",$params);
//then you redirect to the final page in iso-8859-1
?>
There is no answer in pure javascript that returns relative coordinates when the reference element is nested inside others which can be with absolute positioning. Here is a solution to this scenario:
function getRelativeCoordinates (event, referenceElement) {
const position = {
x: event.pageX,
y: event.pageY
};
const offset = {
left: referenceElement.offsetLeft,
top: referenceElement.offsetTop
};
let reference = referenceElement.offsetParent;
while(reference){
offset.left += reference.offsetLeft;
offset.top += reference.offsetTop;
reference = reference.offsetParent;
}
return {
x: position.x - offset.left,
y: position.y - offset.top,
};
}
For future questions, It's also possible to do it by using float
property and clearing it in each 3 elements.
Here's an example I've made.
.grid {_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
float: left;_x000D_
margin: 8px;_x000D_
width: 48px;_x000D_
height: 48px;_x000D_
background-color: #bdbdbd;_x000D_
font-family: 'Helvetica', 'Arial', sans-serif;_x000D_
font-size: 14px;_x000D_
font-weight: 400;_x000D_
line-height: 20px;_x000D_
text-indent: 4px;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
.cell:nth-child(3n) + .cell {_x000D_
clear: both;_x000D_
}
_x000D_
<div class="grid">_x000D_
<div class="cell">1</div>_x000D_
<div class="cell">2</div>_x000D_
<div class="cell">3</div>_x000D_
<div class="cell">4</div>_x000D_
<div class="cell">5</div>_x000D_
<div class="cell">6</div>_x000D_
<div class="cell">7</div>_x000D_
<div class="cell">8</div>_x000D_
<div class="cell">9</div>_x000D_
<div class="cell">10</div>_x000D_
</div>
_x000D_
Delete the line "/*# sourceMappingURL=bootstrap.min.css.map */ "
in following files.
To fetch the file path in Linux use the command find / -name "\*bootstrap\*"
Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top
, padding-bottom
, padding-left
, and padding-right;
or padding: [top] [right] [bottom] [left];
).
I have found some solution after so much googling. You can also try it if tired to search for a good solution.
You need username and password to make SOAP request on https://www.livedocx.com
Make registration using this https://www.livedocx.com/user/account_registration.aspx and follow the steps accordingly.
Use below code in your .php file.
ini_set ('soap.wsdl_cache_enabled', 0);
// you will get this username and pass while register
define ('USERNAME', 'Username');
define ('PASSWORD', 'Password');
// SOAP WSDL endpoint
define ('ENDPOINT', 'https://api.livedocx.com/2.1/mailmerge.asmx?wsdl');
// Define timezone
date_default_timezone_set('Europe/Berlin');
$soap = new SoapClient(ENDPOINT);
$soap->LogIn(
array(
'username' => USERNAME,
'password' => PASSWORD
)
);
$data = file_get_contents('test.doc');
$soap->SetLocalTemplate(
array(
'template' => base64_encode($data),
'format' => 'doc'
)
);
$soap->CreateDocument();
$result = $soap->RetrieveDocument(
array(
'format' => 'pdf'
)
);
$data = $result->RetrieveDocumentResult;
file_put_contents('tree.pdf', base64_decode($data));
$soap->LogOut();
unset($soap);
Follow this link for more information http://www.phplivedocx.org/
OpenOffice and Unoconv installation Required.
from command prompt
apt-get remove --purge unoconv
git clone https://github.com/dagwieers/unoconv
cd unoconv
sudo make install
Now add below code in your PHP script and make sure file should be executable.
shell_exec('/usr/bin/unoconv -f pdf folder/test.docx');
shell_exec('/usr/bin/unoconv -f pdf folder/sachin.png');
Hope this solution help you.
You could use the following:
$file = 'http://mysite.co.za/images/favicon.ico';
$file_exists = (@fopen($file, "r")) ? true : false;
Worked for me when trying to check if an image exists on the URL
$(document).ready(function () {
$("#divId").toggleClass('cssclassname'); // toggle class
});
**OR**
$(document).ready(function() {
$("#objectId").click(function() { // click or other event to change the div class
$("#divId").toggleClass("cssclassname"); // toggle class
)};
)};
If you're using C#, it would be driver.Displayed. Here's an example from my own project:
if (!driver.FindElement(By.Name("newtagfield")).Displayed) //if the tag options is not displayed
driver.FindElement(By.Id("expand-folder-tags")).Click(); //make sure the folder and tags options are visible
As per: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
9.2 OPTIONS
The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
Responses to this method are not cacheable.
If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body.
If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).
If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.
A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of "0".
The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a Max-Forwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.
9.4 HEAD
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.
Here is my understanding of interface advantage. Correct me if I am wrong. Imagine we are developing OS and other team is developing the drivers for some devices. So we have developed an interface StorageDevice. We have two implementations of it (FDD and HDD) provided by other developers team.
Then we have a OperatingSystem class which can call interface methods such as saveData by just passing an instance of class implemented the StorageDevice interface.
The advantage here is that we don't care about the implementation of the interface. The other team will do the job by implementing the StorageDevice interface.
package mypack;
interface StorageDevice {
void saveData (String data);
}
class FDD implements StorageDevice {
public void saveData (String data) {
System.out.println("Save to floppy drive! Data: "+data);
}
}
class HDD implements StorageDevice {
public void saveData (String data) {
System.out.println("Save to hard disk drive! Data: "+data);
}
}
class OperatingSystem {
public String name;
StorageDevice[] devices;
public OperatingSystem(String name, StorageDevice[] devices) {
this.name = name;
this.devices = devices.clone();
System.out.println("Running OS " + this.name);
System.out.println("List with storage devices available:");
for (StorageDevice s: devices) {
System.out.println(s);
}
}
public void saveSomeDataToStorageDevice (StorageDevice storage, String data) {
storage.saveData(data);
}
}
public class Main {
public static void main(String[] args) {
StorageDevice fdd0 = new FDD();
StorageDevice hdd0 = new HDD();
StorageDevice[] devs = {fdd0, hdd0};
OperatingSystem os = new OperatingSystem("Linux", devs);
os.saveSomeDataToStorageDevice(fdd0, "blah, blah, blah...");
}
}
From the comments of php's date()
manual page:
<?php $mysqltime = date ('Y-m-d H:i:s', $phptime); ?>
You had the 'Y' correct - that's a full year, but 'M' is a three character month, while 'm' is a two digit month. Same issue with 'D' instead of 'd'. 'G' is a 1 or 2 digit hour, where 'H' always has a leading 0 when needed.
For Notepad++ 5.9
I use:
import os
import sys
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
As aiham points out in a comment, you can define this function in a module and use it in different scripts.
Plain and simple on Windows platforms:
where java
Javascript can be used, as long as you grab whatever page you're after via a proxy on your domain:
<html>
<head>
<script src="/js/jquery-1.3.2.js"></script>
</head>
<body>
<script>
$.get("www.mydomain.com/?url=www.google.com", function(response) {
alert(response)
});
</script>
</body>
Since Join-Path can be piped a path value, you can pipe multiple Join-Path statements together:
Join-Path "C:" -ChildPath "Windows" | Join-Path -ChildPath "system32" | Join-Path -ChildPath "drivers"
It's not as terse as you would probably like it to be, but it's fully PowerShell and is relatively easy to read.
BeRecursive's answer is the one I used, so that we could standardize on Json.Net (we have MVC5 and WebApi 5 -- WebApi 5 already uses Json.Net), but I found an issue. When you have parameters in your route to which you're POSTing, MVC tries to call the model binder for the URI values, and this code will attempt to bind the posted JSON to those values.
Example:
[HttpPost]
[Route("Customer/{customerId:int}/Vehicle/{vehicleId:int}/Policy/Create"]
public async Task<JsonNetResult> Create(int customerId, int vehicleId, PolicyRequest policyRequest)
The BindModel
function gets called three times, bombing on the first, as it tries to bind the JSON to customerId
with the error: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.
I added this block of code to the top of BindModel
:
if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) {
return base.BindModel(controllerContext, bindingContext);
}
The ValueProvider, fortunately, has route values figured out by the time it gets to this method.
Reading and writing binary files is pretty much the same as any other file, the only difference is how you open it:
unsigned char buffer[10];
FILE *ptr;
ptr = fopen("test.bin","rb"); // r for read, b for binary
fread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer
You said you can read it, but it's not outputting correctly... keep in mind that when you "output" this data, you're not reading ASCII, so it's not like printing a string to the screen:
for(int i = 0; i<10; i++)
printf("%u ", buffer[i]); // prints a series of bytes
Writing to a file is pretty much the same, with the exception that you're using fwrite()
instead of fread()
:
FILE *write_ptr;
write_ptr = fopen("test.bin","wb"); // w for write, b for binary
fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer
Since we're talking Linux.. there's an easy way to do a sanity check. Install hexdump
on your system (if it's not already on there) and dump your file:
mike@mike-VirtualBox:~/C$ hexdump test.bin
0000000 457f 464c 0102 0001 0000 0000 0000 0000
0000010 0001 003e 0001 0000 0000 0000 0000 0000
...
Now compare that to your output:
mike@mike-VirtualBox:~/C$ ./a.out
127 69 76 70 2 1 1 0 0 0
hmm, maybe change the printf
to a %x
to make this a little clearer:
mike@mike-VirtualBox:~/C$ ./a.out
7F 45 4C 46 2 1 1 0 0 0
Hey, look! The data matches up now*. Awesome, we must be reading the binary file correctly!
*Note the bytes are just swapped on the output but that data is correct, you can adjust for this sort of thing
My solution that does not involve any other library and it works with diff > 24h
var momentInSeconds = moment.duration(n,'seconds')
console.log(("0" + Math.floor(momentInSeconds.asHours())).slice(-2) + ':' + ("0" + momentInSeconds.minutes()).slice(-2) + ':' + ("0" + momentInSeconds.seconds()).slice(-2))
I think you may need to stringify the data using JSON.stringify.
var data = JSON.stringify({
'StrContactDetails': Details,
'IsPrimary':true
});
$.ajax({
type: "POST",
url: @url.Action("Dhp","SaveEmergencyContact"),
data: data,
success: function(){},
contentType: 'application/json'
});
So the controller method would look like,
public ActionResult SaveEmergencyContact(string StrContactDetails, bool IsPrimary)
Here you can simply use:
SendKeys "{ENTER}"
at the end of code linked to the Username field.
And so you can skip pressing ENTER Key once (one time).
And as a result, the next button ("Log In" button here) will be activated. And when you press ENTER once (your desired outcome), It will run code which is linked with "Log In" button.
The short answer is that the syntax is this.dataset.whatever
.
Your code should look like this:
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset.uid, this.dataset.name, this.dataset.value)">
Another important note: Javascript will always strip out hyphens and make the data attributes camelCase, regardless of whatever capitalization you use. data-camelCase
will become this.dataset.camelcase
and data-Camel-case
will become this.dataset.camelCase
.
jQuery (after v1.5 and later) always uses lowercase, regardless of your capitalization.
So when referencing your data attributes using this method, remember the camelCase:
<div data-this-is-wild="yes, it's true"
onclick="fun(this.dataset.thisIsWild)">
Also, you don't need to use commas to separate attributes.
If you need more than 1 class
You can do this:
<i id="icon"
v-bind:class="{ 'fa fa-star': showStar }"
v-on:click="showStar = !showStar"
>
</i>
data: {
showStar: true
}
Notice the single quotes ' around the classes!
Thanks to everyone else's solutions.
var values = $("input[name='user_group']:checked").map(function(){
return $(this).val();
}).get();
This will give you all the values of the checked boxed in an array.
Java 8 added a new API for working with dates and times. With Java 8 you can use
import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();
Instant.now()
returns an Instant that represents the current system time. With getEpochSecond()
you get the epoch seconds (unix time) from the Instant
.
If you want to read a file line by line and writing this in another:
var fs = require('fs');
var readline = require('readline');
var Stream = require('stream');
function readFileLineByLine(inputFile, outputFile) {
var instream = fs.createReadStream(inputFile);
var outstream = new Stream();
outstream.readable = true;
outstream.writable = true;
var rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false
});
rl.on('line', function (line) {
fs.appendFileSync(outputFile, line + '\n');
});
};
Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.
It works too :
<form>
<label for="male"><input type="checkbox" name="male" id="male" />Male</label><br />
<label for="female"><input type="checkbox" name="female" id="female" />Female</label>
</form>
I'm assuming this is happening for an anonymous class. When you create an anonymous class you actually create a class that extends the class whose name you got.
The "cleaner" way to get the name you want is:
If your class is an anonymous inner class, getSuperClass()
should give you the class that it was created from. If you created it from an interface than you're sort of SOL because the best you can do is getInterfaces()
which might give you more than one interface.
The "hacky" way is to just get the name with getClassName()
and use a regex to drop the $1
.
Here's a decoration that lets you set a spacing between items as well as a spacing on the edges. This works for both HORIZONTAL
and VERTICAL
layouts.
class LinearSpacingDecoration(
@Px private val itemSpacing: Int,
@Px private val edgeSpacing: Int = 0
): RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val count = parent.adapter?.itemCount ?: 0
val position = parent.getChildAdapterPosition(view)
val leading = if (position == 0) edgeSpacing else itemSpacing
val trailing = if (position == count - 1) edgeSpacing else 0
outRect.run {
if ((parent.layoutManager as? LinearLayoutManager)?.orientation == LinearLayout.VERTICAL) {
top = leading
bottom = trailing
} else {
left = leading
right = trailing
}
}
}
}
Usage:
recyclerView.addItemDecoration(LinearSpacingDecoration(itemSpacing = 10, edgeSpacing = 20))
If you have password for your dB then
mysql -u <username> -p <DBName> < yourfile.sql
You can always abuse the fact that duplicated keys are overwritten. This is what I just wrote:
"dependencies": {
"grunt": "...",
"grunt-cli": "...",
"api-easy": "# Here is the pull request: https://github.com/...",
"api-easy": "git://..."
"grunt-vows": "...",
"vows": "..."
}
However, it is not clear whether JSON allows duplicated keys (see Does JSON syntax allow duplicate keys in an object?. It seems to work with npm, so I take the risk.
The recommened hack is to use "//"
keys (from the nodejs mailing list). When I tested it, it did not work with "dependencies" sections, though. Also, the example in the post uses multiple "//"
keys, which implies that npm does not reject JSON files with duplicated keys. In other words, the hack above should always be fine.
Update: One annoying disadvantage of the duplicated key hack is that npm install --save
silently eliminates all duplicates. Unfortunately, it is very easy to overlook it and your well-intentioned comments are gone.
The "//"
hack is still the safest as it seems. However, multi-line comments will be removed by npm install --save
, too.
You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.
But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:
preventDefault
method)First, you'll have to cancel the form submit action like so:
$("#myform").submit(function(event) {
// Cancels the form's submit action.
event.preventDefault();
});
And then, grab the value of the data. Let's just assume you have one text box.
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
});
And then fire off a request. Let's just assume it's a POST request.
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
// I like to use defers :)
deferred = $.post("http://somewhere.com", { val: val });
deferred.success(function () {
// Do your stuff.
});
deferred.error(function () {
// Handle any errors here.
});
});
And this should about do it.
Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.
Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.
$.post("http://somewhere.com", { val: val }, function () {
// Start partying here.
}, function () {
// Handle the bad news here.
});
<asp:GridView ID="GridView1" AutoGenerateEditButton="True"
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" width="600px">
<Columns>
<asp:BoundField HeaderText="UserId"
DataField="UserId"
SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
</Columns>
</asp:GridView>
As alluded to in wickeD's answer, with replaceAll the replacement string is handled differently between replace and replaceAll. I expected a[3] and a[4] to have the same value, but they are different.
public static void main(String[] args) {
String[] a = new String[5];
a[0] = "\\";
a[1] = "X";
a[2] = a[0] + a[1];
a[3] = a[1].replaceAll("X", a[0] + "X");
a[4] = a[1].replace("X", a[0] + "X");
for (String s : a) {
System.out.println(s + "\t" + s.length());
}
}
The output of this is:
\ 1
X 1
\X 2
X 1
\X 2
This is different from perl where the replacement does not require the extra level of escaping:
#!/bin/perl
$esc = "\\";
$s = "X";
$s =~ s/X/${esc}X/;
print "$s " . length($s) . "\n";
which prints \X 2
This can be quite a nuisance, as when trying to use the value returned by java.sql.DatabaseMetaData.getSearchStringEscape() with replaceAll().
You can find an example below. Basically you attach a function to window
's scroll
event and trace scrollTop
property and if it's higher than desired threshold you apply position: fixed
and some other css properties.
jQuery(function($) {_x000D_
$(window).scroll(function fix_element() {_x000D_
$('#target').css(_x000D_
$(window).scrollTop() > 100_x000D_
? { 'position': 'fixed', 'top': '10px' }_x000D_
: { 'position': 'relative', 'top': 'auto' }_x000D_
);_x000D_
return fix_element;_x000D_
}());_x000D_
});
_x000D_
body {_x000D_
height: 2000px;_x000D_
padding-top: 100px;_x000D_
}_x000D_
code {_x000D_
padding: 5px;_x000D_
background: #efefef;_x000D_
}_x000D_
#target {_x000D_
color: #c00;_x000D_
font: 15px arial;_x000D_
padding: 10px;_x000D_
margin: 10px;_x000D_
border: 1px solid #c00;_x000D_
width: 200px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="target">This <code>div</code> is going to be fixed</div>
_x000D_
'Truncate tableName' will fail on a table with key constraint defined. It will also not reindex the table AUTO_INCREMENT
value. Instead, Delete all table entries and reset indexing back to 1 using this sql syntax:
DELETE FROM tableName;
ALTER TABLE tableName AUTO_INCREMENT = 1
You can use the -B
option.
-B, --block-size=SIZE use SIZE-byte blocks
All together,
df -BG
I had the same problem, I was trying to listen the change on some select and actually the problem was I was using the event instead of the event.target which is the select object.
INCORRECT :
$(document).on('change', $("select"), function(el) {
console.log($(el).val());
});
CORRECT :
$(document).on('change', $("select"), function(el) {
console.log($(el.target).val());
});
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
To get Incoming,Outgoing and Missed Call history , hope this code will help u:)
Call this code on your background thread.
StringBuffer sb = new StringBuffer();
String[] projection = new String[] {
CallLog.Calls.CACHED_NAME,
CallLog.Calls.NUMBER,
CallLog.Calls.TYPE,
CallLog.Calls.DATE,
CallLog.Calls.DURATION
};
sb.append("Call Details :");
// String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor managedCursor = getApplicationContext().getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, null);
while (managedCursor.moveToNext()) {
String name = managedCursor.getString(0); //name
String number = managedCursor.getString(1); // number
String type = managedCursor.getString(2); // type
String date = managedCursor.getString(3); // time
@SuppressLint("SimpleDateFormat")
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String dateString = formatter.format(new Date(Long.parseLong(date)));
String duration = managedCursor.getString(4); // duration
String dir = null;
int dircode = Integer.parseInt(type);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append("\nPhone Name :-- "+name+" Number:--- " + number + " \nCall Type:--- " + dir + " \nCall Date:--- " + dateString + " \nCall duration in sec :--- " + duration);
sb.append("\n----------------------------------");
You should not rely on instruments -s
. The officially supported tool for working with Simulators from the command line is xcrun simctl
.
The log directory for a device can be found with xcrun simctl getenv booted SIMULATOR_LOG_ROOT
. This will always be correct even if the location changes.
Now that things are moving to os_log
it is easier to open Console.app on the host Mac. Booted simulators should show up as a log source on the left, just like physical devices. You can also run log commands in the booted simulator:
# os_log equivalent of tail -f
xcrun simctl spawn booted log stream --level=debug
# filter log output
xcrun simctl spawn booted log stream --predicate 'processImagePath endswith "myapp"'
xcrun simctl spawn booted log stream --predicate 'eventMessage contains "error" and messageType == info'
# a log dump that Console.app can open
xcrun simctl spawn booted log collect
# open location where log collect will write the dump
cd `xcrun simctl getenv booted SIMULATOR_SHARED_RESOURCES_DIRECTORY`
If you want to use Safari Developer tools (including the JS console) with a webpage in the Simulator: Start one of the simulators, open Safari, then go to Safari on your mac and you should see Simulator in the menu.
You can open a URL in the Simulator by dragging it from the Safari address bar and dropping on the Simulator window. You can also use xcrun simctl openurl booted <url>
.
[Gray] introduced the ACD properties for a transaction in 1981. In 1983 [Haerder] added the Isolation property. In my opinion, the ACD properties would be have a more useful set of properties to discuss. One interpretation of Atomicity (that the transaction should be atomic as seen from any client any time) would actually imply the isolation property. The "isolation" property is useful when the transaction is not isolated; when the isolation property is relaxed. In ANSI SQL speak: if the isolation level is weaker then SERIALIZABLE. But when the isolation level is SERIALIZABLE, the isolation property is not really of interest.
I have written more about this in a blog post: "ACID Does Not Make Sense".
http://blog.franslundberg.com/2013/12/acid-does-not-make-sense.html
[Gray] The Transaction Concept, Jim Gray, 1981. http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
[Haerder] Principles of Transaction-Oriented Database Recovery, Haerder and Reuter, 1983. http://www.stanford.edu/class/cs340v/papers/recovery.pdf
I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...
Let's say the code looks like this:
$positions = $this->positions() || [];
You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.
If you need to get value of $this->positions() or empty array, you have to use:
$positions = $this->positions() or [];
EDIT:
The above example doesn't work as intended but the truth is that ||
and or
is not the same... Try this:
<?php
function returnEmpty()
{
//return "string";
//return [1];
return null;
}
$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];
var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";
This is the result:
bool(false)
NULL
array(0) {
}
So, actually the third option ?:
is the correct solution when you want to set returned value or empty array.
$positions = $this->positions() ?: [];
Tested with PHP 7.2.1
useful to windows users who use eclipse for c/c++ but run *.exe file and get an error: "missing libstdc++6.dll"
4 ways to solve it
Eclipse ->"Project" -> "Properties" -> "C/C++ Build" -> "Settings" -> "Tool Settings" -> "MinGW C++ Linker" -> "Misscellaneous" -> "Linker flags" (add '-static' to it)
Add '{{the path where your MinGW was installed}}/bin' to current user environment variable - "Path" in Windows, then reboot eclipse, and finally recompile.
Add '{{the path where your MinGW was installed}}/bin' to Windows environment variable - "Path", then reboot eclipse, and finally recompile.
Copy the file "libstdc++-6.dll" to the path where the *.exe file is running, then rerun. (this is not a good way)
Note: the file "libstdc++-6.dll" is in the folder '{{the path where your MinGW was installed}}/bin'
Try This
<button class="click_on_enterkey" type="button" onclick="return false;">
<script>
$('.click_on_enterkey').on('keyup',function(event){
if(event.keyCode == 13){
$(this).click();
}
});
<script>
There are actually multiple solutions, depending on the scenario:
public static void runJustBeforeBeingDrawn(final View view, final Runnable runnable) { final OnPreDrawListener preDrawListener = new OnPreDrawListener() { @Override public boolean onPreDraw() { view.getViewTreeObserver().removeOnPreDrawListener(this); runnable.run(); return true; } }; view.getViewTreeObserver().addOnPreDrawListener(preDrawListener); }
Sample usage:
ViewUtil.runJustBeforeBeingDrawn(yourView, new Runnable() {
@Override
public void run() {
//Here you can safely get the view size (use "getWidth" and "getHeight"), and do whatever you wish with it
}
});
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int width=view.getMeasuredWidth(); int height=view.getMeasuredHeight();
If you know the size of the container:
val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxWidth, View.MeasureSpec.AT_MOST)
val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.AT_MOST)
view.measure(widthMeasureSpec, heightMeasureSpec)
val width=view.measuredWidth
val height=view.measuredHeight
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { final int newHeight= MeasureSpec.getSize(heightMeasureSpec); final int newWidth= MeasureSpec.getSize(widthMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
If you write in Kotlin, you can use the next function, which behind the scenes works exactly like runJustBeforeBeingDrawn
that I've written:
view.doOnPreDraw { actionToBeTriggered() }
Note that you need to add this to gradle (found via here) :
android {
kotlinOptions {
jvmTarget = "1.8"
}
}
implementation 'androidx.core:core-ktx:#.#'
Simply use CSS padding rules with table data:
td {
padding: 20px;
}
And for border spacing:
table {
border-spacing: 1px;
border-collapse: collapse;
}
However, it can create problems in older version of browsers like Internet Explorer because of the diff implementation of the box model.
In Python, "privacy" depends on "consenting adults'" levels of agreement - you can't force it (any more than you can in real life;-). A single leading underscore means you're not supposed to access it "from the outside" -- two leading underscores (w/o trailing underscores) carry the message even more forcefully... but, in the end, it still depends on social convention and consensus: Python's introspection is forceful enough that you can't handcuff every other programmer in the world to respect your wishes.
((Btw, though it's a closely held secret, much the same holds for C++: with most compilers, a simple #define private public
line before #include
ing your .h
file is all it takes for wily coders to make hash of your "privacy"...!-))
Here is a work around I found if you want to only shuffle a subset of the DataFrame:
shuffle_to_index = 20
df = pd.concat([df.iloc[np.random.permutation(range(shuffle_to_index))], df.iloc[shuffle_to_index:]])
You can at least stop the the non-tech savvy people from using the right-click context menu to download your video. You can disable the context menu for any element using the oncontextmenu attribute.
oncontextmenu="return false;"
This works for the body element (whole page) or just a single video using it inside the video tag.
<video oncontextmenu="return false;" controls>...</video>
Yes, you can assign one instance of a struct to another using a simple assignment statement.
In the case of non-pointer or non pointer containing struct members, assignment means copy.
In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.
Let us see this first hand:
#include <stdio.h>
struct Test{
int foo;
char *bar;
};
int main(){
struct Test t1;
struct Test t2;
t1.foo = 1;
t1.bar = malloc(100 * sizeof(char));
strcpy(t1.bar, "t1 bar value");
t2.foo = 2;
t2.bar = malloc(100 * sizeof(char));
strcpy(t2.bar, "t2 bar value");
printf("t2 foo and bar before copy: %d %s\n", t2.foo, t2.bar);
t2 = t1;// <---- ASSIGNMENT
printf("t2 foo and bar after copy: %d %s\n", t2.foo, t2.bar);
//The following 3 lines of code demonstrate that foo is deep copied and bar is shallow copied
strcpy(t1.bar, "t1 bar value changed");
t1.foo = 3;
printf("t2 foo and bar after t1 is altered: %d %s\n", t2.foo, t2.bar);
return 0;
}
LinqToSql will automatically convert a .Skip(N1).Take(N2) into the TSQL syntax for you. In fact, every "query" you do in Linq, is actually just creating a SQL query for you in the background. To test this, just run SQL Profiler while your application is running.
The skip/take methodology has worked very well for me, and others from what I read.
Out of curiosity, what type of self-paging query do you have, that you believe is more efficient than Linq's skip/take?
$("#MyTableData").on({
mouseenter: function(){
//stuff to do on mouse enter
$(this).css({'color':'red'});
},
mouseleave: function () {
//stuff to do on mouse leave
$(this).css({'color':'blue'});
}},'tr');
I admit that my approach escapes the whole "Code First" concept. But if you have the ability to just change the default value in the table itself... it's much simpler than the lengths that you have to go through above... I'm just too lazy to do all that work!
It almost seems as if the posters original idea would work:
[DefaultValue(true)]
public bool IsAdmin { get; set; }
I thought they just made the mistake of adding quotes... but alas no such intuitiveness. The other suggestions were just too much for me (granted I have the privileges needed to go into the table and make the changes... where not every developer will in every situation). In the end I just did it the old fashioned way. I set the default value in the SQL Server table... I mean really, enough already! NOTE: I further tested doing an add-migration and update-database and the changes stuck.
You can try calling this method in you program:
static double string_double(string s)
{
double temp = 0;
double dtemp = 0;
int b = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '.')
{
i++;
while (i < s.Length)
{
dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
i++;
b++;
}
temp = temp + (dtemp * Math.Pow(10, -b));
return temp;
}
else
{
temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
}
}
return -1; //if somehow failed
}
Example:
string s = "12.3";
double d = string_double (s); //d = 12.3
For me, this error was caused by just unused import:
import { NgModule, Input } from '@angular/core';
Resulting error:
Input is declared, but it's value never read
Comment it out, and error doesn't occur:
import { NgModule/*, Input*/ } from '@angular/core';
Try this :
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys("[email protected]");
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.