Here is one equivalent of the accepted answer for the UTF-8 world.
if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
//Disallowed Character In $string
}
Explanation:
Note, that if the hyphen is the last character in the class definition it does not need to be escaped. If the dash appears elsewhere in the class definition it needs to be escaped, as it will be seen as a range character rather then a hyphen.
If what you are trying to do is to split a string into several lines, you can use a backslash:
$ a="hello\
> world"
$ echo $a
helloworld
With one space in between:
$ a="hello \
> world"
$ echo $a
hello world
This one also adds only one space in between:
$ a="hello \
> world"
$ echo $a
hello world
The practical way is setting font-family
to a value that is the specific name of the semibold version, such as
font-family: "Myriad pro Semibold"
if that’s the name. (Personally I use my own font listing tool, which runs on Internet Explorer only to see the fonts in my system by names as usable in CSS.)
In this approach, font-weight
is not needed (and probably better not set).
Web browsers have been poor at implementing font weights by the book: they largely cannot find the specific weight version, except bold. The workaround is to include the information in the font family name, even though this is not how things are supposed to work.
Testing with Segoe UI, which often exists in different font weight versions on Windows systems, I was able to make Internet Explorer 9 select the proper version when using the logical approach (of using the font family name Segoe UI and different font-weight
values), but it failed on Firefox 9 and Chrome 16 (only normal and bold work). On all of these browsers, for example, setting font-family: Segoe UI Light
works OK.
Since Gson 2.8
, we can create util function like
public <T> List<T> getList(String jsonArray, Class<T> clazz) {
Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
return new Gson().fromJson(jsonArray, typeOfT);
}
Example using
String jsonArray = ...
List<User> user = getList(jsonArray, User.class);
If you're using autolayout in iOS 6+, you can do this by adjusting the intrinsicContentSize
in a subclass of UILabel
.
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.textAlignment = NSTextAlignmentRight;
}
return self;
}
- (CGSize)intrinsicContentSize
{
CGSize size = [super intrinsicContentSize];
return CGSizeMake(size.width + 10.0, size.height);
}
The PATCH
method is the correct choice here as you're updating an existing resource - the group ID. PUT
should only be used if you're replacing a resource in its entirety.
Further information on partial resource modification is available in RFC 5789. Specifically, the PUT
method is described as follows:
Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.
There is nothing wrong with syntax of
$('#part' + number).html(text);
jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.
In your case you should pass a String to $()
that is
$(<a string>)
Make sure you have access to the variables number
and text
.
To test do:
function(){
alert(number + ":" + text);//or use console.log(number + ":" + text)
$('#part' + number).html(text);
});
If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.
Try this it may help you:
public void ButtonClick(View view) {
Fragment mFragment = new YourNextFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
}
private static bool CompareDictionaries(IDictionary<string, IEnumerable<string>> dict1, IDictionary<string, IEnumerable<string>> dict2)
{
if (dict1.Count != dict2.Count)
{
return false;
}
var keyDiff = dict1.Keys.Except(dict2.Keys);
if (keyDiff.Any())
{
return false;
}
return (from key in dict1.Keys
let value1 = dict1[key]
let value2 = dict2[key]
select value1.Except(value2)).All(diffInValues => !diffInValues.Any());
}
The python error says that wordInput
is not an iterable -> it is of NoneType.
If you print wordInput
before the offending line, you will see that wordInput
is None
.
Since wordInput
is None
, that means that the argument passed to the function is also None
. In this case word
. You assign the result of pickEasy
to word
.
The problem is that your pickEasy
function does not return anything. In Python, a method that didn't return anything returns a NoneType.
I think you wanted to return a word
, so this will suffice:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
This one is simplier :)
dataview dataview1;
this.dataview1= dataset.tables[0].defaultview;
this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC";
this.datagridview.datasource = dataview1;
Alternatively you could use minio-js client library get-object.js
var Minio = require('minio')
var s3Client = new Minio({
endPoint: 's3.amazonaws.com',
accessKey: 'YOUR-ACCESSKEYID',
secretKey: 'YOUR-SECRETACCESSKEY'
})
var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
if (e) {
return console.log(e)
}
dataStream.on('data', function(chunk) {
size += chunk.length
})
dataStream.on('end', function() {
console.log("End. Total size = " + size)
})
dataStream.on('error', function(e) {
console.log(e)
})
})
Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.
First, I see you're using an explicit $.parseJSON()
. If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.
To iterate through the first item in the array you've got there, use code like this:
var firstItem = response.d[0];
for(key in firstItem) {
console.log(key + ':' + firstItem[key]);
}
If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d
and then use this code inside that outer loop.
For angular6+
this.shirtCollection = afs.collection<Shirt>('shirts');
this.shirts = this.shirtCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
This worked for me (Select2 4.0.4):
$(document).on('change', 'select#your_id', function(e) {
// your code
console.log('this.value', this.value);
});
Multiple text-shadows..
Something like this:
var steps = 10,
i,
R = 0.6,
x,
y,
theStyle = '1vw 1vw 3vw #005dab';
for (i = -steps; i <= steps; i += 1) {
x = (i / steps) / 2;
y = Math.sqrt(Math.pow(R, 2) - Math.pow(x, 2));
theStyle = theStyle + ',' + x.toString() + 'vw ' + y.toString() + 'vw 0 #005dab';
theStyle = theStyle + ',' + x.toString() + 'vw -' + y.toString() + 'vw 0 #005dab';
theStyle = theStyle + ',' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
theStyle = theStyle + ',-' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
}
document.getElementsByTagName("H1")[0].setAttribute("style", "text-shadow:" + theStyle);
I had an issue where one of the nested dependency had an npm audit vulnerability, but I still wanted to maintain the parent dependency version. the npm shrinkwrap solution didn't work for me, so what I did to override the nested dependency version:
For OS X users (Mojave 10.14.3)
Here is what i use in my Bash script to test if Docker is running or not
# Check if docker is running
if ! docker info >/dev/null 2>&1; then
echo "Docker does not seem to be running, run it first and retry"
exit 1
fi
You can just use the -R (recursive) flag.
chmod -R 777 /Users/Test/Desktop/PATH
Extending on the answers, this is what worked for me, maybe someone will find it useful.
Html
<form method="post" action="/url" id="editMeta">
<textarea class="form-control" onkeypress="submitOnEnter(event)"></textarea>
</form>
Js
function submitOnEnter(e) {
if (e.which == 13) {
document.getElementById("editMeta").submit()
}
}
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable
has some columns first...
Introduced in ECMAScript 6, we can now deal with undefined
in a new way using Proxies. It can be used to set a default value to any properties which doesn't exist so that we don't have to check each time whether it actually exists.
var handler = {
get: function(target, name) {
return name in target ? target[name] : 'N/A';
}
};
var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)
Will output the below text without getting any undefined.
Name: Kevin , Age: N/A , Gender: N/A
Here is an official answer to this:
If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.
Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.
You can configure Git to store your password for you. If you'd like to set that up, read all about setting up password caching.
[v setBackgroundColor ColorwithRed: Green: Blue: ];
Each elapsed event will fire in the same thread unless a previous Elapsed is still running.
So it handles the collision for you
try putting this in a console
static void Main(string[] args)
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
var timer = new Timer(1000);
timer.Elapsed += timer_Elapsed;
timer.Start();
Console.ReadLine();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Thread.Sleep(2000);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
you will get something like this
10
6
12
6
12
where 10 is the calling thread and 6 and 12 are firing from the bg elapsed event. If you remove the Thread.Sleep(2000); you will get something like this
10
6
6
6
6
Since there are no collisions.
But this still leaves u with a problem. if u are firing the event every 5 seconds and it takes 10 seconds to edit u need some locking to skip some edits.
I think you need some sort of regular expression matching (the following code is in Python 3):
import string
import re
import nltk
s = "I can't do this now, because I'm so tired. Please give me some time."
l = nltk.word_tokenize(s)
ll = [x for x in l if not re.fullmatch('[' + string.punctuation + ']+', x)]
print(l)
print(ll)
Output:
['I', 'ca', "n't", 'do', 'this', 'now', ',', 'because', 'I', "'m", 'so', 'tired', '.', 'Please', 'give', 'me', 'some', 'time', '.']
['I', 'ca', "n't", 'do', 'this', 'now', 'because', 'I', "'m", 'so', 'tired', 'Please', 'give', 'me', 'some', 'time']
Should work well in most cases since it removes punctuation while preserving tokens like "n't", which can't be obtained from regex tokenizers such as wordpunct_tokenize
.
We have multiple domains in our environment so I use preg_replace with regex to get just the username without DOMAIN\ .
preg_replace("/^.+\\\\/", "", $_SERVER["AUTH_USER"]);
Reading perlport I'd suggest something like
$line =~ s/\015?\012?$//;
to be safe for whatever platform you're on and whatever linefeed style you may be processing because what's in \r and \n may differ through different Perl flavours.
I think it's better to use the symmetric difference operation of sets to do that Here is the link to the doc.
>>> dict1 = {1:'donkey', 2:'chicken', 3:'dog'}
>>> dict2 = {1:'donkey', 2:'chimpansee', 4:'chicken'}
>>> set1 = set(dict1.items())
>>> set2 = set(dict2.items())
>>> set1 ^ set2
{(2, 'chimpansee'), (4, 'chicken'), (2, 'chicken'), (3, 'dog')}
It is symmetric because:
>>> set2 ^ set1
{(2, 'chimpansee'), (4, 'chicken'), (2, 'chicken'), (3, 'dog')}
This is not the case when using the difference operator.
>>> set1 - set2
{(2, 'chicken'), (3, 'dog')}
>>> set2 - set1
{(2, 'chimpansee'), (4, 'chicken')}
However it may not be a good idea to convert the resulting set to a dictionary because you may lose information:
>>> dict(set1 ^ set2)
{2: 'chicken', 3: 'dog', 4: 'chicken'}
From my Diceshaker application:
// Ensures the shake is strong enough on at least two axes before declaring it a shake.
// "Strong enough" means "greater than a client-supplied threshold" in G's.
static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
double
deltaX = fabs(last.x - current.x),
deltaY = fabs(last.y - current.y),
deltaZ = fabs(last.z - current.z);
return
(deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold);
}
@interface L0AppDelegate : NSObject <UIApplicationDelegate> {
BOOL histeresisExcited;
UIAcceleration* lastAcceleration;
}
@property(retain) UIAcceleration* lastAcceleration;
@end
@implementation L0AppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[UIAccelerometer sharedAccelerometer].delegate = self;
}
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
if (self.lastAcceleration) {
if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7)) {
histeresisExcited = YES;
/* SHAKE DETECTED. DO HERE WHAT YOU WANT. */
} else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2)) {
histeresisExcited = NO;
}
}
self.lastAcceleration = acceleration;
}
// and proper @synthesize and -dealloc boilerplate code
@end
The histeresis prevents the shake event from triggering multiple times until the user stops the shake.
playSound is a static method in your class, but you are referring to members like audioSounds
or minTime
which are not declared static
so they would require a SoundManager sm = new SoundManager();
to operate as sm.audioSounds
or sm.minTime
respectively
Solution:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
In 1.0, the functionality was bound to (
and tab
and shift-tab
, in 2.0 tab
was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab
. (
was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab
.
So press Shift-Tab
.
Not a direct answer to this question but rather to the "issue" of $event.currentTarget
apparently be set to null.
This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.
You can check this for more information: Consecutive calls to console.log produce inconsistent results
If you wish to have your config file on a different path you have to give your service a name:
mysqld --install NAME --defaults-file=C:\my-opts2.cnf
You can also use the name to install multiple mysql services listening on different sockets if you need that for some reason. You can see why it's failing by copying the execution path and adding --console to the end in the terminal. Finally, you can modify the starting path of a service by regediting:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\NAME
That works well but it isn't as useful because the windows service mechanism provides little logging capabilities.
1) First Insert JS file path in an index.html file :
<script src="assets/video.js" type="text/javascript"></script>
2) Import JS file and declare the variable in component.ts :
declare var RunPlayer: any;
NOTE: Variable name should be same as the name of a function in js file
3) Call the js method in the component
ngAfterViewInit(){
setTimeout(() => {
new RunPlayer();
});
}
I had different version of annotations jar. Changed all 3 jars to use SAME version of databind,annotations and core jackson jars
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
In my case alter column was not working so one can use 'Modify' command, like:
alter table [table_name] MODIFY column [column_name] varchar(1200);
If you want to get everything after |
excluding set character use this code.
[^|]*$
Others solutions \|.*$
Results : | mypcworld
This one [^|]*$
Results : mypcworld
To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.
Now, add the style to the div class and use the text-align property with center as its value.
See the below example.
<style>
.myDivElement{
text-align:center;
}
.myDivElement ul li{
display:inline;
}
</style>
<div class="myDivElement">
<ul>
<li>Home</li>
<li>About</li>
<li>Gallery</li>
<li>Contact</li>
</ul>
</div>
Here is the reference website Center Align Unordered List
1-liner, takes a XML string text
and YourType
as the expected object type. not very different from other answers, just compressed to 1 line:
var result = (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));
String
A String instance is immutable, that is, we cannot change it after it was created. If we perform any operation on a String it will return a new instance (creates a new instance in memory) instead of modifying the existing instance value.
StringBuilder
StringBuilder is mutable, that is, if we perform any operation on StringBuilder it will update the existing instance value and it will not create new instance.
I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...
def insert(string_s, insert_s, pos_i=0):
return string_s[:pos_i] + insert_s + string_s[pos_i:]
If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.
I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)
Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.
Open the command line (Start
-> Run
-> "cmd"
)
Go to the location of your setup.py file and run python setup.py build
Notes:
There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.
Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1
Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.
That's because there are no spaces in that long string so it has to break out of its container. Add word-break:break-all;
to your .title rules to force a break.
#calendar_container > #events_container > .event_block > .title {
width:400px;
font-size:12px;
word-break:break-all;
}
//Check if Safari
function isSafari() {
return /^((?!chrome).)*safari/i.test(navigator.userAgent);
}
//Check if MAC
if(navigator.userAgent.indexOf('Mac')>1){
alert(isSafari());
}
You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
You can confirm this by printing out the string to see that it turns out identical to the first case.
Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string
, which would make it look perhaps like this:
$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
mysql_real_escape_string($prefix));
$query = mysql_query($sql);
Note that inside the first argument of sprintf
the percent sign needs to be doubled to end up appearing once in the result.
<?php
if(isset($_GET['delete'])){
$delurl=$_GET['delete'];
unlink($delurl);
}
?>
<?php
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a href=\"$entry\">$entry</a> | <a href=\"?delete=$entry\">Delete</a><br>";
}
}
closedir($handle);
}
?>
This is It
Simply put, numpy.newaxis
is used to increase the dimension of the existing array by one more dimension, when used once. Thus,
1D array will become 2D array
2D array will become 3D array
3D array will become 4D array
4D array will become 5D array
and so on..
Here is a visual illustration which depicts promotion of 1D array to 2D arrays.
Scenario-1: np.newaxis
might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector, as depicted in the above picture.
Example:
# 1D array
In [7]: arr = np.arange(4)
In [8]: arr.shape
Out[8]: (4,)
# make it as row vector by inserting an axis along first dimension
In [9]: row_vec = arr[np.newaxis, :] # arr[None, :]
In [10]: row_vec.shape
Out[10]: (1, 4)
# make it as column vector by inserting an axis along second dimension
In [11]: col_vec = arr[:, np.newaxis] # arr[:, None]
In [12]: col_vec.shape
Out[12]: (4, 1)
Scenario-2: When we want to make use of numpy broadcasting as part of some operation, for instance while doing addition of some arrays.
Example:
Let's say you want to add the following two arrays:
x1 = np.array([1, 2, 3, 4, 5])
x2 = np.array([5, 4, 3])
If you try to add these just like that, NumPy will raise the following ValueError
:
ValueError: operands could not be broadcast together with shapes (5,) (3,)
In this situation, you can use np.newaxis
to increase the dimension of one of the arrays so that NumPy can broadcast.
In [2]: x1_new = x1[:, np.newaxis] # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
# [2],
# [3],
# [4],
# [5]])
Now, add:
In [3]: x1_new + x2
Out[3]:
array([[ 6, 5, 4],
[ 7, 6, 5],
[ 8, 7, 6],
[ 9, 8, 7],
[10, 9, 8]])
Alternatively, you can also add new axis to the array x2
:
In [6]: x2_new = x2[:, np.newaxis] # x2[:, None]
In [7]: x2_new # shape is (3, 1)
Out[7]:
array([[5],
[4],
[3]])
Now, add:
In [8]: x1 + x2_new
Out[8]:
array([[ 6, 7, 8, 9, 10],
[ 5, 6, 7, 8, 9],
[ 4, 5, 6, 7, 8]])
Note: Observe that we get the same result in both cases (but one being the transpose of the other).
Scenario-3: This is similar to scenario-1. But, you can use np.newaxis
more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).
Example:
In [124]: arr = np.arange(5*5).reshape(5,5)
In [125]: arr.shape
Out[125]: (5, 5)
# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis] # arr[None, ..., None, None]
In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)
As an alternative, you can use numpy.expand_dims
that has an intuitive axis
kwarg.
# adding new axes at 1st, 4th, and last dimension of the resulting array
In [131]: newaxes = (0, 3, -1)
In [132]: arr_5D = np.expand_dims(arr, axis=newaxes)
In [133]: arr_5D.shape
Out[133]: (1, 5, 5, 1, 1)
More background on np.newaxis vs np.reshape
newaxis
is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.
np.newaxis
uses the slicing operator to recreate the array while numpy.reshape
reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape
to happen).
Example
In [13]: A = np.ones((3,4,5,6))
In [14]: B = np.ones((4,6))
In [15]: (A + B[:, np.newaxis, :]).shape # B[:, None, :]
Out[15]: (3, 4, 5, 6)
In the above example, we inserted a temporary axis between the first and second axes of B
(to use broadcasting). A missing axis is filled-in here using np.newaxis
to make the broadcasting operation work.
General Tip: You can also use None
in place of np.newaxis
; These are in fact the same objects.
In [13]: np.newaxis is None
Out[13]: True
P.S. Also see this great answer: newaxis vs reshape to add dimensions
This is my code to add paddingRight and paddingBottom to a View to dodge the Navigation Bar. I combined some of the answers here and made a special clause for landscape orientation together with isInMultiWindowMode. The key is to read navigation_bar_height, but also check config_showNavigationBar to make sure we should actually use the height.
None of the previous solutions worked for me. As of Android 7.0 you have to take Multi Window Mode into consideration. This breaks the implementations comparing display.realSize with display.size since realSize gives you the dimensions of the whole screen (both split windows) and size only gives you the dimensions of your App window. Setting padding to this difference will leave your whole view being padding.
/** Adds padding to a view to dodge the navigation bar.
Unfortunately something like this needs to be done since there
are no attr or dimens value available to get the navigation bar
height (as of December 2016). */
public static void addNavigationBarPadding(Activity context, View v) {
Resources resources = context.getResources();
if (hasNavigationBar(resources)) {
int orientation = resources.getConfiguration().orientation;
int size = getNavigationBarSize(resources);
switch (orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N &&
context.isInMultiWindowMode()) { break; }
v.setPadding(v.getPaddingLeft(), v.getPaddingTop(),
v.getPaddingRight() + size, v.getPaddingBottom());
break;
case Configuration.ORIENTATION_PORTRAIT:
v.setPadding(v.getPaddingLeft(), v.getPaddingTop(),
v.getPaddingRight(), v.getPaddingBottom() + size);
break;
}
}
}
private static int getNavigationBarSize(Resources resources) {
int resourceId = resources.getIdentifier("navigation_bar_height",
"dimen", "android");
return resourceId > 0 ? resources.getDimensionPixelSize(resourceId) : 0;
}
private static boolean hasNavigationBar(Resources resources) {
int hasNavBarId = resources.getIdentifier("config_showNavigationBar",
"bool", "android");
return hasNavBarId > 0 && resources.getBoolean(hasNavBarId);
}
Nice! Very slick.
I was disappointed that Excel doesn't let us paste to a merged cell and also pastes results containing a break into successive rows below the "target" cell though, as that meant it simply doesn't work for me. I tried a few tweaks (unmerge/remerge, etc.) but then Excel dropped anything below a break, so that was a dead end.
Ultimately, I came up with a routine that'll handle simple tags and not use the "native" Unicode converter that is causing the issue with merged fields. Hope others find this useful:
Public Sub AddHTMLFormattedText(rngA As Range, strHTML As String, Optional blnShowBadHTMLWarning As Boolean = False)
' Adds converts text formatted with basic HTML tags to formatted text in an Excel cell
' NOTE: Font Sizes not handled perfectly per HTML standard, but I find this method more useful!
Dim strActualText As String, intSrcPos As Integer, intDestPos As Integer, intDestSrcEquiv() As Integer
Dim varyTags As Variant, varTag As Variant, varEndTag As Variant, blnTagMatch As Boolean
Dim intCtr As Integer
Dim intStartPos As Integer, intEndPos As Integer, intActualStartPos As Integer, intActualEndPos As Integer
Dim intFontSizeStartPos As Integer, intFontSizeEndPos As Integer, intFontSize As Integer
varyTags = Array("<b>", "</b>", "<i>", "</i>", "<u>", "</u>", "<sub>", "</sub>", "<sup>", "</sup>")
' Remove unhandled/unneeded tags, convert <br> and <p> tags to line feeds
strHTML = Trim(strHTML)
strHTML = Replace(strHTML, "<html>", "")
strHTML = Replace(strHTML, "</html>", "")
strHTML = Replace(strHTML, "<p>", "")
While LCase(Right$(strHTML, 4)) = "</p>" Or LCase(Right$(strHTML, 4)) = "<br>"
strHTML = Left$(strHTML, Len(strHTML) - 4)
strHTML = Trim(strHTML)
Wend
strHTML = Replace(strHTML, "<br>", vbLf)
strHTML = Replace(strHTML, "</p>", vbLf)
strHTML = Trim(strHTML)
ReDim intDestSrcEquiv(1 To Len(strHTML))
strActualText = ""
intSrcPos = 1
intDestPos = 1
Do While intSrcPos <= Len(strHTML)
blnTagMatch = False
For Each varTag In varyTags
If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
blnTagMatch = True
intSrcPos = intSrcPos + Len(varTag)
If intSrcPos > Len(strHTML) Then Exit Do
Exit For
End If
Next
If blnTagMatch = False Then
varTag = "<font size"
If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
blnTagMatch = True
intEndPos = InStr(intSrcPos, strHTML, ">")
intSrcPos = intEndPos + 1
If intSrcPos > Len(strHTML) Then Exit Do
Else
varTag = "</font>"
If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
blnTagMatch = True
intSrcPos = intSrcPos + Len(varTag)
If intSrcPos > Len(strHTML) Then Exit Do
End If
End If
End If
If blnTagMatch = False Then
strActualText = strActualText & Mid$(strHTML, intSrcPos, 1)
intDestSrcEquiv(intSrcPos) = intDestPos
intDestPos = intDestPos + 1
intSrcPos = intSrcPos + 1
End If
Loop
' Clear any bold/underline/italic/superscript/subscript formatting from cell
rngA.Font.Bold = False
rngA.Font.Underline = False
rngA.Font.Italic = False
rngA.Font.Subscript = False
rngA.Font.Superscript = False
rngA.Value = strActualText
' Now start applying Formats!"
' Start with Font Size first
intSrcPos = 1
intDestPos = 1
Do While intSrcPos <= Len(strHTML)
varTag = "<font size"
If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
intFontSizeStartPos = InStr(intSrcPos, strHTML, """") + 1
intFontSizeEndPos = InStr(intFontSizeStartPos, strHTML, """") - 1
If intFontSizeEndPos - intFontSizeStartPos <= 3 And intFontSizeEndPos - intFontSizeStartPos > 0 Then
Debug.Print Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
If Mid$(strHTML, intFontSizeStartPos, 1) = "+" Then
intFontSizeStartPos = intFontSizeStartPos + 1
intFontSize = 11 + 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
ElseIf Mid$(strHTML, intFontSizeStartPos, 1) = "-" Then
intFontSizeStartPos = intFontSizeStartPos + 1
intFontSize = 11 - 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
Else
intFontSize = Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
End If
Else
' Error!
GoTo HTML_Err
End If
intEndPos = InStr(intSrcPos, strHTML, ">")
intSrcPos = intEndPos + 1
intStartPos = intSrcPos
If intSrcPos > Len(strHTML) Then Exit Do
While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
intStartPos = intStartPos + 1
Wend
If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
varEndTag = "</font>"
intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
intEndPos = intEndPos - 1
Wend
If intEndPos > intSrcPos Then
intActualStartPos = intDestSrcEquiv(intStartPos)
intActualEndPos = intDestSrcEquiv(intEndPos)
rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1) _
.Font.Size = intFontSize
End If
End If
intSrcPos = intSrcPos + 1
Loop
'Now do remaining tags
intSrcPos = 1
intDestPos = 1
Do While intSrcPos <= Len(strHTML)
If intDestSrcEquiv(intSrcPos) = 0 Then
' This must be a Tag!
For intCtr = 0 To UBound(varyTags) Step 2
varTag = varyTags(intCtr)
intStartPos = intSrcPos + Len(varTag)
While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
intStartPos = intStartPos + 1
Wend
If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
varEndTag = varyTags(intCtr + 1)
intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
intEndPos = intEndPos - 1
Wend
If intEndPos > intSrcPos Then
intActualStartPos = intDestSrcEquiv(intStartPos)
intActualEndPos = intDestSrcEquiv(intEndPos)
With rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1).Font
If varTag = "<b>" Then
.Bold = True
ElseIf varTag = "<i>" Then
.Italic = True
ElseIf varTag = "<u>" Then
.Underline = True
ElseIf varTag = "<sup>" Then
.Superscript = True
ElseIf varTag = "<sub>" Then
.Subscript = True
End If
End With
End If
intSrcPos = intSrcPos + Len(varTag) - 1
Exit For
End If
Next
End If
intSrcPos = intSrcPos + 1
intDestPos = intDestPos + 1
Loop
Exit_Sub:
Exit Sub
HTML_Err:
' There was an error with the Tags. Show warning if requested.
If blnShowBadHTMLWarning Then
MsgBox "There was an error with the Tags in the HTML file. Could not apply formatting."
End If
End Sub
Note this doesn't care about tag nesting, instead only requiring a close tag for every open tag, and assuming the close tag nearest the opening tag applies to the opening tag. Properly nested tags will work fine, while improperly nested tags will not be rejected and may or may not work.
I would recommend using Glazed Lists for this. It makes it very easy to map a data structure to a table model.
To react to the mouseclick on the JTable, use an ActionListener: ActionListener on JLabel or JTable cell
{
InputStream is = HTTPClient.get(url);
InputStreamReader reader = new InputStreamReader(is);
JSONTokener tokenizer = new JSONTokener(reader);
JSONObject jsonObject = new JSONObject(tokenizer);
}
If it is a standalone (Main method) java project then Not any specific path put all the jars inside the project not any specific path then right click on the project - > export - > Runnable jar --> Select the lunch configuration and Library handeling then choose the radio button option "Package required libraries into generated jar" -- > Finish.
Or
If you have a web project then put all the jars in web-inf/lib folder and do the same step.
Don't forget SET SCHEMA 'myschema'
which you could use in a separate Statement
SET SCHEMA 'value' is an alias for SET search_path TO value. Only one schema can be specified using this syntax.
And since 9.4 and possibly earlier versions on the JDBC driver, there is support for the setSchema(String schemaName)
method.
Regardless of what OS you are running, look at the logs file of the "Makefile"
to see what is going on, instead of blindly installing stuff.
In my case, MAC OS, the log file is here:
/Users/za/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-15/2.3.0-static/pg-1.0.0/mkmf.log
The logs indicated that the make file could not be created because of the following:
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers
Inside the mkmf.log, you will see that it could not find required libraries, to finish the build.
checking for pg_config... no
Can't find the 'libpq-fe.h header
blah blah
After running "brew install postgresql"
, I can see all required libraries being there:
za:myapp za$ cat /Users/za/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-15/2.3.0-static/pg-1.0.0/mkmf.log | grep yes
find_executable: checking for pg_config... -------------------- yes
find_header: checking for libpq-fe.h... -------------------- yes
find_header: checking for libpq/libpq-fs.h... -------------------- yes
find_header: checking for pg_config_manual.h... -------------------- yes
have_library: checking for PQconnectdb() in -lpq... -------------------- yes
have_func: checking for PQsetSingleRowMode()... -------------------- yes
have_func: checking for PQconninfo()... -------------------- yes
have_func: checking for PQsslAttribute()... -------------------- yes
have_func: checking for PQencryptPasswordConn()... -------------------- yes
have_const: checking for PG_DIAG_TABLE_NAME in libpq-fe.h... -------------------- yes
have_header: checking for unistd.h... -------------------- yes
have_header: checking for inttypes.h... -------------------- yes
checking for C99 variable length arrays... -------------------- yes
You can use chsh to change a user's shell.
Run the following code, for instance, to change your shell to Zsh
chsh -s /bin/zsh
As described in the manpage, and by Lorin, if the shell is not known by the OS, you have to add it to its known list: /etc/shells
.
If anyone experiences the error for the same reason why I experience it, here's my solution:
if you had Html.AntiForgeryToken();
change it to @Html.AntiForgeryToken()
I believe you have to set the property relaxedUrlToFileSystemMapping in your web.config. Haack wrote an article about this a little while ago (and there are some other SO posts asking the same types of question)
<system.web>
<httpRuntime relaxedUrlToFileSystemMapping="true" />
Edit
From the comments below, later versions of .NET / IIS may require this to be in the system.WebServer
element.
<system.webServer>
<httpRuntime relaxedUrlToFileSystemMapping="true" />
The correct way to give spacing for tables is to use cellpadding and cellspacing e.g.
<table cellpadding="4">
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) {
was returning an invalid character error because it was trying to watch the value of attrs.dynamic
which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
Use the LEN
function:
Returns the number of characters of the specified string expression, excluding trailing blanks.
There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>
, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject
method that just makes a plain object
. You can then use reflection to get at the properties you need.
If your controller takes a FormCollection
, and you didn't add anything else to the data
the json should be in form[0]
:
public ActionResult Save(FormCollection forms) {
string json = forms[0];
// do your thing here.
}
Check if they're checked with the el.checked
attribute.
let radio1 = document.querySelector('.radio1');
let radio2 = document.querySelector('.radio2');
let output = document.querySelector('.output');
function update() {
if (radio1.checked) {
output.innerHTML = "radio1";
}
else {
output.innerHTML = "radio2";
}
}
update();
_x000D_
<div class="radios">
<input class="radio1" type="radio" name="radios" onchange="update()" checked>
<input class="radio2" type="radio" name="radios" onchange="update()">
</div>
<div class="output"></div>
_x000D_
In C++11, the using
keyword when used for type alias
is identical to typedef
.
7.1.3.2
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.
Bjarne Stroustrup provides a practical example:
typedef void (*PFD)(double); // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double); // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP
Pre-C++11, the using
keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):
class Derived : public Base {
public:
using Base::f; // lift Base's f into Derived's scope -- works in C++98
void f(char); // provide a new f
void f(int); // prefer this f to Base::f(int)
using Base::Base; // lift Base constructors Derived's scope -- C++11 only
Derived(char); // provide a new constructor
Derived(int); // prefer this constructor to Base::Base(int)
// ...
};
Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard
, Design decisions
, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.
Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.
First let’s consider a toy example:
template <typename T> class MyAlloc {/*...*/}; template <typename T, class A> class MyVector {/*...*/}; template <typename T> struct Vec { typedef MyVector<T, MyAlloc<T> > type; }; Vec<int>::type p; // sample usage
The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.
template <typename T> void foo (Vec<T>::type&);
So, the syntax is somewhat ugly. We would rather avoid the nested
::type
We’d prefer something like the following:template <typename T> using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below Vec<int> p; // sample usage
Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on
Vec<T>
in deducible context, and the syntax is improved as well. For example we could rewrite foo as:template <typename T> void foo (Vec<T>&);
We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to
foo(p)
will succeed.
The follow-up paper n1489 explains why using
instead of using typedef
:
It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:
template<class T> typedef std::vector<T, MyAllocator<T> > Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector< [bullet] , MyAllocator< [bullet] > >
– where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentencetemplate<class T> using Vec = std::vector<T, MyAllocator<T> >;
can be read/interpreted as: from now on, I’ll be using
Vec<T>
as a synonym forstd::vector<T, MyAllocator<T> >
. With that reading, the new syntax for aliasing seems reasonably logical.
I think the important distinction is made here, aliases instead of types. Another quote from the same document:
An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.
Summary, for the role of using
:
namespace PO = boost::program_options
and using PO = ...
equivalent)A typedef declaration can be viewed as a special case of non-template alias-declaration
. It's an aesthetic change, and is considered identical in this case.namespace std
into the global scope), member functions, inheriting constructorsIt cannot be used for:
int i;
using r = i; // compile-error
Instead do:
using r = decltype(i);
Naming a set of overloads.
// bring cos into scope
using std::cos;
// invalid syntax
using std::cos(double);
// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);
Rackspace maintains the ius repository, which contains a reasonably up-to-date git, but the stock git has to first be removed.
CentOS 6 or 7 instructions (run as root or with sudo):
# retrieve and check CENTOS_MAIN_VERSION (6 or 7):
CENTOS_MAIN_VERSION=$(cat /etc/centos-release | awk -F 'release[ ]*' '{print $2}' | awk -F '.' '{print $1}')
echo $CENTOS_MAIN_VERSION
# output should be "6" or "7"
# Install IUS Repo and Epel-Release:
yum install -y https://repo.ius.io/ius-release-el${CENTOS_MAIN_VERSION}.rpm
yum install -y epel-release
# re-install git:
yum erase -y git*
yum install -y git-core
# check version:
git --version
# output: git version 2.24.3
Note: git-all
instead of git-core
often installs an old version. Try e.g. git224-all
instead.
The script is tested on a CentOS 7 docker image (7e6257c9f8d8
) and on a CentOS 6 docker image (d0957ffdf8a2
).
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov
is the function you defined above.)
Try the following parameter:
-nc
,--no-clobber
: skip downloads that would download to existing files.
Sample usage:
wget -nc http://example.com/pic.png
Had the very same issue this week when I accidentally committed, then tried to remove a build file from a shared repository, and this:
http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html
has worked fine for me and not mentioned so far.
git update-index --assume-unchanged <file>
To remove the file you're interested in from version control, then use all your other commands as normal.
git update-index --no-assume-unchanged <file>
If you ever wanted to put it back in.
Edit: please see comments from Chris Johnsen and KPM, this only works locally and the file remains under version control for other users if they don't also do it. The accepted answer gives more complete/correct methods for dealing with this. Also some notes from the link if using this method:
Obviously there’s quite a few caveats that come into play with this. If you git add the file directly, it will be added to the index. Merging a commit with this flag on will cause the merge to fail gracefully so you can handle it manually.
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.
var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration - interval, 'milliseconds');
$('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);
Wrap your image with a span
element with a black background.
.img-wrapper {
display: inline-block;
background: #000;
}
.item-fade {
vertical-align: top;
transition: opacity 0.3s;
-webkit-transition: opacity 0.3s;
opacity: 1;
}
.item-fade:hover {
opacity: 0.2;
}
_x000D_
<span class="img-wrapper">
<img class="item-fade" src="http://placehold.it/100x100/cf5" />
</span>
_x000D_
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementById
because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
You would need to use append
or appendTo
or after
etc.. to put it in the dom first..
Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..
If you keep pointers in container and don't want to bother with manually destroying of them, then use boost shared_ptr. Here is sample for std::vector, but you can use it for any other STL container (set, map, queue, ...)
#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>
struct foo
{
foo( const int i_x ) : d_x( i_x )
{
std::cout << "foo::foo " << d_x << std::endl;
}
~foo()
{
std::cout << "foo::~foo " << d_x << std::endl;
}
int d_x;
};
typedef boost::shared_ptr< foo > smart_foo_t;
int main()
{
std::vector< smart_foo_t > foos;
for ( int i = 0; i < 10; ++i )
{
smart_foo_t f( new foo( i ) );
foos.push_back( f );
}
foos.clear();
return 0;
}
In my case everything was set up correctly but still the InfoPlist.strings file was not found.
The only thing that really worked was, to remove and add the InfoPlist.strings files again to the project.
List is an interface, and you can not initialize an interface. Instantiate an implementing class instead.
Like:
List<String> abc = new ArrayList<String>();
List<String> xyz = new LinkedList<String>();
Something like:
>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'
Just put the actual encoding you are using.
I had a similar issue after upgrading to a new swift version recently. Moving files around caused my xcode project to reference items that were no longer in the project directory giving me the Error Code Build Input File Not Found.
In my situation I somehow had multiple files/images that were being referenced as described below:
In the image above.
It was in here that I somehow had multiple files and images that were being referenced from other folders and the build would fail as they could no longer find them. And I could not find them either! or how Xcode was still referencing them
I hope this helps someone else !
Performance-wise it's the same as a named method. The big problem is when you do the following:
MyButton.Click -= (o, i) =>
{
//snip
}
It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.
This worked for me:
var new_number = float.toFixed(2);
Example:
var my_float = 0.6666
my_float.toFixed(3) # => 0.667
I just hide() the tinymce and submit form, the changed value of textarea missing. So I added this:
$("textarea[id='id_answer']").change(function(){
var editor_id = $(this).attr('id');
var editor = tinymce.get(editor_id);
editor.setContent($(this).val()).save();
});
It works for me.
After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..
Remove all listeners in element by one js line:
element.parentNode.innerHTML += '';
You can specify multiple patterns in an array.
select-string VendorEnquiry,Failed C:\Logs
This works with -notmatch as well:
select-string -notmatch VendorEnquiry,Failed C:\Logs
For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,
as a reference of available options see sprintf
#include <stdio.h>
int main ()
{
unsigned long lval = 123;
char buffer [50];
sprintf (buffer, "%lu" , lval );
}
There is the solution with Kotlin :
given(myObject.myCall()).willAnswer {
throw IOException("Ooops")
}
Where given comes from
import org.mockito.BDDMockito.given
Perhaps the simplest way to solve this (that will work) is:
CREATE new_table AS SELECT id, col1, col2, ... (only the columns you actually want in the final table) FROM my_table;
RENAME my_table TO old_table, new_table TO my_table;
DROP old_table;
Or keep old_table for a rollback if needed.
This will work but foreign keys will not be moved. You would have to re-add them to my_table later; also foreign keys in other tables that reference my_table will have to be fixed (pointed to the new my_table).
Good Luck...
$('#baba').prop('selectedIndex',-1);
While it seems @Miguel A. Arilla has pointed it out clearly and I voted up for him, I created on top of his useful solution another solution which looks neat but requires a lot more work.
It definitely depends on the above solution. So basically I created something similar to Func<string, IService>>
and I called it IServiceAccessor
as an interface and then I had to add a some more extensions to the IServiceCollection
as such:
public static IServiceCollection AddSingleton<TService, TImplementation, TServiceAccessor>(
this IServiceCollection services,
string instanceName
)
where TService : class
where TImplementation : class, TService
where TServiceAccessor : class, IServiceAccessor<TService>
{
services.AddSingleton<TService, TImplementation>();
services.AddSingleton<TServiceAccessor>();
var provider = services.BuildServiceProvider();
var implementationInstance = provider.GetServices<TService>().Last();
var accessor = provider.GetServices<TServiceAccessor>().First();
var serviceDescriptors = services.Where(d => d.ServiceType == typeof(TServiceAccessor));
while (serviceDescriptors.Any())
{
services.Remove(serviceDescriptors.First());
}
accessor.SetService(implementationInstance, instanceName);
services.AddSingleton<TServiceAccessor>(prvd => accessor);
return services;
}
The service Accessor looks like:
public interface IServiceAccessor<TService>
{
void Register(TService service,string name);
TService Resolve(string name);
}
The end result,you will be able to register services with names or named instances like we used to do with other containers..for instance:
services.AddSingleton<IEncryptionService, SymmetricEncryptionService, EncyptionServiceAccessor>("Symmetric");
services.AddSingleton<IEncryptionService, AsymmetricEncryptionService, EncyptionServiceAccessor>("Asymmetric");
That is enough for now, but to make your work complete, it is better to add more extension methods as you can to cover all types of registrations following the same approach.
There was another post on stackoverflow, but I can not find it, where the poster has explained in details why this feature is not supported and how to work around it, basically similar to what @Miguel stated. It was nice post even though I do not agree with each point because I think there are situation where you really need named instances. I will post that link here once I find it again.
As a matter of fact, you do not need to pass that Selector or Accessor:
I am using the following code in my project and it worked well so far.
/// <summary>
/// Adds the singleton.
/// </summary>
/// <typeparam name="TService">The type of the t service.</typeparam>
/// <typeparam name="TImplementation">The type of the t implementation.</typeparam>
/// <param name="services">The services.</param>
/// <param name="instanceName">Name of the instance.</param>
/// <returns>IServiceCollection.</returns>
public static IServiceCollection AddSingleton<TService, TImplementation>(
this IServiceCollection services,
string instanceName
)
where TService : class
where TImplementation : class, TService
{
var provider = services.BuildServiceProvider();
var implementationInstance = provider.GetServices<TService>().LastOrDefault();
if (implementationInstance.IsNull())
{
services.AddSingleton<TService, TImplementation>();
provider = services.BuildServiceProvider();
implementationInstance = provider.GetServices<TService>().Single();
}
return services.RegisterInternal(instanceName, provider, implementationInstance);
}
private static IServiceCollection RegisterInternal<TService>(this IServiceCollection services,
string instanceName, ServiceProvider provider, TService implementationInstance)
where TService : class
{
var accessor = provider.GetServices<IServiceAccessor<TService>>().LastOrDefault();
if (accessor.IsNull())
{
services.AddSingleton<ServiceAccessor<TService>>();
provider = services.BuildServiceProvider();
accessor = provider.GetServices<ServiceAccessor<TService>>().Single();
}
else
{
var serviceDescriptors = services.Where(d => d.ServiceType == typeof(IServiceAccessor<TService>));
while (serviceDescriptors.Any())
{
services.Remove(serviceDescriptors.First());
}
}
accessor.Register(implementationInstance, instanceName);
services.AddSingleton<TService>(prvd => implementationInstance);
services.AddSingleton<IServiceAccessor<TService>>(prvd => accessor);
return services;
}
//
// Summary:
// Adds a singleton service of the type specified in TService with an instance specified
// in implementationInstance to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection.
//
// Parameters:
// services:
// The Microsoft.Extensions.DependencyInjection.IServiceCollection to add the service
// to.
// implementationInstance:
// The instance of the service.
// instanceName:
// The name of the instance.
//
// Returns:
// A reference to this instance after the operation has completed.
public static IServiceCollection AddSingleton<TService>(
this IServiceCollection services,
TService implementationInstance,
string instanceName) where TService : class
{
var provider = services.BuildServiceProvider();
return RegisterInternal(services, instanceName, provider, implementationInstance);
}
/// <summary>
/// Registers an interface for a class
/// </summary>
/// <typeparam name="TInterface">The type of the t interface.</typeparam>
/// <param name="services">The services.</param>
/// <returns>IServiceCollection.</returns>
public static IServiceCollection As<TInterface>(this IServiceCollection services)
where TInterface : class
{
var descriptor = services.Where(d => d.ServiceType.GetInterface(typeof(TInterface).Name) != null).FirstOrDefault();
if (descriptor.IsNotNull())
{
var provider = services.BuildServiceProvider();
var implementationInstance = (TInterface)provider?.GetServices(descriptor?.ServiceType)?.Last();
services?.AddSingleton(implementationInstance);
}
return services;
}
You can export the secret keys to as environment variables on the ~/.bashrc
or ~/.bash_profile
of your server:
export SECRET_KEY_BASE = "YOUR_SECRET_KEY"
And then, you can source your .bashrc
or .bash_profile
:
source ~/.bashrc
source ~/.bash_profile
Never commit your secrets.yml
In order to get rid of duplicates, you can group by drinks.id
. But that way you'll get only one photo for each drinks.id
(which photo you'll get depends on database internal implementation).
Though it is not documented, in case of MySQL, you'll get the photo with lowest id
(in my experience I've never seen other behavior).
SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks.id
You can commit in the current branch, checkout to another branch, and finally cherry-pick that commit (in lieu of merge).
If $_SERVER['HTTP_REFERER']
variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.
It's better to use the actual (msi) installer from nodejs.org instead of downloading the node executable only. The installer includes npm and makes it easier to manage your node installation. There is an installer for both 32-bit and 64-bit Windows.
Also a couple of other tidbits:
Installing modules globally doesn't do what you might expect. The only modules you should install globally (the -g
flag in npm) are ones that install commands. So to install Express you would just do npm install express
and that will install Express to your current working directory. If you were instead looking for the Express project generator (command), you need to do npm install -g express-generator
for Express 4.
You can use node anywhere from your command prompt to execute scripts. For example if you have already written a separate script: node foo.js
. Or you can open up the REPL (as you've already found out) by just selecting the node.js (start menu) shortcut or by just typing node
in a command prompt.
I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.
You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.
The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.
This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.
You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder
The only restrictions/limitations:
IEDriverServer.exe
- should be downloaded separately and placed near SwdPageRecorder.exe
Use Timer for every second...
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//your method
}
}, 0, 1000);//put here time 1000 milliseconds=1 second
Given three tasks - FeedCat()
, SellHouse()
and BuyCar()
, there are two interesting cases: either they all complete synchronously (for some reason, perhaps caching or an error), or they don't.
Let's say we have, from the question:
Task<string> DoTheThings() {
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
// what here?
}
Now, a simple approach would be:
Task.WhenAll(x, y, z);
but ... that isn't convenient for processing the results; we'd typically want to await
that:
async Task<string> DoTheThings() {
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
await Task.WhenAll(x, y, z);
// presumably we want to do something with the results...
return DoWhatever(x.Result, y.Result, z.Result);
}
but this does lots of overhead and allocates various arrays (including the params Task[]
array) and lists (internally). It works, but it isn't great IMO. In many ways it is simpler to use an async
operation and just await
each in turn:
async Task<string> DoTheThings() {
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
// do something with the results...
return DoWhatever(await x, await y, await z);
}
Contrary to some of the comments above, using await
instead of Task.WhenAll
makes no difference to how the tasks run (concurrently, sequentially, etc). At the highest level, Task.WhenAll
predates good compiler support for async
/await
, and was useful when those things didn't exist. It is also useful when you have an arbitrary array of tasks, rather than 3 discreet tasks.
But: we still have the problem that async
/await
generates a lot of compiler noise for the continuation. If it is likely that the tasks might actually complete synchronously, then we can optimize this by building in a synchronous path with an asynchronous fallback:
Task<string> DoTheThings() {
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
if(x.Status == TaskStatus.RanToCompletion &&
y.Status == TaskStatus.RanToCompletion &&
z.Status == TaskStatus.RanToCompletion)
return Task.FromResult(
DoWhatever(a.Result, b.Result, c.Result));
// we can safely access .Result, as they are known
// to be ran-to-completion
return Awaited(x, y, z);
}
async Task Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
return DoWhatever(await x, await y, await z);
}
This "sync path with async fallback" approach is increasingly common especially in high performance code where synchronous completions are relatively frequent. Note it won't help at all if the completion is always genuinely asynchronous.
Additional things that apply here:
with recent C#, a common pattern is for the async
fallback method is commonly implemented as a local function:
Task<string> DoTheThings() {
async Task<string> Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
return DoWhatever(await a, await b, await c);
}
Task<Cat> x = FeedCat();
Task<House> y = SellHouse();
Task<Tesla> z = BuyCar();
if(x.Status == TaskStatus.RanToCompletion &&
y.Status == TaskStatus.RanToCompletion &&
z.Status == TaskStatus.RanToCompletion)
return Task.FromResult(
DoWhatever(a.Result, b.Result, c.Result));
// we can safely access .Result, as they are known
// to be ran-to-completion
return Awaited(x, y, z);
}
prefer ValueTask<T>
to Task<T>
if there is a good chance of things ever completely synchronously with many different return values:
ValueTask<string> DoTheThings() {
async ValueTask<string> Awaited(ValueTask<Cat> a, Task<House> b, Task<Tesla> c) {
return DoWhatever(await a, await b, await c);
}
ValueTask<Cat> x = FeedCat();
ValueTask<House> y = SellHouse();
ValueTask<Tesla> z = BuyCar();
if(x.IsCompletedSuccessfully &&
y.IsCompletedSuccessfully &&
z.IsCompletedSuccessfully)
return new ValueTask<string>(
DoWhatever(a.Result, b.Result, c.Result));
// we can safely access .Result, as they are known
// to be ran-to-completion
return Awaited(x, y, z);
}
if possible, prefer IsCompletedSuccessfully
to Status == TaskStatus.RanToCompletion
; this now exists in .NET Core for Task
, and everywhere for ValueTask<T>
This does it simply:
select t2.id,t2.record_date,t2.other_cols
from (select ROW_NUMBER() over(partition by id order by record_date)as rownum,id,record_date,other_cols from MyTable)t2
where t2.rownum = 1
Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:
export function HelloChandu() {
}
export function HelloTester() {
}
Then import them like so:
import { HelloChandu } from './helpers'
or...
import functions from './helpers'
then
functions.HelloChandu
If you need to do it dynamically in the browser using javascript, here is an example...
<img id=graph alt=""
src="http://www.kitco.com/images/live/gold.gif"
/>
<script language="javascript" type="text/javascript">
var d = new Date();
document.getElementById("graph").src =
"http://www.kitco.com/images/live/gold.gif?ver=" +
d.getTime();
</script>
When the first characters in a script are #!
, that is called the shebang. If your file starts with
#!/path/to/something
the standard is to run something
and pass the rest of the file to that program as an input.
With that said, the difference between #!/bin/bash
, #!/bin/sh
, or even #!/bin/zsh
is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash
and sh
are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh
is a link to dash
, and on traditional Unix systems (Solaris, Irix, etc) bash
is usually a completely different program from sh
.
Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python
, #!/usr/bin/perl
, or even #!/usr/local/bin/my_own_scripting_language
.
<script type="text/javascript">
$(window).on('load',function(){
setTimeout(function(){ alert(" //show popup"); }, 5000);
});
</script>
In the header file
header file
#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef MAIN_FILE
int global;
#else
extern int global;
#endif
#endif
In the file with the file you want the global to live:
#define MAIN_FILE
#include "share.h"
In the other files that need the extern version:
#include "share.h"
Declare @fs_e int, @C_Tables CURSOR, @Table varchar(50)
SET @C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN @C_Tables
FETCH @C_Tables INTO @Table
SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
WHILE ( @fs_e <> -1)
BEGIN
exec('Select * from ' + @Table)
FETCH @C_Tables INTO @Table
SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
END
You can store your settings info as Strings
of XML in the Settings.Default
. Create some classes to store your configuration data and make sure they are [Serializable]
. Then, with the following helpers, you can serialize instances of these objects--or List<T>
(or arrays T[]
, etc.) of them--to String
. Store each of these various strings in its own respective Settings.Default
slot in your WPF application's Settings
.
To recover the objects the next time the app starts, read the Settings
string of interest and Deserialize
to the expected type T
(which this time must be explcitly specified as a type argument to Deserialize<T>
).
public static String Serialize<T>(T t)
{
using (StringWriter sw = new StringWriter())
using (XmlWriter xw = XmlWriter.Create(sw))
{
new XmlSerializer(typeof(T)).Serialize(xw, t);
return sw.GetStringBuilder().ToString();
}
}
public static T Deserialize<T>(String s_xml)
{
using (XmlReader xw = XmlReader.Create(new StringReader(s_xml)))
return (T)new XmlSerializer(typeof(T)).Deserialize(xw);
}
I'm writing this because I found the other answers hard to understand.
Essentially your JRE is not updated and/or Eclipse is not configured to use the most recent JRE.
On Windows, go to Control Panel -> Programs -> Java -> update and proceed to update java
or if you don't have Java, go to Oracle's website and download the most recent JRE.
Once this is done, go into eclipse, and under the project view, right click on your project, select Java Build Path, double click on JRE System Library, then Select Workspace Default JRE 14.1.
If a recent version of Java doesn't show up here, it probably isn't installed. Check you JRE(NOT JDK) version and make sure it's recent. If it is, try restarting the computer then trying this again.
To add the ; secure
suffix to the Set-Cookie
http header I simply used the <httpCookies>
element in the web.config:
<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>
IMHO much more handy than writing code as in the article of Anubhav Goyal.
See: http://msdn.microsoft.com/en-us/library/ms228262(v=vs.100).aspx
Set the class .fill
to height: 100%
.fill {
min-height: 100%;
height: 100%;
}
(I put a red background for #map
so you can see it takes up 100% height)
In addition to all the other answers, you could use switch
. But it does seem a bit long.
switch ($result->vocation) {
case 1:
echo 'Sorcerer';
break;
case 2:
echo 'Druid';
break;
case 3:
echo 'Paladin';
break;
case 4:
echo 'Knight';
break;
case 5:
echo 'Master Sorcerer';
break;
case 6:
echo 'Elder Druid';
break;
case 7:
echo 'Royal Paladin';
break;
default:
echo 'Elite Knight';
break;
}
Yes but its messy hacking the sun classes. There is a simpler way:
http://code.google.com/p/named-regexp/
named-regexp is a thin wrapper for the standard JDK regular expressions implementation, with the single purpose of handling named capturing groups in the .net style : (?...).
It can be used with Java 5 and 6 (generics are used).
Java 7 will handle named capturing groups , so this project is not meant to last.
Best way to parse Json to HashMap
public static HashMap<String, String> jsonToMap(JSONObject json) throws JSONException {
HashMap<String, String> map = new HashMap<>();
try {
Iterator<String> iterator = json.keys();
while (iterator.hasNext()) {
String key = iterator.next();
String value = json.getString(key);
map.put(key, value);
}
return map;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Try marginTop
in place of margin-top
, eg:
$("#ActionBox").css("marginTop", foo);
Use intersection
or intersection_update
intersection :
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
ans = sorted(set(a).intersection(set(xyz)))
intersection_update:
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
b = set(a)
b.intersection_update(xyz)
then b
is your answer
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
This is same code from user Tombart with stream flush and close to avoid incomplete temporary file content copy from jar resource and to have unique temp file names.
File file = null;
String resource = "/view/Trial_main.html" ;
URL res = getClass().getResource(resource);
if (res.toString().startsWith("jar:")) {
try {
InputStream input = getClass().getResourceAsStream(resource);
file = File.createTempFile(new Date().getTime()+"", ".html");
OutputStream out = new FileOutputStream(file);
int read;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
input.close();
file.deleteOnExit();
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
//this will probably work in your IDE, but not from a JAR
file = new File(res.getFile());
}
IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).
enum NSURLError: Int {
case unknown = -1
case cancelled = -999
case badURL = -1000
case timedOut = -1001
case unsupportedURL = -1002
case cannotFindHost = -1003
case cannotConnectToHost = -1004
case connectionLost = -1005
case lookupFailed = -1006
case HTTPTooManyRedirects = -1007
case resourceUnavailable = -1008
case notConnectedToInternet = -1009
case redirectToNonExistentLocation = -1010
case badServerResponse = -1011
case userCancelledAuthentication = -1012
case userAuthenticationRequired = -1013
case zeroByteResource = -1014
case cannotDecodeRawData = -1015
case cannotDecodeContentData = -1016
case cannotParseResponse = -1017
//case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
case fileDoesNotExist = -1100
case fileIsDirectory = -1101
case noPermissionsToReadFile = -1102
//case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103
// SSL errors
case secureConnectionFailed = -1200
case serverCertificateHasBadDate = -1201
case serverCertificateUntrusted = -1202
case serverCertificateHasUnknownRoot = -1203
case serverCertificateNotYetValid = -1204
case clientCertificateRejected = -1205
case clientCertificateRequired = -1206
case cannotLoadFromNetwork = -2000
// Download and file I/O errors
case cannotCreateFile = -3000
case cannotOpenFile = -3001
case cannotCloseFile = -3002
case cannotWriteToFile = -3003
case cannotRemoveFile = -3004
case cannotMoveFile = -3005
case downloadDecodingFailedMidStream = -3006
case downloadDecodingFailedToComplete = -3007
/*
case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018
case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019
case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020
case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021
case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
*/
}
Direct link to URLError.Code
in the Swift github repository, which contains the up to date list of error codes being used (github link).
this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.
for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.
PS: but like I said, this might be totally unrelated to your query :)
Indeed, you must initialize your array then right after that use array.push() command line.
var array = new Array();
array.push("first value");
array.push("second value");
I think you are trying to run some utility or shell script from UNIX\LINUX which has some GUI. Anyways
SOLUTION: dude all you need is an XServer & X11 forwarding enabled. I use XMing (XServer). You are already enabling X11 forwarding. Just Install it(XMing) and keep it running when you create the session with PuTTY.
adb logcat -c
Logcat options are documented here: http://developer.android.com/tools/help/logcat.html
To correctly save the instance state of Fragment
you should do the following:
1. In the fragment, save instance state by overriding onSaveInstanceState()
and restore in onActivityCreated()
:
class MyFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
if (savedInstanceState != null) {
//Restore the fragment's state here
}
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's state here
}
}
2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState()
and restore in onCreate()
.
class MyActivity extends Activity {
private MyFragment
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
//Restore the fragment's instance
mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
...
}
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
}
}
Hope this helps.
Try this solution.
$mainModelData = mainModel::where('column', $value)
->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
->orderBy('relation_table.title', 'ASC')
->with(['relationModal' => function ($q) {
$q->where('column', 'value');
}])->get();
Example:
$user = User::where('city', 'kullu')
->join('salaries', 'users.id', '=', 'salaries.user_id')
->orderBy('salaries.amount', 'ASC')
->with(['salaries' => function ($q) {
$q->where('amount', '>', '500000');
}])->get();
You can change the column name in join()
as per your database structure.
Simple steps: 1.Go to Android Studio. 2.Close all open projects if any. 3.There will be an option which says import non Android Studio Projects(Eclipse ect). 4.Click on it and choose ur project Thats't it enjoy!!!
Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):
var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
{
DefaultExt = "*.xml",
Filter = "BIN Files (*.bin)|*.bin",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
};
var result = saveFileDialog.ShowDialog();
if (result != null && result == true)
{
// Save the file here
}
There are some dedicated classes for this:
import java.text.*;
final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
// process c
...
}
How about this
var parsed = new Function('return ' + stringifiedJSON )();
This is a safer alternative for eval
.
var stringifiedJSON = '{"hello":"world"}';_x000D_
var parsed = new Function('return ' + stringifiedJSON)();_x000D_
alert(parsed.hello);
_x000D_
I hope following program will solve your problem
String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!
Yes, you'll need arrays.
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];
Or you can use the date.js library.
EDIT:
If you're going to use these frequently, you may want to extend Date.prototype
for accessibility.
(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ];
};
Date.prototype.getDayName = function() {
return days[ this.getDay() ];
};
})();
var now = new Date();
var day = now.getDayName();
var month = now.getMonthName();
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
Here's a backdoor method which might not work with all VMs but should work on both linux and windows (original example here):
java.lang.management.RuntimeMXBean runtime =
java.lang.management.ManagementFactory.getRuntimeMXBean();
java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
sun.management.VMManagement mgmt =
(sun.management.VMManagement) jvm.get(runtime);
java.lang.reflect.Method pid_method =
mgmt.getClass().getDeclaredMethod("getProcessId");
pid_method.setAccessible(true);
int pid = (Integer) pid_method.invoke(mgmt);
This expands on the answer by Denis Bubnov.
I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.
{% set count = 0 %}
{% for anchor in items %}
{% if anchor.content['#paragraph'].field_anchor_link.0.value %}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
{% if count > 0 %}
--- build the toc here --
{% endif %}
I use this subtle alias:
alias vim='gnome-terminal -- vim'
-x is deprecated now. We need to use -- instead
Depending on your situation, the table being locked may just be part of a normal operation & you don't want to just kill the blocking transaction. What you want to do is have your statement wait for the other resource. Oracle 11g has DDL timeouts which can be set to deal with this.
If you're dealing with 10g then you have to get more creative and write some PL/SQL to handle the re-try. Look at Getting around ORA-00054 in Oracle 10g This re-runs your statement when a resource_busy exception occurs.
Best way is to define it in styles.xml
<style name="common_txt_style_heading" parent="android:style/Widget.TextView">
<item name="android:textSize">@dimen/common_txtsize_heading</item>
<item name="android:textColor">@color/color_black</item>
<item name="android:textStyle">bold|italic</item>
</style>
And update it in TextView
<TextView
android:id="@+id/txt_userprofile"
style="@style/common_txt_style_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/margin_small"
android:text="@string/some_heading" />
Item #1. Putting a break
within the foreach
loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:
$todo=$project.PropertyGroup
foreach ($thing in $todo){
if ($thing -eq 'some_condition'){
break
}
}
Item #2. PowerShell lets you modify an array within a foreach
loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.
$a=1,2,3
foreach ($value in $a){
Write-Host $value
}
Write-Host $a
I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.
For ASP.NET MVC if you want to make an exception for leaving the page via submitting a particular form:
Set a form id:
@using (Html.BeginForm("Create", "MgtJob", FormMethod.Post, new { id = "createjob" }))
{
// Your code
}
<script type="text/javascript">
// Without submit form
$(window).bind('beforeunload', function () {
if ($('input').val() !== '') {
return "It looks like you have input you haven't submitted."
}
});
// this will call before submit; and it will unbind beforeunload
$(function () {
$("#createjob").submit(function (event) {
$(window).unbind("beforeunload");
});
});
</script>
Example, if you have:
$config['base_url'] = 'www.example.com'
set in your config.php then
echo base_url();
This works very well almost at every place.
/* Edit */
This might work for the latest versions of codeigniter (4 and above).
Use cli utility keytool from java software distribution for import (and trust!) needed certificates
Sample:
From cli change dir to jre\bin
Check keystore (file found in jre\bin directory)
keytool -list -keystore ..\lib\security\cacerts
Enter keystore password: changeit
Download and save all certificates chain from needed server.
Add certificates (before need to remove "read-only" attribute on file "..\lib\security\cacerts") keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore ..\lib\security\cacerts -file "r:\root.crt"
accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK
source: http://www.java-samples.com/showtutorial.php?tutorialid=210
System.out.println("...") in Java code is translated into JVM. Looking into the JVM gave me better understanding what is going on behind the hood.
From the book Programming form the Java Virtual Machine. This code is copied from https://github.com/ymasory/programming-for-the-jvm/blob/master/examples/HelloWorld.j.
This is the JVM source code.
.class public HelloWorld
.super java/lang/Object
.method public static main([Ljava/lang/String;)V
.limit stack 2
.limit locals 1
getstatic java/lang/System/out Ljava/io/PrintStream;
ldc "Hello, world"
invokevirtual java/io/PrintStream/println
(Ljava/lang/String;)V
return
.end method
.end class
As "The JVM doesn't permit byte-level access to memory" the out
object in type Ljava/io/PrintSteram
; is stored in a stack with getstatic
JVM command.
Then the argument is pushed on the stack before called a method println
of the java/io/PrintStream
class from an instance named out
. The method's parameter is (Ljava/lang/String
;) and output type is void (V).
How about mkString ?
theStrings.mkString(",")
A variant exists in which you can specify a prefix and suffix too.
See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.
Store the value of the scroll as changes in HiddenField when around the PostBack retrieves the value and adds the scroll.
//jQuery
jQuery(document).ready(function () {
$(window).scrollTop($("#<%=hidScroll.ClientID %>").val());
$(window).scroll(function (event) {
$("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
});
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
$(window).scrollTop($("#<%=hidScroll.ClientID %>").val());
$(window).scroll(function (event) {
$("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
});
});
//Page Asp.Net
<asp:HiddenField ID="hidScroll" runat="server" Value="0" />
<div>_x000D_
<div style="width: 20%; float: left;">_x000D_
<p>Some Contentsssssssssss</p>_x000D_
</div>_x000D_
<div style="float: left; width: 80%;">_x000D_
<textarea style="width: 100%; max-width: 100%;"></textarea>_x000D_
</div>_x000D_
<div style="clear: both;"></div>_x000D_
</div>_x000D_
_x000D_
_x000D_
Which WebControl are you using? Did you try?
DateTime.Now.ToString("yyyy-MM-dd");
Above suggestions are good. But to try to answer your question directly I'd suggest using cpy-cli
in a script defined in your package.json
.
This example expects node
to somewhere on your path. Install cpy-cli
as a development dependency:
npm install --save-dev cpy-cli
Then create a couple of nodejs files. One to do the copy and the other to display a checkmark and message.
copy.js
#!/usr/bin/env node
var shelljs = require('shelljs');
var addCheckMark = require('./helpers/checkmark');
var path = require('path');
var cpy = path.join(__dirname, '../node_modules/cpy-cli/cli.js');
shelljs.exec(cpy + ' /static/* /build/', addCheckMark.bind(null, callback));
function callback() {
process.stdout.write(' Copied /static/* to the /build/ directory\n\n');
}
checkmark.js
var chalk = require('chalk');
/**
* Adds mark check symbol
*/
function addCheckMark(callback) {
process.stdout.write(chalk.green(' ?'));
callback();
}
module.exports = addCheckMark;
Add the script in package.json
. Assuming scripts are in <project-root>/scripts/
...
"scripts": {
"copy": "node scripts/copy.js",
...
To run the sript:
npm run copy
There is a workaround using vw. Is useful when you can't create a new fluid container. This, inside a classic 'container' div will be full size.
.row-full{
width: 100vw;
position: relative;
margin-left: -50vw;
left: 50%;
}
After this there is the sidebar problem (thanks to @Typhlosaurus), solved with this js function, calling it on document load and resize:
function full_row_resize(){
var body_width = $('body').width();
$('.row-full').css('width', (body_width));
$('.row-full').css('margin-left', ('-'+(body_width/2)+'px'));
return false;
}
Once Data is exported to excel, highlight the date column and format to fit your needs or use the custom field. Worked for me like a charm!
This happens because document.write
would overwrite your existing code therefore place your div
before your javascript code. e.g.:
CSS:
#mydiv {
visibility:hidden;
}
Inside your html file
<div id="mydiv">
<p>Hello world</p>
</div>
<script type="text/javascript">
document.getElementById('mydiv').style.visibility='visible';
</script>
Hope this was helpful
this works for me,
$(function() { $('.datepicker').datepicker({ startDate: '-0m', autoclose: true }); });
The domain name portion of a URL is not case sensitive since DNS ignores case:
http://en.example.org/
and HTTP://EN.EXAMPLE.ORG/
both open the same page.
The path is used to specify and perhaps find the resource requested. It is case-sensitive, though it may be treated as case-insensitive by some servers, especially those based on Microsoft Windows.
If the server is case sensitive and http://en.example.org/wiki/URL
is correct, then http://en.example.org/WIKI/URL
or http://en.example.org/wiki/url
will display an HTTP 404 error page, unless these URLs point to valid resources themselves.
To disable CSRF for class based views the following worked for me.
Using django 1.10 and python 3.5.2
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
def post(self, request, *args, **kwargs):
return HttpResponse('Hello world')
Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing
ipconfig /all
in cmd.
You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.
If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf
Listen *:80
To Remove an Item
$("select#mySelect option[value='option1']").remove();
To Add an item
$("#mySelect").append('<option value="option1">Option</option>');
To Check for an option
$('#yourSelect option[value=yourValue]').length > 0;
To remove a selected option
$('#mySelect :selected').remove();
It could be a faulty name of a drawable file. I had an image I was using that was named Untitled
. Changing the name solved my problem.
My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:
<IfModule mod_rewrite.c>
# Turn on URL rewriting
RewriteEngine On
# If your website begins from a folder e.g localhost/my_project then
# you have to change it to: RewriteBase /my_project/
# If your site begins from the root e.g. example.local/ then
# let it as it is
RewriteBase /
# Protect application and system files from being viewed when the index.php is missing
RewriteCond $1 ^(application|system|private|logs)
# Rewrite to index.php/access_denied/URL
RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]
# Allow these directories and files to be displayed directly:
RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)
# No rewriting
RewriteRule ^(.*)$ - [PT,L]
# Rewrite to index.php/URL
RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>
It will return 18 results starting on record #9 and finishing on record #26.
Start by reading the query from offset
. First you offset by 8, which means you skip the first 8 results of the query. Then you limit by 18. Which means you consider records 9, 10, 11, 12, 13, 14, 15, 16....24, 25, 26 which are a total of 18 records.
Check this out.
And also the official documentation.
There isn't any in printf
- the two are synonyms.
Add field if not exist:
CALL addFieldIfNotExists ('settings', 'multi_user', 'TINYINT(1) NOT NULL DEFAULT 1');
addFieldIfNotExists code:
DELIMITER $$
DROP PROCEDURE IF EXISTS addFieldIfNotExists
$$
DROP FUNCTION IF EXISTS isFieldExisting
$$
CREATE FUNCTION isFieldExisting (table_name_IN VARCHAR(100), field_name_IN VARCHAR(100))
RETURNS INT
RETURN (
SELECT COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.columns
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = table_name_IN
AND COLUMN_NAME = field_name_IN
)
$$
CREATE PROCEDURE addFieldIfNotExists (
IN table_name_IN VARCHAR(100)
, IN field_name_IN VARCHAR(100)
, IN field_definition_IN VARCHAR(100)
)
BEGIN
SET @isFieldThere = isFieldExisting(table_name_IN, field_name_IN);
IF (@isFieldThere = 0) THEN
SET @ddl = CONCAT('ALTER TABLE ', table_name_IN);
SET @ddl = CONCAT(@ddl, ' ', 'ADD COLUMN') ;
SET @ddl = CONCAT(@ddl, ' ', field_name_IN);
SET @ddl = CONCAT(@ddl, ' ', field_definition_IN);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END;
$$
You can handle the fds yourself. The exec in java returns a Process object. Intermittently check if the process is still running. Once it has completed close the processes STDERR, STDIN, and STDOUT streams (e.g. proc.getErrorStream.close()). That will mitigate the leaks.
Wordpress dont have a php.ini file.
It just a cms, look into your server.
for example if you use XAMPP in windows xampp\php\php.ini
is the location.
If you'd want to use something like a "contains" operator through javascript, you can always use a Regular expression for that...
eg. Say you want to retrieve a customer having "Bartolomew" as name
async function getBartolomew() {
const custStartWith_Bart = await Customers.find({name: /^Bart/ }); // Starts with Bart
const custEndWith_lomew = await Customers.find({name: /lomew$/ }); // Ends with lomew
const custContains_rtol = await Customers.find({name: /.*rtol.*/ }); // Contains rtol
console.log(custStartWith_Bart);
console.log(custEndWith_lomew);
console.log(custContains_rtol);
}
If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name
=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))
See screenshot
From Unix.SE: A simple command-line utility called gpustat
now exists: https://github.com/wookayin/gpustat.
It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi
.
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', '');
It will return 5.98 without rounding the number.
It would not be wrong, if we say that redis is combination of (cache + data structure) while memcached is just a cache.
This works on Windows
Then you'll be able to see all modules within those paths from your scripts.
As of ES 7, mapping types have been removed. You can read more details here
If you are using Ruby On Rails this means that you may need to remove document_type
from your model or concern.
As an alternative to mapping types one solution is to use an index per document type.
Before:
module Searchable
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
index_name [Rails.env, Rails.application.class.module_parent_name.underscore].join('_')
document_type self.name.downcase
end
end
After:
module Searchable
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
index_name [Rails.env, Rails.application.class.module_parent_name.underscore, self.name.downcase].join('_')
end
end
The first answer will print a string with prefix b'. That means your string will be like this b'your_string' To solve this issue please add the following line of code.
encoded_string= base64.b64encode(img_file.read())
print(encoded_string.decode('utf-8'))
My case was different from the accepted answer. I was trying to mock a package-private method for an instance that did not live in that package
package common;
public class Animal {
void packageProtected();
}
package instances;
class Dog extends Animal { }
and the test classes
package common;
public abstract class AnimalTest<T extends Animal> {
@Before
setup(){
doNothing().when(getInstance()).packageProtected();
}
abstract T getInstance();
}
package instances;
class DogTest extends AnimalTest<Dog> {
Dog getInstance(){
return spy(new Dog());
}
@Test
public void myTest(){}
}
The compilation is correct, but when it tries to setup the test, it invokes the real method instead.
Declaring the method protected or public fixes the issue, tho it's not a clean solution.
In your xml file add something like this with width and height as 'match_parent'.
<RelativeLayout
android:id="@+id/bac_dim_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C0000000"
android:visibility="gone" >
</RelativeLayout>
In your activity oncreate
//setting background dim when showing popup
back_dim_layout = (RelativeLayout) findViewById(R.id.share_bac_dim_layout);
Finally make visible when you show your popupwindow and make its visible gone when you exit popupwindow.
back_dim_layout.setVisibility(View.VISIBLE);
back_dim_layout.setVisibility(View.GONE);
The error you are getting is either because you are doing TO_DATE
on a column that's already a date, and you're using a format mask that is different to your nls_date_format
parameter[1] or because the event_occurrence column contains data that isn't a number.
You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.
And fix the datatype of that column to make sure you can only store numbers.
[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask)
is:
TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)
Generally, the default nls_date_format
parameter is set to dd-MON-yy
, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.
To remove elements from an array, use the remove(at:)
,
removeLast()
and removeAll()
.
yourArray = [1,2,3,4]
Remove the value at 2 position
yourArray.remove(at: 2)
Remove the last value from array
yourArray.removeLast()
Removes all members from the set
yourArray.removeAll()
jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:
public class MaxAttribute : ValidationAttribute, IClientValidatable
{
private readonly int maxValue;
public MaxAttribute(int maxValue)
{
this.maxValue = maxValue;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = ErrorMessageString, maxValue;
rule.ValidationType = "max";
rule.ValidationParameters.Add("max", maxValue);
yield return rule;
}
public override bool IsValid(object value)
{
return (int)value <= maxValue;
}
}
Adapter:
$.validator.unobtrusive.adapters.add(
'max',
['max'],
function (options) {
options.rules['max'] = parseInt(options.params['max'], 10);
options.messages['max'] = options.message;
});
Min attribute would be very similar.
It's for whose Hadoop is 2.6 and Spark is 1.6 and without "databricks" package.
import org.apache.spark.sql.types.{StructType,StructField,StringType,IntegerType};
import org.apache.spark.sql.Row;
val csv = sc.textFile("/path/to/file.csv")
val rows = csv.map(line => line.split(",").map(_.trim))
val header = rows.first
val data = rows.filter(_(0) != header(0))
val rdd = data.map(row => Row(row(0),row(1).toInt))
val schema = new StructType()
.add(StructField("id", StringType, true))
.add(StructField("val", IntegerType, true))
val df = sqlContext.createDataFrame(rdd, schema)
Try this:
string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
Status 422 (RFC 4918, Section 11.2) comes to mind:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Here You Go:
HTML
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
Script:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
i will provide mine because @muni s solution was a bit overkill for me
note: if you want to add custom definitions for several resolutions together, say something like this:
//mobile generally
@media screen and (max-width: 1199) {
.irns-desktop{
display: none;
}
.irns-mobile{
display: initial;
}
}
Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')
//here all definitions to apply globally
//desktop
@media only screen
and (min-width : 1200) {
}
//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px) {
} // end media query
//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px) {
}//end media definition
//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px) {
}//end media query
//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {
}
//end media query
This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.
So, which XML parsing module to pick?
Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.
Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.
Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692
Solution using command line for Windows, Linux, and MacOS
If you have updated your GitHub password on the GitHub server, in the first attempt of the git fetch/pull/push
command it generates the authentication failed message.
Execute the same git fetch/pull/push
command a second time and it prompts for credentials (username and password). Enter the username and the new updated password of the GitHub server and login will be successful.
Even I had this problem, and I performed the above steps and done!!
It's not pretty, but the way I resign the firstResponder when I don't know what that the responder is:
Create an UITextField, either in IB or programmatically. Make it Hidden. Link it up to your code if you made it in IB. Then, when you want to dismiss the keyboard, you switch the responder to the invisible text field, and immediately resign it:
[self.invisibleField becomeFirstResponder];
[self.invisibleField resignFirstResponder];
You still need to add
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
</plugins>
in your build, because pluginManagement
is only a way to share the same plugin configuration across all your project modules.
From Maven documentation:
pluginManagement: is an element that is seen along side plugins. Plugin Management contains plugin elements in much the same way, except that rather than configuring plugin information for this particular project build, it is intended to configure project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.
I prefer readability first which most often does not use the setup method. I make an exception when a basic setup operation takes a long time and is repeated within each test.
At that point I move that functionality into a setup method using the @BeforeClass
annotation (optimize later).
Example of optimization using the @BeforeClass
setup method: I use dbunit for some database functional tests. The setup method is responsible for putting the database in a known state (very slow... 30 seconds - 2 minutes depending on amount of data). I load this data in the setup method annotated with @BeforeClass
and then run 10-20 tests against the same set of data as opposed to re-loading/initializing the database inside each test.
Using Junit 3.8 (extending TestCase as shown in your example) requires writing a little more code than just adding an annotation, but the "run once before class setup" is still possible.
Try negation operator !
before $(this)
:
if (!$(this).parent().next().is('ul')){
You can also setup the environment in visual studio code. Run Ctrl + Shift + P, Then type ctr in the box that appears and select tasks:Configure Task Runner, Then change the task.json file to this: { "version": "0.1.0", "command": "explorer", "windows": { "command": "explorer.exe" }, "args": ["index.html"] }
, save your changes, Then select your index.html file and type Ctrl + Shift + B. This will open the project with your default browser.
The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.
Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.
Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.
Enough explanation, the solution (JS, CSS, HTML):
$(window).on("load",function() {_x000D_
$(window).scroll(function() {_x000D_
var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
}_x000D_
});_x000D_
}).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
if ($(this).css("opacity")==0) {...}
. This makes sure the object is only faded in when the opacity
is 0
. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object..animate()
to .fadeTo()
. It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate..position()
to .offset()
. This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.$(window).height()
to $(window).innerHeight()
. The latter is more reliable in my experience.$(window).scroll();
. Now you can give all desired objects on the page the .fade
class, and objects that should be invisible at page-load, will be faded out immediately.#container
from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px
because you used .position()
instead of .offset()
, otherwise I don't know. Feel free of course to leave it in your code.)If you want opacity values other than 0
and 1
, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
var min = 0.3;_x000D_
var max = 0.7;_x000D_
var threshold = 0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
_x000D_
/* If the element is completely within bounds of the window, fade it in */_x000D_
if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
} else { //object goes out of view (scrolling up)_x000D_
if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
threshold
and for min/max
at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.|| pageLoad
to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad
is a boolean that is send along as an argument when fade()
is invoked.function fade() {...}
, in order to be able to send along the pageLoad
boolean when the scroll-handler is invoked.Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3
, the actual value (in this case) is 0.300000011920929
. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}
.
I added a threshold, to take that difference into account: == 0.3
becomes <= 0.31
.
(I've set the threshold to 0.01
, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)
The operators are now changed from ==
to <=
and >=
.
If you want to fade the elements based on their visible percentage, use the following code:
$(window).on("load",function() {_x000D_
function fade(pageLoad) {_x000D_
var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
var min=0.3, max=0.7, threshold=0.01;_x000D_
_x000D_
$(".fade").each(function() {_x000D_
/* Check the location of each desired element */_x000D_
var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
_x000D_
/* Fade element in/out based on its visible percentage */_x000D_
if (objectTop < windowTop) {_x000D_
if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if (objectBottom > windowBottom) {_x000D_
if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
} else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
});_x000D_
} fade(true); //fade elements on page-load_x000D_
$(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
margin: 50px;_x000D_
padding: 50px;_x000D_
background-color: lightgreen;_x000D_
opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<div class="fade">Fade In 01</div>_x000D_
<div class="fade">Fade In 02</div>_x000D_
<div class="fade">Fade In 03</div>_x000D_
<div class="fade">Fade In 04</div>_x000D_
<div class="fade">Fade In 05</div>_x000D_
<div class="fade">Fade In 06</div>_x000D_
<div class="fade">Fade In 07</div>_x000D_
<div class="fade">Fade In 08</div>_x000D_
<div class="fade">Fade In 09</div>_x000D_
<div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
mysql> SHOW PROCESSLIST;
+-----+------+-----------------+------+---------+------+-------+---------------+
| Id | User | Host | db | Command | Time | State | Info |
+-----+------+-----------------+------+---------+------+-------+----------------+
| 143 | root | localhost:61179 | cds | Query | 0 | init | SHOW PROCESSLIST |
| 192 | root | localhost:53793 | cds | Sleep | 4 | | NULL |
+-----+------+-----------------+------+---------+------+-------+----------------+
2 rows in set (0.00 sec)
mysql> KILL 192;
Query OK, 0 rows affected (0.00 sec)
USER 192 :
mysql> SELECT * FROM exept;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
mysql> SELECT * FROM exept;
ERROR 2013 (HY000): Lost connection to MySQL server during query
This can be simply done like this.
created() {
var scripts = [
"https://cloudfront.net/js/jquery-3.4.1.min.js",
"js/local.js"
];
scripts.forEach(script => {
let tag = document.createElement("script");
tag.setAttribute("src", script);
document.head.appendChild(tag);
});
}
You can use attached properties for setting button border radius (also the same will work for textboxes).
Create class for attached property
public class CornerRadiusSetter
{
public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty);
public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value);
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius),
typeof(CornerRadiusSetter), new UIPropertyMetadata(new CornerRadius(), CornerRadiusChangedCallback));
public static void CornerRadiusChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
{
Control control = sender as Control;
if (control == null) return;
control.Loaded -= Control_Loaded;
control.Loaded += Control_Loaded;
}
private static void Control_Loaded(object sender, EventArgs e)
{
Control control = sender as Control;
if (control == null || control.Template == null) return;
control.ApplyTemplate();
Border border = control.Template.FindName("border", control) as Border;
if (border == null) return;
border.CornerRadius = GetCornerRadius(control);
}
}
Then you can use attached property syntax for multiple buttons without style duplicates:
<Button local:CornerRadiusSetter.CornerRadius="10">Click me!</Button>
<Button local:CornerRadiusSetter.CornerRadius="5, 0, 0, 5">Click me!</Button>
<Button local:CornerRadiusSetter.CornerRadius="3, 20, 8, 15">Click me!</Button>
You can also use evalAsync. It will run sometime after digest has finished!
scope.evalAsync(function(scope){
//use the scope...
});
perldoc perlvar
does not seem to suggest any such variable.
In addition to the other answers, there is a big benefit to using the DisplayAttribute
when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.
Also, you can let MVC generate the templates for you by using Html.EditorForModel()
and it will generate the correct label for you.
Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.
var results = (medicineInfo.OrderBy(x=>x.id)_x000D_
.Skip((pages -1) * 2)_x000D_
.Take(2));
_x000D_
Maybe you can do something with
get-process -includeusername
Your problem is well explained in this document by Apple. Example code on this page (at Listing 4-1
) does exactly what you need, it will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew.
The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:
Declare a variable
var activeField: UITextField?
then add these methods
func registerForKeyboardNotifications()
{
//Adding notifies on keyboard appearing
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
func deregisterFromKeyboardNotifications()
{
//Removing notifies on keyboard appearing
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(notification: NSNotification)
{
//Need to calculate keyboard exact size due to Apple suggestions
self.scrollView.scrollEnabled = true
var info : NSDictionary = notification.userInfo!
var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
aRect.size.height -= keyboardSize!.height
if let activeFieldPresent = activeField
{
if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
{
self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
}
}
}
func keyboardWillBeHidden(notification: NSNotification)
{
//Once keyboard disappears, restore original positions
var info : NSDictionary = notification.userInfo!
var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
self.view.endEditing(true)
self.scrollView.scrollEnabled = false
}
func textFieldDidBeginEditing(textField: UITextField!)
{
activeField = textField
}
func textFieldDidEndEditing(textField: UITextField!)
{
activeField = nil
}
Be sure to declare your ViewController as UITextFieldDelegate
and set correct delegates in your initialization methods:
ex:
self.you_text_field.delegate = self
And remember to call registerForKeyboardNotifications
on viewInit and deregisterFromKeyboardNotifications
on exit.
func registerForKeyboardNotifications(){
//Adding notifies on keyboard appearing
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}
func deregisterFromKeyboardNotifications(){
//Removing notifies on keyboard appearing
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWasShown(notification: NSNotification){
//Need to calculate keyboard exact size due to Apple suggestions
self.scrollView.isScrollEnabled = true
var info = notification.userInfo!
let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
aRect.size.height -= keyboardSize!.height
if let activeField = self.activeField {
if (!aRect.contains(activeField.frame.origin)){
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
}
@objc func keyboardWillBeHidden(notification: NSNotification){
//Once keyboard disappears, restore original positions
var info = notification.userInfo!
let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
self.view.endEditing(true)
self.scrollView.isScrollEnabled = false
}
func textFieldDidBeginEditing(_ textField: UITextField){
activeField = textField
}
func textFieldDidEndEditing(_ textField: UITextField){
activeField = nil
}