You can first concatenate the strings in the list with the separator ';' using the function join
and then use the split
function in order create the list:
l = ['Facebook;Google+;MySpace', 'Apple;Android']
l1 = ";".join(l)).split(";")
print l1
outputs
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
Yes you will have to escape all double quotes by a backslash.
In my case the files were appeared as modified after changing the files permissions.
To make git ignore permission changes, do the following :
# For the current repository
git config core.filemode false
# Globally
git config --global core.filemode false
For Python 3:
>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'
...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.
\s
on its own always covers the ASCII whitespace:
Additionally:
re.UNICODE
enabled,...\s
also covers the Unicode whitespace characters, for example:
...etc. See the full list here, under "Unicode characters with White_Space property".
However \s
DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:
...etc. See the full list here, under "Related Unicode characters without White_Space property".
So these 6 characters are covered by the list in the second regex, \u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF
.
Sources:
I agree with Paolo that we need to see more code. I tested this overly simplified example and it worked. This means that it is able to change the form action on the fly.
<script type="text/javascript">
function submitForm(){
var form_url = $("#openid_form").attr("action");
alert("Before - action=" + form_url);
//changing the action to google.com
$("#openid_form").attr("action","http://google.com");
alert("After - action = "+$("#openid_form").attr("action"));
//submit the form
$("#openid_form").submit();
}
</script>
<form id="openid_form" action="test.html">
First Name:<input type="text" name="fname" /><br/>
Last Name: <input type="text" name="lname" /><br/>
<input type="button" onclick="submitForm()" value="Submit Form" />
</form>
EDIT: I tested the updated code you posted and found a syntax error in the declaration of providers_large
. There's an extra comma. Firefox ignores the issue, but IE8 throws an error.
var providers_large = {
google: {
name: 'Google',
url: 'https://www.google.com/accounts/o8/id'
},
facebook: {
name: 'Facebook',
form_url: 'http://wikipediamaze.rpxnow.com/facebook/start?token_url=http://www.wikipediamaze.com/Accounts/Logon'
}, //<-- Here's the problem. Remove that comma
};
I think your solution would be to wrap your content container and your sidebar in a parent containing div. Float your sidebar to the left and give it the background image. Create a wide margin at least the width of your sidebar for your content container. Add clearing a float hack to make it all work.
A simpler solution is to do this rather than using uniform:
$('#check1').prop('checked', true); // will check the checkbox with id check1
$('#check1').prop('checked', false); // will uncheck the checkbox with id check1
This will not trigger any click action defined.
You can also use:
$('#check1').click(); //
This will toggle the check/uncheck for the checkbox but this will also trigger any click action you have defined. So be careful.
EDIT: jQuery 1.6+ uses prop()
not attr()
for checkboxes checked value
In my case this error occured when I set up my environment adb path as ~/.android-sdk/platform-tools
(which happens when e.g. android-platform-tools is installed via homebrew), which version was 36, but Android Studio project has Android SDK next path ~/Library/Android/sdk
which adb version was 39.
I have changed my PATH to platform-tools to ~/Library/Android/sdk/platform-tools
and error was solved
There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.
function file_get_contents_proxy($url,$proxy){
// Create context stream
$context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
$context = stream_context_create($context_array);
// Use context stream with file_get_contents
$data = file_get_contents($url,false,$context);
// Return data via proxy
return $data;
}
To initialize long you need to append "L" to the end.
It can be either uppercase or lowercase.
All the numeric values are by default int
. Even when you do any operation of byte
with any integer, byte
is first promoted to int
and then any operations are performed.
Try this
byte a = 1; // declare a byte
a = a*2; // you will get error here
You get error because 2
is by default int
.
Hence you are trying to multiply byte
with int
.
Hence result gets typecasted to int
which can't be assigned back to byte
.
I used android:ems="23"
to solve my problem. Just replace 23 with the best value in your case.
<TextView
android:id="@+id/msg"
android:ems="23"
android:text="ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab "
android:textColor="@color/white"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Yet another solution:
string s = "??"; // or whatever
if (chldNode.Attributes.Cast<XmlAttribute>()
.Select(x => x.Value)
.Contains(attributeName))
s = xe.Attributes[attributeName].Value;
It also avoids the exception when the expected attribute attributeName
actually doesn't exist.
You can also use DateTime.Now.ToString("yyyy-MM-dd")
for the date, and DateTime.Now.ToString("hh:mm:ss")
for the time.
I defined an alias, workoff, as the opposite of workon:
alias workoff='deactivate'
It is easy to remember:
[bobstein@host ~]$ workon django_project
(django_project)[bobstein@host ~]$ workoff
[bobstein@host ~]$
Follow this tutorial Tensorflow GPU I did it and it works perfect.
Attention! - install version 9.0! newer version is not supported by Tensorflow-gpu
Steps:
pip install tensorflow-gpu
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Use numpy.tile
:
>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
or for repeating columns:
>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
Or if you want to do this with a script:
sed -i 's/\r//' filename
[Kotlin version] I created this extension that also checks if the desired color has enough contrast to hide the System UI, like Battery Status Icon, Clock, etc, so we set the System UI white or black according to this.
fun Activity.coloredStatusBarMode(@ColorInt color: Int = Color.WHITE, lightSystemUI: Boolean? = null) {
var flags: Int = window.decorView.systemUiVisibility // get current flags
var systemLightUIFlag = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
var setSystemUILight = lightSystemUI
if (setSystemUILight == null) {
// Automatically check if the desired status bar is dark or light
setSystemUILight = ColorUtils.calculateLuminance(color) < 0.5
}
flags = if (setSystemUILight) {
// Set System UI Light (Battery Status Icon, Clock, etc)
removeFlag(flags, systemLightUIFlag)
} else {
// Set System UI Dark (Battery Status Icon, Clock, etc)
addFlag(flags, systemLightUIFlag)
}
window.decorView.systemUiVisibility = flags
window.statusBarColor = color
}
private fun containsFlag(flags: Int, flagToCheck: Int) = (flags and flagToCheck) != 0
private fun addFlag(flags: Int, flagToAdd: Int): Int {
return if (!containsFlag(flags, flagToAdd)) {
flags or flagToAdd
} else {
flags
}
}
private fun removeFlag(flags: Int, flagToRemove: Int): Int {
return if (containsFlag(flags, flagToRemove)) {
flags and flagToRemove.inv()
} else {
flags
}
}
A simple solution is to wrap the query into a subselect with the ORDER statement first and applying the GROUP BY later:
SELECT * FROM (
SELECT `timestamp`, `fromEmail`, `subject`
FROM `incomingEmails`
ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)
This is similar to using the join but looks much nicer.
Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard. MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.
IMPORTANT UPDATE Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the MySQL documentation "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."
As of 5.7.5 ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)
As @mikep points out below the solution is to use ANY_VALUE() from 5.7 and above
See http://www.cafewebmaster.com/mysql-order-sort-group https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
Change the line into this
angular.forEach(values, function(value, key){
console.log(key + ': ' + value);
});
angular.forEach(values, function(value, key){
console.log(key + ': ' + value.Name);
});
You can change the index as explained already using set_index
.
You don't need to manually swap rows with columns, there is a transpose (data.T
) method in pandas that does it for you:
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> newdf = df.set_index('Locality').T
> newdf
Locality ABBOTSFORD ABERFELDIE
2005 427000 534000
2006 448000 600000
then you can fetch the dataframe column values and transform them to a list:
> newdf['ABBOTSFORD'].values.tolist()
[427000, 448000]
I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:
select min(Id), distinct MailId, EmailAddress, Name
from yourTableName
group by MailId, EmailAddress, Name
I see that I am using a GROUP BY clause
but you still won't have two rows against any particular MailId
.
One of the most straightforward ways of gettings rid of ^Ms with just an emacs command one-liner:
C-x h C-u M-| dos2unix
Analysis:
C-x h: select current buffer
C-u: apply following command as a filter, redirecting its output to replace current buffer
M-| dos2unix: performs `dos2unix` [current buffer]
*nix platforms have the dos2unix
utility out-of-the-box, including Mac (with brew
). Under Windows, it is widely available too (MSYS2, Cygwin, user-contributed, among others).
Try this code,
$(".endDate").datepicker({
format: 'dd/mm/yyyy',
autoclose: true
}).datepicker("update", "10/10/2016");
this will update date and apply format dd/mm/yyyy
as well.
You can refer to event modifiers in vuejs to prevent form submission on enter
key.
It is a very common need to call
event.preventDefault()
orevent.stopPropagation()
inside event handlers.Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
To address this problem, Vue provides event modifiers for
v-on
. Recall that modifiers are directive postfixes denoted by a dot.
<form v-on:submit.prevent="<method>">
...
</form>
As the documentation states, this is syntactical sugar for e.preventDefault()
and will stop the unwanted form submission on press of enter key.
Here is a working fiddle.
new Vue({_x000D_
el: '#myApp',_x000D_
data: {_x000D_
emailAddress: '',_x000D_
log: ''_x000D_
},_x000D_
methods: {_x000D_
validateEmailAddress: function(e) {_x000D_
if (e.keyCode === 13) {_x000D_
alert('Enter was pressed');_x000D_
} else if (e.keyCode === 50) {_x000D_
alert('@ was pressed');_x000D_
} _x000D_
this.log += e.key;_x000D_
},_x000D_
_x000D_
postEmailAddress: function() {_x000D_
this.log += '\n\nPosting';_x000D_
},_x000D_
noop () {_x000D_
// do nothing ?_x000D_
}_x000D_
}_x000D_
})
_x000D_
html, body, #editor {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
<form v-on:submit.prevent="noop">_x000D_
<input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />_x000D_
<button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
<br /><br />_x000D_
_x000D_
<textarea v-model="log" rows="4"></textarea> _x000D_
</form>_x000D_
</div>
_x000D_
You should add App Transport Security Settings
to info.plist
and add Allow Arbitrary Loads
to App Transport Security Settings
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Try this, works for me very well:
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
std::vector always makes a copy of whatever is being stored in the vector.
If you are keeping a vector of pointers, then it will make a copy of the pointer, but not the instance being to which the pointer is pointing. If you are dealing with large objects, you can (and probably should) always use a vector of pointers. Often, using a vector of smart pointers of an appropriate type is good for safety purposes, since handling object lifetime and memory management can be tricky otherwise.
Use the below code to find the count of number of matches that the regex finds in your input
Pattern p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);// "regex" here indicates your predefined regex.
Matcher m = p.matcher(pattern); // "pattern" indicates your string to match the pattern against with
boolean b = m.matches();
if(b)
count++;
while (m.find())
count++;
This is a generalized code not specific one though, tailor it to suit your need
Please feel free to correct me if there is any mistake.
Also check out http://www.sagekey.com/installation_access.aspx for great installation scripts for Ms Access. Also if you need to integrate images into your application check out DBPix at ammara.com
When you use the start command to a website it will use the default browser by default but if you want to use a specific browser then use start iexplorer.exe www.website.com
Also you cannot have http://
in the url.
All credit to Rajeev Kumar's answer, but I received a list of anonymous type that evaluated to string, which was not as easy to iterate over. Updating the code as below helped to return a List that was more easy to manipulate (or, for example, drop straight into a foreach block).
var distinctIds = datatable.AsEnumerable().Select(row => row.Field<string>("id")).Distinct().ToList();
First enable a2enmod rewrite
next restart the apache
/etc/init.d/apache2 restart
Also, change this:
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
to
SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
The reason is that for the first time the variable SelBranchVal
will be empty
It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.
A better query would be:
SELECT
COLUMN_NAME,
Case
When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary')
Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)
When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint')
Then convert(varchar(MAX), NUMERIC_PRECISION)
When DATA_TYPE = 'bit'
Then convert(varchar(MAX), 1)
When DATA_TYPE IN ('decimal', 'float')
Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE))
When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp')
Then ''
End As DATALEN,
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
Where
TABLE_NAME = ''
The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!
Two notes from experience which might be helpful:
You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.
If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.
(This answer took a while to write, and codeWizard's answer is correct in aim and essence, but not entirely complete, so I'll post this anyway.)
There is no such thing as a "remote Git tag". There are only "tags". I point all this out not to be pedantic,1 but because there is a great deal of confusion about this with casual Git users, and the Git documentation is not very helpful2 to beginners. (It's not clear if the confusion comes because of poor documentation, or the poor documentation comes because this is inherently somewhat confusing, or what.)
There are "remote branches", more properly called "remote-tracking branches", but it's worth noting that these are actually local entities. There are no remote tags, though (unless you (re)invent them). There are only local tags, so you need to get the tag locally in order to use it.
The general form for names for specific commits—which Git calls references—is any string starting with refs/
. A string that starts with refs/heads/
names a branch; a string starting with refs/remotes/
names a remote-tracking branch; and a string starting with refs/tags/
names a tag. The name refs/stash
is the stash reference (as used by git stash
; note the lack of a trailing slash).
There are some unusual special-case names that do not begin with refs/
: HEAD
, ORIG_HEAD
, MERGE_HEAD
, and CHERRY_PICK_HEAD
in particular are all also names that may refer to specific commits (though HEAD
normally contains the name of a branch, i.e., contains ref: refs/heads/branch
). But in general, references start with refs/
.
One thing Git does to make this confusing is that it allows you to omit the refs/
, and often the word after refs/
. For instance, you can omit refs/heads/
or refs/tags/
when referring to a local branch or tag—and in fact you must omit refs/heads/
when checking out a local branch! You can do this whenever the result is unambiguous, or—as we just noted—when you must do it (for git checkout branch
).
It's true that references exist not only in your own repository, but also in remote repositories. However, Git gives you access to a remote repository's references only at very specific times: namely, during fetch
and push
operations. You can also use git ls-remote
or git remote show
to see them, but fetch
and push
are the more interesting points of contact.
During fetch
and push
, Git uses strings it calls refspecs to transfer references between the local and remote repository. Thus, it is at these times, and via refspecs, that two Git repositories can get into sync with each other. Once your names are in sync, you can use the same name that someone with the remote uses. There is some special magic here on fetch
, though, and it affects both branch names and tag names.
You should think of git fetch
as directing your Git to call up (or perhaps text-message) another Git—the "remote"—and have a conversation with it. Early in this conversation, the remote lists all of its references: everything in refs/heads/
and everything in refs/tags/
, along with any other references it has. Your Git scans through these and (based on the usual fetch refspec) renames their branches.
Let's take a look at the normal refspec for the remote named origin
:
$ git config --get-all remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*
$
This refspec instructs your Git to take every name matching refs/heads/*
—i.e., every branch on the remote—and change its name to refs/remotes/origin/*
, i.e., keep the matched part the same, changing the branch name (refs/heads/
) to a remote-tracking branch name (refs/remotes/
, specifically, refs/remotes/origin/
).
It is through this refspec that origin
's branches become your remote-tracking branches for remote origin
. Branch name becomes remote-tracking branch name, with the name of the remote, in this case origin
, included. The plus sign +
at the front of the refspec sets the "force" flag, i.e., your remote-tracking branch will be updated to match the remote's branch name, regardless of what it takes to make it match. (Without the +
, branch updates are limited to "fast forward" changes, and tag updates are simply ignored since Git version 1.8.2 or so—before then the same fast-forward rules applied.)
But what about tags? There's no refspec for them—at least, not by default. You can set one, in which case the form of the refspec is up to you; or you can run git fetch --tags
. Using --tags
has the effect of adding refs/tags/*:refs/tags/*
to the refspec, i.e., it brings over all tags (but does not update your tag if you already have a tag with that name, regardless of what the remote's tag says Edit, Jan 2017: as of Git 2.10, testing shows that --tags
forcibly updates your tags from the remote's tags, as if the refspec read +refs/tags/*:refs/tags/*
; this may be a difference in behavior from an earlier version of Git).
Note that there is no renaming here: if remote origin
has tag xyzzy
, and you don't, and you git fetch origin "refs/tags/*:refs/tags/*"
, you get refs/tags/xyzzy
added to your repository (pointing to the same commit as on the remote). If you use +refs/tags/*:refs/tags/*
then your tag xyzzy
, if you have one, is replaced by the one from origin
. That is, the +
force flag on a refspec means "replace my reference's value with the one my Git gets from their Git".
For historical reasons,3 if you use neither the --tags
option nor the --no-tags
option, git fetch
takes special action. Remember that we said above that the remote starts by displaying to your local Git all of its references, whether your local Git wants to see them or not.4 Your Git takes note of all the tags it sees at this point. Then, as it begins downloading any commit objects it needs to handle whatever it's fetching, if one of those commits has the same ID as any of those tags, git will add that tag—or those tags, if multiple tags have that ID—to your repository.
Edit, Jan 2017: testing shows that the behavior in Git 2.10 is now: If their Git provides a tag named T, and you do not have a tag named T, and the commit ID associated with T is an ancestor of one of their branches that your git fetch
is examining, your Git adds T to your tags with or without --tags
. Adding --tags
causes your Git to obtain all their tags, and also force update.
You may have to use git fetch --tags
to get their tags. If their tag names conflict with your existing tag names, you may (depending on Git version) even have to delete (or rename) some of your tags, and then run git fetch --tags
, to get their tags. Since tags—unlike remote branches—do not have automatic renaming, your tag names must match their tag names, which is why you can have issues with conflicts.
In most normal cases, though, a simple git fetch
will do the job, bringing over their commits and their matching tags, and since they—whoever they are—will tag commits at the time they publish those commits, you will keep up with their tags. If you don't make your own tags, nor mix their repository and other repositories (via multiple remotes), you won't have any tag name collisions either, so you won't have to fuss with deleting or renaming tags in order to obtain their tags.
I mentioned above that you can omit refs/
almost always, and refs/heads/
and refs/tags/
and so on most of the time. But when can't you?
The complete (or near-complete anyway) answer is in the gitrevisions
documentation. Git will resolve a name to a commit ID using the six-step sequence given in the link. Curiously, tags override branches: if there is a tag xyzzy
and a branch xyzzy
, and they point to different commits, then:
git rev-parse xyzzy
will give you the ID to which the tag points. However—and this is what's missing from gitrevisions
—git checkout
prefers branch names, so git checkout xyzzy
will put you on the branch, disregarding the tag.
In case of ambiguity, you can almost always spell out the ref name using its full name, refs/heads/xyzzy
or refs/tags/xyzzy
. (Note that this does work with git checkout
, but in a perhaps unexpected manner: git checkout refs/heads/xyzzy
causes a detached-HEAD checkout rather than a branch checkout. This is why you just have to note that git checkout
will use the short name as a branch name first: that's how you check out the branch xyzzy
even if the tag xyzzy
exists. If you want to check out the tag, you can use refs/tags/xyzzy
.)
Because (as gitrevisions
notes) Git will try refs/name
, you can also simply write tags/xyzzy
to identify the commit tagged xyzzy
. (If someone has managed to write a valid reference named xyzzy
into $GIT_DIR
, however, this will resolve as $GIT_DIR/xyzzy
. But normally only the various *HEAD
names should be in $GIT_DIR
.)
1Okay, okay, "not just to be pedantic". :-)
2Some would say "very not-helpful", and I would tend to agree, actually.
3Basically, git fetch
, and the whole concept of remotes and refspecs, was a bit of a late addition to Git, happening around the time of Git 1.5. Before then there were just some ad-hoc special cases, and tag-fetching was one of them, so it got grandfathered in via special code.
4If it helps, think of the remote Git as a flasher, in the slang meaning.
Of course it's possible to create a foreign key relationship to a compound (more than one column) primary key. You didn't show us the statement you're using to try and create that relationship - it should be something like:
ALTER TABLE dbo.Content
ADD CONSTRAINT FK_Content_Libraries
FOREIGN KEY(LibraryID, Application)
REFERENCES dbo.Libraries(ID, Application)
Is that what you're using?? If (ID, Application)
is indeed the primary key on dbo.Libraries
, this statement should definitely work.
Luk: just to check - can you run this statement in your database and report back what the output is??
SELECT
tc.TABLE_NAME,
tc.CONSTRAINT_NAME,
ccu.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE
tc.TABLE_NAME IN ('Libraries', 'Content')
<?php
function info($name="George",$age=18) {
echo "$name is $age years old.<br>";
}
info(); // prints default values(number of values = 2)
info("Nick"); // changes first default argument from George to Nick
info("Mark",17); // changes both default arguments' values
?>
date = models.DateTimeField(default=datetime.now, blank=True)
Adding a branch
option in .gitmodule
is NOT related to the detached behavior of submodules at all. The old answer from @mkungla is incorrect, or obsolete.
From git submodule --help
, HEAD detached is the default behavior of git submodule update --remote
.
First, there's no need to specify a branch to be tracked. origin/master
is the default branch to be tracked.
--remote
Instead of using the superproject's recorded SHA-1 to update the submodule, use the status of the submodule's remote-tracking branch. The remote used is branch's remote (
branch.<name>.remote
), defaulting toorigin
. The remote branch used defaults tomaster
.
So why is HEAD detached after update
? This is caused by the default module update behavior: checkout
.
--checkout
Checkout the commit recorded in the superproject on a detached HEAD in the submodule. This is the default behavior, the main use of this option is to override
submodule.$name.update
when set to a value other thancheckout
.
To explain this weird update behavior, we need to understand how do submodules work?
Quote from Starting with Submodules in book Pro Git
Although sbmodule
DbConnector
is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.
The main repo tracks the submodule with its state at a specific point, the commit id. So when you update modules, you're updating the commit id to a new one.
If you want the submodule merged with remote branch automatically, use --merge
or --rebase
.
--merge
This option is only valid for the update command. Merge the commit recorded in the superproject into the current branch of the submodule. If this option is given, the submodule's HEAD will not be detached.
--rebase
Rebase the current branch onto the commit recorded in the superproject. If this option is given, the submodule's HEAD will not be detached.
All you need to do is,
git submodule update --remote --merge
# or
git submodule update --remote --rebase
Recommended alias:
git config alias.supdate 'submodule update --remote --merge'
# do submodule update with
git supdate
There's also an option to make --merge
or --rebase
as the default behavior of git submodule update
, by setting submodule.$name.update
to merge
or rebase
.
Here's an example about how to config the default update behavior of submodule update in .gitmodule
.
[submodule "bash/plugins/dircolors-solarized"]
path = bash/plugins/dircolors-solarized
url = https://github.com/seebi/dircolors-solarized.git
update = merge # <-- this is what you need to add
Or configure it in command line,
# replace $name with a real submodule name
git config -f .gitmodules submodule.$name.update merge
git submodule --help
m <- matrix(1:20, ncol = 4)
colnames(m) <- letters[1:4]
The following command will select the first row of the matrix above.
subset(m, m[,4] == 16)
And this will select the last three.
subset(m, m[,4] > 17)
The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with
mf <- data.frame(m)
Then you can select with
mf[ mf$a == 16, ]
Or, you could use the subset command.
You can simply bind $this->getParameter('app.version')
in controller to twig param and then render it.
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
sqldump to a text file, find/replace, re-import the sqldump.
Dump the database to a text file
mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql
Restore the database after you have made changes to it.
mysql -u root -p[root_password] [database_name] < dumpfilename.sql
I have had the same problem, font/opentype worked for me
Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.
Try
SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
FROM Project_Assigned pa
INNER JOIN Account a
ON pa.AccountID = a.Account_ID
INNER JOIN Project p
ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
ON a.Account_ID = c.Account_ID
WHERE a.Access_Type = 'Client';
cocoapod on terminal follow this:
sudo gem update
sudo gem install cocoapods
pod setup
cd (project direct drag link)
pod init
open -aXcode podfile (if its already open add your pod file name ex:alamofire4.3)
pod install
pod update
Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:
int *fun()
{
int *point;
*point=12; <<<<<< your program crashed here.
return point;
}
The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.
Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.
int *fun()
{
int point;
point = 12;
return (&point);
}
or almost identically:
int *fun()
{
int point;
int *point_ptr;
point_ptr = &point;
*point_ptr = 12;
return (point_ptr);
}
Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:
int *fun()
{
static int point;
int *point_ptr;
point_ptr = &point;
*point_ptr = 12;
return (point_ptr);
}
or
int *fun()
{
static int point;
point = 12;
return (&point);
}
As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.
To run your script under the Perl debugger you should use the -d
switch:
perl -d script.pl
But Perl is flexible. It supplies some hooks, and you may force the debugger to work as you want
So to use different debuggers you may do:
perl -d:DebugHooks::Terminal script.pl
# OR
perl -d:Trepan script.pl
Look these modules here and here.
There are several most interesting Perl modules that hook into Perl debugger internals: Devel::NYTProf and Devel::Cover
And many others.
I need the two parts of string, so, regex lookbehind help me with this.
const full_name = 'Maria do Bairro';_x000D_
const [first_name, last_name] = full_name.split(/(?<=^[^ ]+) /);_x000D_
console.log(first_name);_x000D_
console.log(last_name);
_x000D_
To set the class when clicking on a div immediately within the .container element, you could use:
<script>
$('.container>div').click(function () {
$(this).addClass('whatever')
});
</script>
This is my two cents:
$('#container_element').scroll( function(){
console.log($(this).scrollTop()+' + '+ $(this).height()+' = '+ ($(this).scrollTop() + $(this).height()) +' _ '+ $(this)[0].scrollHeight );
if($(this).scrollTop() + $(this).height() == $(this)[0].scrollHeight){
console.log('bottom found');
}
});
You can create your own specialised content types. For example one for Json content and one for Xml content (then just assign them to the HttpResponseMessage.Content):
public class JsonContent : StringContent
{
public JsonContent(string content)
: this(content, Encoding.UTF8)
{
}
public JsonContent(string content, Encoding encoding)
: base(content, encoding, "application/json")
{
}
}
public class XmlContent : StringContent
{
public XmlContent(string content)
: this(content, Encoding.UTF8)
{
}
public XmlContent(string content, Encoding encoding)
: base(content, encoding, "application/xml")
{
}
}
Based @RBT's answer above, I tried Postman native app and want to give a couple of additional details.
In the latest postman desktop app, you can find the cookies option on the extreme right:
You can see the cookies for your localhost (these cookies are linked with the cookies in your chrome browser, although the app is running natively). Also you can set the cookies for a particular domain too.
You can enable NuGet packages and update you dlls. so that it work. or you can update the package manually by going through the package manager in your vs if u know which version you require for your solution.
$('.date').each(function (e) {
if ($(this).attr('disabled') != 'disabled') {
$(this).attr('readOnly', 'true');
$(this).css('cursor', 'pointer');
$(this).css('color', '#5f5f5f');
}
});
I don't think this is OP's problem, but if you're like me, you ran into this error while you were trying to play around with git plumbing commands (update-index
& cat-file
) without ever actually committing anything in the first place. So try committing something (git commit -am 'First commit'
) and your problem should be solved.
I've found out the solution! Thanks to Firebug ;)
//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event
//V2 version is:
GEvent.trigger(markers[i], 'click');
//V3 version is:
google.maps.event.trigger(markers[i], 'click');
Use:
String str = "whatever";
str = str.replaceAll("[,.]", "");
replaceAll takes a regular expression. This:
[,.]
...looks for each comma and/or period.
Can you try enabling Hyper-V manually, and potentially creating and running a Hyper-V VM manually? Details:
In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.
glutSolidSphere
is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?
#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>
// your framework of choice here
class SolidSphere
{
protected:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
public:
SolidSphere(float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = x;
*n++ = y;
*n++ = z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
}
}
void draw(GLfloat x, GLfloat y, GLfloat z)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x,y,z);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
glPopMatrix();
}
};
SolidSphere sphere(1, 12, 24);
void display()
{
int const win_width = …; // retrieve window dimensions from
int const win_height = …; // framework of choice here
float const win_aspect = (float)win_width / (float)win_height;
glViewport(0, 0, win_width, win_height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
#ifdef DRAW_WIREFRAME
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
sphere.draw(0, 0, -5);
swapBuffers();
}
int main(int argc, char *argv[])
{
// initialize and register your framework of choice here
return 0;
}
I know this isn't a direct answer to your question but it does offer one solution to your problem. Python 2.7.9 includes PIP and SetupTools, if you update to this version you will have one solution to your problem.
You can execute commands in parallel with start
like this:
start "" ping myserver
start "" nslookup myserver
start "" morecommands
They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.
Hope this helps!
This uses parameter substitution and takes care of the single value list case:
l = [1,5,8]
get_operator = lambda x: '=' if len(x) == 1 else 'IN'
get_value = lambda x: int(x[0]) if len(x) == 1 else x
query = 'SELECT * FROM table where id ' + get_operator(l) + ' %s'
cursor.execute(query, (get_value(l),))
according to High Performance MySQL book:
VARCHAR stores variable-length character strings and is the most common string data type. It can require less storage space than fixed-length types, because it uses only as much space as it needs (i.e., less space is used to store shorter values). The exception is a MyISAM table created with ROW_FORMAT=FIXED, which uses a fixed amount of space on disk for each row and can thus waste space. VARCHAR helps performance because it saves space.
CHAR is fixed-length: MySQL always allocates enough space for the specified number of characters. When storing a CHAR value, MySQL removes any trailing spaces. (This was also true of VARCHAR in MySQL 4.1 and older versions—CHAR and VAR CHAR were logically identical and differed only in storage format.) Values are padded with spaces as needed for comparisons.
I believe SET
is ANSI standard whereas the SELECT
is not. Also note the different behavior of SET
vs. SELECT
in the example below when a value is not found.
declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */
set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */
The path to the SDK is:
C:\Users\USERNAME\AppData\Local\Android\sdk
This can be used in Eclipse after you replace USERNAME with your Windows user name.
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
Take a Look at this Bundle for Laravel that I Made Recently !
src/googlemap.php
Pls Read the readme file first and don't forget to pass different ID if you want to have multiple Maps in one page
No one has mentioned the obvious:
var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);
This might mean a little less polling. If you watch both name + age
(for this) and name
(elsewhere) then I assume Angular will effectively look at name
twice to see if it's dirty.
It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.
And you can watch the values in different ways if you need to:
$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);
$watchGroup
is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.
If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.
My solution:
export class DashboardManagementComponent implements OnInit {
_cols = 5;
_rows = 10;
constructor() { }
ngOnInit() {
}
get cols() {
return Array(this._cols).fill(null).map((el, index) => index);
}
get rows() {
return Array(this._rows).fill(null).map((el, index) => index);
}
In html:
<div class="charts-setup">
<div class="col" *ngFor="let col of cols; let colIdx = index">
<div class="row" *ngFor="let row of rows; let rowIdx = index">
Col: {{colIdx}}, row: {{rowIdx}}
</div>
</div>
</div>
You can do that with a single statement and a subquery in nearly all relational databases.
INSERT INTO targetTable(field1)
SELECT field1
FROM myTable
WHERE NOT(field1 IN (SELECT field1 FROM targetTable))
Certain relational databases have improved syntax for the above, since what you describe is a fairly common task. SQL Server has a MERGE
syntax with all kinds of options, and MySQL has optional INSERT OR IGNORE
syntax.
Edit: SmallSQL's documentation is fairly sparse as to which parts of the SQL standard it implements. It may not implement subqueries, and as such you may be unable to follow the advice above, or anywhere else, if you need to stick with SmallSQL.
You're applying transitions only to the :hover
pseudo-class, and not to the element itself.
.item {
height:200px;
width:200px;
background:red;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-ms-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
.item:hover {
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Demo: http://jsfiddle.net/7uR8z/6/
If you don't want the transition to affect the mouse-over
event, but only mouse-out
, you can turn transitions off for the :hover
state :
.item:hover {
-webkit-transition: none;
-moz-transition: none;
-ms-transition: none;
-o-transition: none;
transition: none;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
diplay: block;
have no any effect
positionin also works very strange accodringly to frontend foundamentals, so be careful
body:before{
content:url(https://i.imgur.com/LJvMTyw.png);
transform: scale(.3);
position: fixed;
left: 50%;
top: -6%;
background: white;
}
Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.
For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.
Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called
"java.util.NoSuchElementException: No line found".
If you have to call "sc.nextLine()" n times, then you have to have at least n lines.
Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.
Try to add export PATH=$PATH:/home/me/play
in ~/.bashrc file.
I think we can write this fewer styles, without changing the existing color. The following worked for me (in Bootstrap 3.2.0)
.navbar-nav > li > a { padding-top: 5px !important; padding-bottom: 5px !important; }
.navbar { min-height: 32px !important; }
.navbar-brand { padding-top: 5px; padding-bottom: 10px; padding-left: 10px; }
The last one ('navbar-brand') is actually needed only if you have text as your 'brand' name.
I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.
Try this:
Option Explicit
Sub DoIHavePercentSymbol()
Dim rng As Range
Set rng = ActiveCell
Do While rng.Value <> Empty
If InStr(rng.Value, "%") = 0 Then
MsgBox "I know nothing about percentages!"
Set rng = rng.Offset(1)
rng.Select
Else
MsgBox "I contain a % symbol!"
Set rng = rng.Offset(1)
rng.Select
End If
Loop
End Sub
InStr
will return the number of times your search text appears in the string. I changed your if
test to check for no matches first.
The message boxes and the .Selects
are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.
First create a standalone commit with just a rename.
Then any eventual changes to the file content put in the separate commit.
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.
You must load the image and read the bytes from it. Then put these bytes into the JSON object.
read.table
wants to return a data.frame
, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE )
to fill in the blanks.
e.g.
read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
# V1 V2 V3
#1 Element1 Element2
#2 Element5 Element6 Element7
A note on whether or not to set header = FALSE
... read.table
tries to automatically determine if you have a header row thus:
header
is set toTRUE
if and only if the first row contains one fewer field than the number of columns
This is certainly something that has a lot of traps. I was working with Paolo Bergantino's answer, and realising that even that has some limitations. I found working with string representations of dates a good place to quickly find some of the main problems. Start with an input string like this:
'12-2-2019 5:1:48.670'
and set up Paolo's function like this:
function count(re, str) {
if (typeof re !== "string") {
return 0;
}
re = (re === '.') ? ('\\' + re) : re;
var cre = new RegExp(re, 'g');
return ((str || '').match(cre) || []).length;
}
I wanted the regular expression to be passed in, so that the function is more reusable, secondly, I wanted the parameter to be a string, so that the client doesn't have to make the regex, but simply match on the string, like a standard string utility class method.
Now, here you can see that I'm dealing with issues with the input. With the following:
if (typeof re !== "string") {
return 0;
}
I am ensuring that the input isn't anything like the literal 0
, false
, undefined
, or null
, none of which are strings. Since these literals are not in the input string, there should be no matches, but it should match '0'
, which is a string.
With the following:
re = (re === '.') ? ('\\' + re) : re;
I am dealing with the fact that the RegExp constructor will (I think, wrongly) interpret the string '.'
as the all character matcher \.\
Finally, because I am using the RegExp constructor, I need to give it the global 'g'
flag so that it counts all matches, not just the first one, similar to the suggestions in other posts.
I realise that this is an extremely late answer, but it might be helpful to someone stumbling along here. BTW here's the TypeScript version:
function count(re: string, str: string): number {
if (typeof re !== 'string') {
return 0;
}
re = (re === '.') ? ('\\' + re) : re;
const cre = new RegExp(re, 'g');
return ((str || '').match(cre) || []).length;
}
To perform a linear regression between two vectors x
and y
follow these steps:
[p,err] = polyfit(x,y,1); % First order polynomial
y_fit = polyval(p,x,err); % Values on a line
y_dif = y - y_fit; % y value difference (residuals)
SSdif = sum(y_dif.^2); % Sum square of difference
SStot = (length(y)-1)*var(y); % Sum square of y taken from variance
rsq = 1-SSdif/SStot; % Correlation 'r' value. If 1.0 the correlelation is perfect
For x=[10;200;7;150]
and y=[0.001;0.45;0.0007;0.2]
I get rsq = 0.9181
.
Reference URL: http://www.mathworks.com/help/matlab/data_analysis/linear-regression.html
I just had the same problem and...
declare @userId uniqueidentifier
set @userId = (select top 1 UserId from aspnet_Users)
or even shorter:
declare @userId uniqueidentifier
SELECT TOP 1 @userId = UserId FROM aspnet_Users
For me I had to put the whole interval in single quotes not just the value of the interval.
select id,
title,
created_at + interval '1 day' * claim_window as deadline from projects
Instead of
select id,
title,
created_at + interval '1' day * claim_window as deadline from projects
If you just want to get the path to a certain action, use UrlHelper
:
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);
if you want to create a hyperlink:
string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);
Intellisense will give you the meaning of each of the parameters.
Update from comments: controller already has a UrlHelper
:
string url = this.Url.Action("About", "Home", null);
Async functions are not supported by Node versions older than version 7.6.
You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.
That said, the current (2018) LTS version of Node.js is 8.x, so if you are using an earlier version you should very strongly consider upgrading.
The simplest way is like this:
import os
retvalue = os.popen("ps -p 2993 -o time --no-headers").readlines()
print retvalue
This will be returned as a list
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
You can try finishAffinity()
, it closes all current activities and works on and above Android 4.1
To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:
Whichever of those you choose, your record will look like the following:
Record: ALIAS
or ANAME
Name: empty or @
Target: example.com.herokudns.com.
That's all you need.
However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.
If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www
to http://example.com
.
If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.
To handle the redirects at the application level, you'll need to:
heroku domains:add example.com
and heroku domains:add www.example.com
)www
pointing to www.example.com.herokudns.com.
SECURE_SSL_REDIRECT
to True
)Check out this post from DNSimple for more.
Also you can use this
private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
it's the most simple method
Create docker image with openssh-server
preinstalled:
FROM ubuntu:16.04
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:screencast' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]
Build the image using:
$ docker build -t eg_sshd .
Run a test_sshd
container:
$ docker run -d -P --name test_sshd eg_sshd
$ docker port test_sshd 22
0.0.0.0:49154
Ssh to your container:
$ ssh [email protected] -p 49154
# The password is ``screencast``.
root@f38c87f2a42d:/#
Source: https://docs.docker.com/engine/examples/running_ssh_service/#build-an-eg_sshd-image
I had a similar issue when working on local. You url is going to be the path to the local file e.g. file:///Users/PeterP/Desktop/folder/index.html.
Please note that I am on a MAC.
I got round this by installing http-server globally. https://www.npmjs.com/package/http-server
Steps:
npm install http-server -g
http-server ~/Desktop/folder/
PS: I assume you have node installed, otherwise you wont get very far running npm commands.
Quick note: Check if you have other Python versions, if you have removed them, make sure you did that right. If you have Miniconda on your system then Python will not be removed easily.
What worked for me: removed other Python versions and the Miniconda, reinstalled Python and the matplotlib library and everything worked great.
window.location.replace
is the best way to emulate a redirect:
function ShowComments(){
var movieShareId = document.getElementById('movieId');
window.location.replace("/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/");
}
More information about why window.location.replace
is the best javascript redirect can be found right here.
I encountered similar situations like yours that I am using python3.7 and django 2.1 in virtualenv on mac osx. Try to run command:
pip install mysql-python
pip install pymysql
And edit __init__.py
file in your project folder and add following:
import pymysql
pymysql.install_as_MySQLdb()
Then run: python3 manage.py runserver
or python manage.py runserver
Try this
#include <stdio.h>
struct context;
struct funcptrs{
void (*func0)(struct context *ctx);
void (*func1)(void);
};
struct context{
struct funcptrs fps;
};
void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }
void getContext(struct context *con){
con->fps.func0 = func0;
con->fps.func1 = func1;
}
int main(int argc, char *argv[]){
struct context c;
c.fps.func0 = func0;
c.fps.func1 = func1;
getContext(&c);
c.fps.func0(&c);
getchar();
return 0;
}
I tried this, but the query won't run telling me my field is invalid in the select statement because it is not contained in either an aggregate function or the GROUP BY clause. It's forcing me to keep it there. Is there a way around this?
You need to do a self-join. You can't both aggregate and preserve non-aggregated data in the same subquery. E.g.
select q2.AccountNumber, q2.Bill, q2.BillDate, q1.BillSum
from
(
SELECT AccountNumber, SUM(Bill) as BillSum
FROM Table1
GROUP BY AccountNumber
) q1,
(
select AccountNumber, Bill, BillDate
from table1
) q2
where q1.AccountNumber = q2.AccountNumber
The Uri.parse(extras.getString("imageUri"))
was causing an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference
So I changed to the following:
intent.putExtra("imageUri", imageUri)
and
Uri uri = (Uri) getIntent().get("imageUri");
This solved the problem.
I know this is old but I think this will help anyone else who comes looking...
SELECT CAST(COUNT(ProductID) AS bit) AS [EXISTS] FROM Products WHERE(ProductID = @ProductID)
This will ALWAYS return TRUE if exists and FALSE if it doesn't (as opposed to no row).
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
select * from my_table where my_field Like '[a-z][a-z]%'
Using gcc 3.4 and 4.1 on very large trees (sometimes making use of distcc), I have yet to see any speed up when using #pragma once in lieu of, or in combination with standard include guards.
I really don't see how its worth potentially confusing older versions of gcc, or even other compilers since there's no real savings. I have not tried all of the various de-linters, but I'm willing to bet it will confuse many of them.
I too wish it had been adopted early on, but I can see the argument "Why do we need that when ifndef works perfectly fine?". Given C's many dark corners and complexities, include guards are one of the easiest, self explaining things. If you have even a small knowledge of how the preprocessor works, they should be self explanatory.
If you do observe a significant speed up, however, please update your question.
All the above answers are correct. This answer of mine below can be helpful if someone needs it. I have seen this requirement in many questions which we are solving using C.
log2 (x) = logy (x) / logy (2)
However, if you are using C language and you want the result in integer, you can use the following:
int result = (int)(floor(log(x) / log(2))) + 1;
Hope this helps.
It's just a namespace definition to avoid collision of class names. The com.domain.package.Class
is an established Java convention wherein the namespace is qualified with the company domain in reverse.
Here is a "concrete" (and possibly useful) example of how, why, and when to use these handy, yet unsightly constructs...
Xcode uses a "global" "user default" to decide which XCTestObserver
class spews it's heart out to the beleaguered console.
In this example... when I implicitly load this psuedo-library, let's call it... libdemure.a
, via a flag in my test target á la..
OTHER_LDFLAGS = -ldemure
I want to..
At load (ie. when XCTest
loads my test bundle), override the "default" XCTest
"observer" class... (via the constructor
function) PS: As far as I can tell.. anything done here could be done with equivalent effect inside my class' + (void) load { ... }
method.
run my tests.... in this case, with less inane verbosity in the logs (implementation upon request)
Return the "global" XCTestObserver
class to it's pristine state.. so as not to foul up other XCTest
runs which haven't gotten on the bandwagon (aka. linked to libdemure.a
). I guess this historically was done in dealloc
.. but I'm not about to start messing with that old hag.
So...
#define USER_DEFS NSUserDefaults.standardUserDefaults
@interface DemureTestObserver : XCTestObserver @end
@implementation DemureTestObserver
__attribute__((constructor)) static void hijack_observer() {
/*! here I totally hijack the default logging, but you CAN
use multiple observers, just CSV them,
i.e. "@"DemureTestObserverm,XCTestLog"
*/
[USER_DEFS setObject:@"DemureTestObserver"
forKey:@"XCTestObserverClass"];
[USER_DEFS synchronize];
}
__attribute__((destructor)) static void reset_observer() {
// Clean up, and it's as if we had never been here.
[USER_DEFS setObject:@"XCTestLog"
forKey:@"XCTestObserverClass"];
[USER_DEFS synchronize];
}
...
@end
Without the linker flag... (Fashion-police swarm Cupertino demanding retribution, yet Apple's default prevails, as is desired, here)
WITH the -ldemure.a
linker flag... (Comprehensible results, gasp... "thanks constructor
/destructor
"... Crowd cheers)
For your case solution is :
php artisan cache:clear
php artisan route:cache
Optimizing Route Loading is a must on production :
If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:
php artisan route:cache
This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.
Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.
Laravel 5 clear cache from route, view, config and all cache data from application
I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.
Reoptimized class loader:
php artisan optimize
Clear Cache facade value:
php artisan cache:clear
Clear Route cache:
php artisan route:cache
Clear View cache:
php artisan view:clear
Clear Config cache:
php artisan config:cache
with leading zero for day and month
var pattern =/^(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})$/;
and with both leading zero/without leading zero for day and month
var pattern =/^(0?[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0?[1-9]|1[0-2])\/([0-9]{4})$/;
if you use an assignment operator but use it in wrong way or in wrong place,
then you'll get this types of errors!
suppose if you type:
p+1=p; you will get the error!!
you will get the same error for this:
if(ch>='a' && ch='z')
as you see can see that I i tried to assign in if() statement!!!
how silly I am!!! right??
ha ha
actually i forgot to give less then(<) sign
if(ch>='a' && ch<='z')
and got the error!!
You may be using old version of Mysql but surely you can use
DELETE FROM konta WHERE taken <> ''
But there are many other options available. You can try the following ones
DELETE * from konta WHERE strcmp(taken, '') <> 0;
DELETE * from konta where NOT (taken = '');
You need the data to be in "tall" format instead of "wide" for ggplot2. "wide" means having an observation per row with each variable as a different column (like you have now). You need to convert it to a "tall" format where you have a column that tells you the name of the variable and another column that tells you the value of the variable. The process of passing from wide to tall is usually called "melting". You can use tidyr::gather
to melt your data frame:
library(ggplot2)
library(tidyr)
test_data <-
data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
date = seq(as.Date("2002-01-01"), by="1 month", length.out=100)
)
test_data %>%
gather(key,value, var0, var1) %>%
ggplot(aes(x=date, y=value, colour=key)) +
geom_line()
Just to be clear the data
that ggplot
is consuming after piping it via gather
looks like this:
date key value
2002-01-01 var0 100.00000
2002-02-01 var0 115.16388
...
2007-11-01 var1 114.86302
2007-12-01 var1 119.30996
I got this problem as well using the drupal 7 Location module. Autofilling all empty locations resulted in this error. Executing one of the requests to the location api manually resulted in this error in the returned JSON:
"Browser API keys cannot have referer restrictions when used with this API."
Resolving the problem then was easy: create a new key without any restrictions and use it only for Geocoding.
Note for those new to google api keys: by restrictions they mean limiting requests using an api key to specific domains / subdomains. (eg. only request from http://yourdomain.com are allowed).
int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);
Encode.php
<h1>Encode HTML CODE</h1>
<form action='htmlencodeoutput.php' method='post'>
<textarea rows='30' cols='100'name='inputval'></textarea>
<input type='submit'>
</form>
htmlencodeoutput.php
<?php
$code=bin2hex($_POST['inputval']);
$spilt=chunk_split($code,2,"%");
$totallen=strlen($spilt);
$sublen=$totallen-1;
$fianlop=substr($spilt,'0', $sublen);
$output="<script>
document.write(unescape('%$fianlop'));
</script>";
?>
<textarea rows='20' cols='100'><?php echo $output?> </textarea>
You can encode HTML like this .
To hide status bar for each individual view controller programmatically, use any of the following two procedures:
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
-(BOOL)prefersStatusBarHidden {
return YES;
}
To hide status bar for the entire application, we should follow the given below procedure:
You should add this value to plist: "View controller-based status bar appearance" and set it to "NO".
(Update: overlooked a fault in the matter, I have corrected)
(Update2: I wrote from memory the code screwed up, repaired it)
(Update3: check on SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150)
,Questions nvarchar(100)
,Answer nvarchar(100)
)
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
inner join deleted d on i.BusinessUnit = d.BusinessUnit
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
FROM
deleted d
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
delete Derived_Values;
and then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
Record Count: 0;
BUSINESSUNIT QUESTIONS ANSWER
Updated Record -- After Update Trigger.BU1 Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1 Q11 A11
Updated Record -- After Update Trigger.BU1 Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1 Q12 A12
Updated Record -- After Update Trigger.BU2 Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2 Q21 A21
Updated Record -- After Update Trigger.BU2 Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2 Q22 A22
(Update4: If you want to sync: SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
CREATE TRIGGER trgAfterInsert ON [Derived_Values]
FOR INSERT
AS
begin
insert
[Derived_Values_Test]
(BusinessUnit,Questions,Answer)
SELECT
i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
end
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
update
[Derived_Values_Test]
set
--BusinessUnit = i.BusinessUnit
--,Questions = i.Questions
Answer = i.Answer
from
[Derived_Values]
inner join inserted i
on
[Derived_Values].BusinessUnit = i.BusinessUnit
and
[Derived_Values].Questions = i.Questions
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR DELETE
AS
begin
delete
[Derived_Values_Test]
from
[Derived_Values_Test]
inner join deleted d
on
[Derived_Values_Test].BusinessUnit = d.BusinessUnit
and
[Derived_Values_Test].Questions = d.Questions
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
--delete Derived_Values;
And then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
You might want to take a look at a similar question posted on Stack Overflow. It uses the .apply()
method to accomplish this.
The short answer is that setting grid-auto-rows: 1fr;
on the grid container solves what was asked.
If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext
. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.
The b-list has a good introduction to context processors.
Edit (I seem to have been confused about what the actual question was):
You'll notice that password_reset
takes a named parameter called template_name
:
def password_reset(request, is_admin_site=False,
template_name='registration/password_reset_form.html',
email_template_name='registration/password_reset_email.html',
password_reset_form=PasswordResetForm,
token_generator=default_token_generator,
post_reset_redirect=None):
Check password_reset for more information.
... thus, with a urls.py like:
from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset
urlpatterns = patterns('',
(r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
...
)
django.contrib.auth.views.password_reset
will be called for URLs matching '/accounts/password/reset'
with the keyword argument template_name = 'my_templates/password_reset.html'
.
Otherwise, you don't need to provide any context as the password_reset
view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax
error and look through the stack trace find the frame with a local variable named context
. If you want to modify the context then what I said above about context processors is probably the way to go.
In summary: what do you need to do to use your own template? Provide a template_name
keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.
This will do:
#include <fstream>
#include <iostream>
using std::fstream;
int main(int argc, char *argv[]) {
fstream file;
file.open("test.txt",std::ios::out);
file << fflush;
file.close();
}
If you use IntelliJ IDEA you can browse all maven goals/tasks (including plugins) in Maven Projects
tab:
Take a look at Job Control on UNIX systems
If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs
and kill -9 %<job #>
to kill it. The '-9' is a type of signal. You can man kill
to see a list of signals.
No, don't do it that way.
From your Eclipse workspace, right click your project on the left pane -> Properties -> Java Build Path -> Add Jars -> add your jars here.
Tadaa!! :)
Try this below code it is also works well in angular 2
<span>{{current_date | date: 'yyyy-MM-dd'}}</span>
You should use this:
"\n"
You also might wanna have a look at PHP EOL.
codeblocks.It seems to be good
A bit late to the party, but I think the most succinct way to find just the name of your current execution context would be
current_folder_path, current_folder_name = os.path.split(os.getcwd())
Removing CocoaPods from a project is possible, but not currently automated by the CLI. First thing, if the only issue you have is not being able to use an xcworkspace
you can use CocoaPods with just xcodeproj
s by using the --no-integrate
flag which will produce the Pods.xcodeproj
but not a workspace. Then you can add this xcodeproj
as a subproject to your main xcodeproj
.
If you really want to remove all CocoaPods integration you need to do a few things:
NOTE editing some of these things if done incorrectly could break your main project. I strongly encourage you to check your projects into source control just in case. Also these instructions are for CocoaPods version 0.39.0
, they could change with new versions.
Podfile
Podfile.lock
and your Pods
directory)xcworkspace
xcodeproj
file, delete the references to Pods.xcconfig
and libPods.a
(in the Frameworks
group)Build Phases
delete the Copy Pods Resources
, Embed Pods Frameworks
and Check Pods Manifest.lock
phases.After those steps you should be set with a single xcodeproj
that existed before you integrated CocoaPods. If I missed anything let me know and I will edit this.
Also we're always looking for suggestions for how to improve CocoaPods so if you have an issues please submit them in our issue tracker so we can come up with a way to fix them!
EDIT
As shown by Jack Wu in the comments there is a third party CocoaPods plugin that can automate these steps for you. It can be found here. Note that it is a third party plugin and might not always be updated when CocoaPods is. Also note that it is made by a CocoaPods core team member so that problem won't be a problem.
If you are using the elastic search 7.7 or above version then follow below command.
curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk? pretty&refresh" --data-binary @"/Users/waseem.khan/waseem/elastic/account.json"
On above file path is /Users/waseem.khan/waseem/elastic/account.json
.
If you are using elastic search 6.x version then you can use the below command.
curl -X POST localhost:9200/bank/_bulk?pretty&refresh --data-binary @"/Users/waseem.khan/waseem/elastic/account.json" -H 'Content-Type: application/json'
Note: Make sure in your .json file at the end you will add the one empty line otherwise you will be getting below exception.
"error" : {
"root_cause" : [
{
"type" : "illegal_argument_exception",
"reason" : "The bulk request must be terminated by a newline [\n]"
}
],
"type" : "illegal_argument_exception",
"reason" : "The bulk request must be terminated by a newline [\n]"
},
`enter code here`"status" : 400
The menu location seems to have changed to:
Query Designer --> Pane --> SQL
This should print the list of positions without the -1
at the end that Peter Lawrey's solution has had.
int index = word.indexOf(guess);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index + 1);
}
It can also be done as a for
loop:
for (int index = word.indexOf(guess);
index >= 0;
index = word.indexOf(guess, index + 1))
{
System.out.println(index);
}
[Note: if guess
can be longer than a single character, then it is possible, by analyzing the guess
string, to loop through word
faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]
Sounds like you want to do an "upsert". MongoDB has built-in support for this. Pass an extra parameter to your update() call: {upsert:true}. For example:
key = {'key':'value'}
data = {'key2':'value2', 'key3':'value3'};
coll.update(key, data, upsert=True); #In python upsert must be passed as a keyword argument
This replaces your if-find-else-update block entirely. It will insert if the key doesn't exist and will update if it does.
Before:
{"key":"value", "key2":"Ohai."}
After:
{"key":"value", "key2":"value2", "key3":"value3"}
You can also specify what data you want to write:
data = {"$set":{"key2":"value2"}}
Now your selected document will update the value of "key2" only and leave everything else untouched.
In case of .css method in jQuery for !important rule will not apply.
In this case we should use .attr function.
For Example:
If you want to add style as below:
<div id='voltaic_holder' style='position:absolute;top:-75px !important'>
You should use:
$("#voltaic_holder").attr("style", "position:absolute;top:-75px !important");
Hope it helps some one.
You can use pygame's surfarray module. This module has a 3d pixel array returning method called pixels3d(surface). I've shown usage below:
from pygame import surfarray, image, display
import pygame
import numpy #important to import
pygame.init()
image = image.load("myimagefile.jpg") #surface to render
resolution = (image.get_width(),image.get_height())
screen = display.set_mode(resolution) #create space for display
screen.blit(image, (0,0)) #superpose image on screen
display.flip()
surfarray.use_arraytype("numpy") #important!
screenpix = surfarray.pixels3d(image) #pixels in 3d array:
#[x][y][rgb]
for y in range(resolution[1]):
for x in range(resolution[0]):
for color in range(3):
screenpix[x][y][color] += 128
#reverting colors
screen.blit(surfarray.make_surface(screenpix), (0,0)) #superpose on screen
display.flip() #update display
while 1:
print finished
I hope been helpful. Last word: screen is locked for lifetime of screenpix.
One quick option is to use the MediaTypeMapping specialization. Here is an example of using QueryStringMapping in the Application_Start event:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("a", "b", "application/json"));
Now whenever the url contains the querystring ?a=b in this case, Json response will be shown in the browser.
i didn't have time to dig why the setBounds() method is not working on bitmap drawable as expected but i have little tweaked @androbean-studio solution to do what setBounds should do...
/**
* Created by ceph3us on 23.05.17.
* file belong to pl.ceph3us.base.android.drawables
* this class wraps drawable and forwards draw canvas
* on it wrapped instance by using its defined bounds
*/
public class WrappedDrawable extends Drawable {
private final Drawable _drawable;
protected Drawable getDrawable() {
return _drawable;
}
public WrappedDrawable(Drawable drawable) {
super();
_drawable = drawable;
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
//update bounds to get correctly
super.setBounds(left, top, right, bottom);
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setBounds(left, top, right, bottom);
}
}
@Override
public void setAlpha(int alpha) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setAlpha(alpha);
}
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setColorFilter(colorFilter);
}
}
@Override
public int getOpacity() {
Drawable drawable = getDrawable();
return drawable != null
? drawable.getOpacity()
: PixelFormat.UNKNOWN;
}
@Override
public void draw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.draw(canvas);
}
}
@Override
public int getIntrinsicWidth() {
Drawable drawable = getDrawable();
return drawable != null
? drawable.getBounds().width()
: 0;
}
@Override
public int getIntrinsicHeight() {
Drawable drawable = getDrawable();
return drawable != null ?
drawable.getBounds().height()
: 0;
}
}
usage:
// get huge drawable
final Drawable drawable = resources.getDrawable(R.drawable.g_logo);
// create our wrapper
WrappedDrawable wrappedDrawable = new WrappedDrawable(drawable);
// set bounds on wrapper
wrappedDrawable.setBounds(0,0,32,32);
// use wrapped drawable
Button.setCompoundDrawablesWithIntrinsicBounds(wrappedDrawable ,null, null, null);
results
The Best way and recommended way of comparing date in typescript
is:
var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();
if(today === reqDateVar){
// NOW
} else {
// Some other time
}
There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
// do something with key
};
};
Or a more structured way of handling it:
(function(d){
var modern = (d.addEventListener), event = function(obj, evt, fn){
if(modern) {
obj.addEventListener(evt, fn, false);
} else {
obj.attachEvent("on" + evt, fn);
}
}, code = function(e){
e = e || window.event;
return(e.keyCode || e.which);
}, init = function(){
event(d, "keypress", function(e){
var key = code(e);
// do stuff with key here
});
};
if(modern) {
d.addEventListener("DOMContentLoaded", init, false);
} else {
d.attachEvent("onreadystatechange", function(){
if(d.readyState === "complete") {
init();
}
});
}
})(document);
Considering for general bit length (though I have used specific type here), I tried to design simplistic algo as below. Simple and obvious check for 0,1,2 or <0 is required initially. Following is simple in sense that it doesn't try to use any existing maths functions. Most of the operator can be replaced with bit-wise operators. I haven't tested with any bench mark data though. I'm neither expert at maths or computer algorithm design in particular, I would love to see you pointing out problem. I know there is lots of improvement chances there.
int main()
{
unsigned int c1=0 ,c2 = 0;
unsigned int x = 0;
unsigned int p = 0;
int k1 = 0;
scanf("%d",&p);
if(p % 2 == 0) {
x = p/2;
}
else {
x = (p/2) +1;
}
while(x)
{
if((x*x) > p) {
c1 = x;
x = x/2;
}else {
c2 = x;
break;
}
}
if((p%2) != 0)
c2++;
while(c2 < c1)
{
if((c2 * c2 ) == p) {
k1 = 1;
break;
}
c2++;
}
if(k1)
printf("\n Perfect square for %d", c2);
else
printf("\n Not perfect but nearest to :%d :", c2);
return 0;
}
Might be it will help someone, 4 level and 2 child's on each level
Library.Include(a => a.Library.Select(b => b.Library.Select(c => c.Library)))
.Include(d=>d.Book.)
.Include(g => g.Library.Select(h=>g.Book))
.Include(j => j.Library.Select(k => k.Library.Select(l=>l.Book)))
If you are really concerned about the execution speed of your apply function and you have a huge dataset to work on, you could use swifter to make faster execution, here is an example for swifter on pandas dataframe:
import pandas as pd
import swifter
def fnc(m):
return m*3+4
df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
# apply a self created function to a single column in pandas
df["y"] = df.m.swifter.apply(fnc)
This will enable your all CPU cores to compute the result hence it will be much faster than normal apply functions. Try and let me know if it become useful for you.
For mocking static functions i was able to do it that way:
wrapper code snippet (not really functional, just for illustration)
class myWrapperClass ...
def myWrapperFunction (...) {
return theOriginalFunction (...)
}
of course having multiple such functions accumulated in a single wrapper class might be beneficial in terms of code reuse.
if you don't want to install homebrew (or any other package manager) just for installing maven, you can grab the binary from their site:
http://maven.apache.org/download.cgi
extract the content to a folder (e.g. /Applications/apache-maven-3.1.1
) with
$ tar -xvf apache-maven-3.1.1-bin.tar.gz
and finally adjust your ~/.bash_profile
with any texteditor you like to include
export M2_HOME=/Applications/apache-maven-3.1.1
export PATH=$PATH:$M2_HOME/bin
restart the terminal and test it with
$ mvn -version
Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-17 17:22:22+0200)
Maven home: /Applications/apache-maven-3.1.1
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: de_DE, platform encoding: MacRoman
OS name: "mac os x", version: "10.9", arch: "x86_64", family: "mac"
You can increase the capacity of the stack by the following :
import sys
sys.setrecursionlimit(10000)
One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.
url='http://www.google.com/blahblah'
try:
r = requests.get(url,timeout=3)
r.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah
vs
url='http://www.google.com/blahblah'
try:
r = requests.get(url,timeout=3)
r.raise_for_status()
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah
%UserProfile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
paste this in your address bar and enter, you will get all the files
just rename the files extension into the extension which u r looking.
ie. open command prompt then
C:\>cd %UserProfile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
then
C:\Users\User\AppData\Local\Google\Chrome\User Data\Default\Cache>ren *.* *.jpg
I had a requirement to search/match for version numbers, that follows maven convention or even just single digit. But no qualifier in any case. It was peculiar, it took me time then I came up with this:
'^[0-9][0-9.]*$'
This makes sure the version,
One drawback is that version can even end with '.' But it can handle indefinite length of version (crazy versioning if you want to call it that)
Matches:
If you are not unhappy with '.' ending, may be you can combine with endswith logic
OK I have answered my own question (but is it the best way?)
This is how to run a method when you click or tap on some text in a TextView:
package com.textviewy;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class TextyView extends Activity implements OnClickListener {
TextView t ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.TextView01);
t.setOnClickListener(this);
}
public void onClick(View arg0) {
t.setText("My text on click");
}
}
and my main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></ListView>
<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
<TextView android:text="This is my first text"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:textStyle="bold"
android:textSize="28dip"
android:editable = "true"
android:clickable="true"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
array_search('20120504', array_keys($your_array));
The "call" solution has some problems.
It fails with many different contents, as the parameters of a CALL
are parsed twice by the parser.
These lines will produce more or less strange problems
one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty
the end
Therefore you shouldn't use the value of %%a
with a call, better move it to a variable and then call a function with only the name of the variable.
@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
set "myVar=%%a"
call :processLine myVar
)
goto :eof
:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof
Even the first answer is absolutely brilliant, you probably want to only run script under sudo.
You have to specify the absolute path like:
sudo /home/user/example.sh
sudo ~/example.sh
(both are working)
THIS WONT WORK!
sudo /bin/sh example.sh
sudo example.sh
It will always return
sudo: bin/sh: command not found
sudo: example.sh: command not found
You need to place the \n
in double quotes.
Inside single quotes it is treated as 2 characters '\'
followed by 'n'
You need:
$str = str_replace("\n", '', $str);
A better alternative is to use PHP_EOL
as:
$str = str_replace(PHP_EOL, '', $str);
In the position where you want to add text, do:
Shift
+ Alt
+ down arrow
and select the lines you want. Then type. The text you type is inserted on all of the lines you selected.
Give selected
attribute to all options like this
$('#countries option').attr('selected', 'selected');
Usage:
$('#select_all').click( function() {
$('#countries option').attr('selected', 'selected');
});
In case you are using 1.6+, better option would be to use .prop()
instead of .attr()
$('#select_all').click( function() {
$('#countries option').prop('selected', true);
});
In foreach
loop instead of carBootSaleList
use carBootSaleList.data
.
You probably do not need answer anymore, but it could help someone.
UPDATE user_account student
SET (student.student_education_facility_id) = (
SELECT teacher.education_facility_id
FROM user_account teacher
WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE student.user_type = 'ROLE_STUDENT';
Assume that you have dynamic currency precision
value => 1.002431
currency precision => 3
`result => 1.002
CAST(Floor(your_float_value) AS VARCHAR) + '.' + REPLACE(STR(FLOOR((your_float_value FLOOR(your_float_value)) * power(10,cu_precision)), cu_precision), SPACE(1), '0')
<?= $form->field($model, 'hidden_Input')->hiddenInput(['id'=>'hidden_Input','class'=>'form-control','value'=>$token_name])->label(false)?>
or
<input type="hidden" name="test" value="1" />
Use This.
In Python, a list
is a dynamic array. You can create one like this:
lst = [] # Declares an empty list named lst
Or you can fill it with items:
lst = [1,2,3]
You can add items using "append":
lst.append('a')
You can iterate over elements of the list using the for
loop:
for item in lst:
# Do something with item
Or, if you'd like to keep track of the current index:
for idx, item in enumerate(lst):
# idx is the current idx, while item is lst[idx]
To remove elements, you can use the del command or the remove function as in:
del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list
Note, though, that one cannot iterate over the list and modify it at the same time; to do that, you should instead iterate over a slice of the list (which is basically a copy of the list). As in:
for item in lst[:]: # Notice the [:] which makes a slice
# Now we can modify lst, since we are iterating over a copy of it
another way to do is get the UriInfo instead of all the QueryParam
Then you will be able to get the queryParam as per needed in your code
@GET
@Path("/query")
public Response getUsers(@Context UriInfo info) {
String param_1 = info.getQueryParameters().getFirst("param_1");
String param_2 = info.getQueryParameters().getFirst("param_2");
return Response ;
}
My situation was similar to the Damo's one - some Products were added to the Pods project twice. The structure of my Podfile was:
# platform :ios, '11.0'
def shared_pods
use_frameworks!
pod 'SharedPod1'
end
target 'Target1' do
pod 'SomePod1'
shared_pods
end
target 'Target2' do
shared_pods
end
and all shared pods were added twice. Uncommenting of first line and then pod install
solved the problem.
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:
make -p
For instance:
%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
which expands
COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
This will also print # environment
data. Here, you will find GCC's include path among other useful info.
C_INCLUDE_PATH=/usr/include
In make, when it comes to search, the paths are many, the light is one... or something to that effect.
C_INCLUDE_PATH
is system-wide, set it in your shell's *.rc
.$(CPPFLAGS)
is for the preprocessor include path.VPATH = my_dir_to_search
... or even more specific
vpath %.c src
vpath %.h include
make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.
I was having trouble coloring rows in table using bootstrap table-striped class then realized delete table-striped class and do this in css file
tr:nth-of-type(odd)
{
background-color: red;
}
tr:nth-of-type(even)
{
background-color: blue;
}
The bootstrap table-striped class will over ride your selectors.
Someone pointed me to args4j lately which is annotation based. I really like it!
If you're open to using a third party library, this will work in Eclipse Collections:
int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);
Note: I am a committer for Eclipse Collections.
You need to include the appropriate header
#include <stdio.h>
If you're not sure which header a standard function is defined in, the function's man page will state this.
For those who using version 7.8.5, the Auto-indent settings is now located at "Settings" -> "Preferences..." -> "Auto-Completion".
Apache/HTTPD tends to be around in most enterprises or if you're using Centos/etc at home. So, if you have that around, you can do a proxy very easily to add the necessary CORS headers.
I have a blog post on this here as I suffered with it quite a few times recently. But the important bit is just adding this to your /etc/httpd/conf/httpd.conf file and ensuring you are already doing "Listen 80":
<VirtualHost *:80>
<LocationMatch "/SomePath">
ProxyPass http://target-ip:8080/SomePath
Header add "Access-Control-Allow-Origin" "*"
</LocationMatch>
</VirtualHost>
This ensures that all requests to URLs under your-server-ip:80/SomePath route to http://target-ip:8080/SomePath (the API without CORS support) and that they return with the correct Access-Control-Allow-Origin header to allow them to work with your web-app.
Of course you can change the ports and target the whole server rather than SomePath if you like.
Does it absolutely have to be 100% functional and fluent? If not, how about this, which is about as short as it gets:
Map<String, Integer> output = new HashMap<>();
input.forEach((k, v) -> output.put(k, Integer.valueOf(v));
(if you can live with the shame and guilt of combining streams with side-effects)
var yourobj={
"c":{
"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
},
"o":{
"v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
"e":[{"name":"lens cleaner","value":1}]
},
"h":{
"d":[{"name":"hdmi cable","value":1},
{"name":"hdtv essentials (hdtv cable setup)","value":1},
{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
my solution
var obj = [];
for(n1 in yourjson)
for(n1_1 in yourjson[n])
for(n1_2 in yourjson[n][n1_1])
obj[n1_2[name]] = n1_2[value];
Approved code
for(n1 in yourobj){
for(n1_1 in yourobj[n1]){
for(n1_2 in yourobj[n1][n1_1]){
for(n1_3 in yourobj[n1][n1_1][n1_2]){
obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
}
}
}
}
console.log(obj);
result
*You should use distinguish accessorizes when using [] method or dot notation
Quite simple with a closure:
def map = [
'iPhone':'iWebOS',
'Android':'2.3.3',
'Nokia':'Symbian',
'Windows':'WM8'
]
map.each{ k, v -> println "${k}:${v}" }
convert the NULL
values with empty string by wrapping it in COALESCE
"UPDATE table SET data = CONCAT(COALESCE(`data`,''), 'a')"
OR
Use CONCAT_WS instead:
"UPDATE table SET data = CONCAT_WS(',',data, 'a')"
NodeJS Solution:
In Nodejs you can get it via promises...
If you write this code, you can be sure that the page is fully loaded when you get to the then...
driver.get('www.sidanmor.com').then(()=> {
// here the page is fully loaded!!!
// do your stuff...
}).catch(console.log.bind(console));
If you write this code, you will navigate, and selenium will wait 3 seconds...
driver.get('www.sidanmor.com');
driver.sleep(3000);
// you can't be sure that the page is fully loaded!!!
// do your stuff... hope it will be OK...
From Selenium documentation:
this.get( url ) ? Thenable
Schedules a command to navigate to the given URL.
Returns a promise that will be resolved when the document has finished loading.
Since you're talking about financial figures, you DO NOT WANT to use floating-point arithmetic. You're better off using Decimal.
>>> from decimal import Decimal
>>> Decimal("33.505")
Decimal('33.505')
Text output formatting with new-style format()
(defaults to half-even rounding):
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.505")))
financial return of outcome 1 = 33.50
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.515")))
financial return of outcome 1 = 33.52
See the differences in rounding due to floating-point imprecision:
>>> round(33.505, 2)
33.51
>>> round(Decimal("33.505"), 2) # This converts back to float (wrong)
33.51
>>> Decimal(33.505) # Don't init Decimal from floating-point
Decimal('33.50500000000000255795384873636066913604736328125')
Proper way to round financial values:
>>> Decimal("33.505").quantize(Decimal("0.01")) # Half-even rounding by default
Decimal('33.50')
It is also common to have other types of rounding in different transactions:
>>> import decimal
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_DOWN)
Decimal('33.50')
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_UP)
Decimal('33.51')
Remember that if you're simulating return outcome, you possibly will have to round at each interest period, since you can't pay/receive cent fractions, nor receive interest over cent fractions. For simulations it's pretty common to just use floating-point due to inherent uncertainties, but if doing so, always remember that the error is there. As such, even fixed-interest investments might differ a bit in returns because of this.
VS10x Code Map That is very cool. Easy jumping to property, method. And easy expand collapse region and more.
You can either pass the parameter in the task constructor or when you call execute:
AsyncTask<Object, Void, MyTaskResult>
The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).
public class MyActivity extends AppCompatActivity {
TextView textView1;
TextView textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textView1 = (TextView) findViewById(R.id.textView1);
textView2 = (TextView) findViewById(R.id.textView2);
String input1 = "test";
boolean input2 = true;
int input3 = 100;
long input4 = 100000000;
new MyTask(input3, input4).execute(input1, input2);
}
private class MyTaskResult {
String text1;
String text2;
}
private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
private String val1;
private boolean val2;
private int val3;
private long val4;
public MyTask(int in3, long in4) {
this.val3 = in3;
this.val4 = in4;
// Do something ...
}
protected void onPreExecute() {
// Do something ...
}
@Override
protected MyTaskResult doInBackground(Object... params) {
MyTaskResult res = new MyTaskResult();
val1 = (String) params[0];
val2 = (boolean) params[1];
//Do some lengthy operation
res.text1 = RunProc1(val1);
res.text2 = RunProc2(val2);
return res;
}
@Override
protected void onPostExecute(MyTaskResult res) {
textView1.setText(res.text1);
textView2.setText(res.text2);
}
}
}
First of all install nodejs:
sudo apt-get install nodejs
Then install npm:
sudo apt-get install npm
Then install bower:
npm install -g bower
For any of the npm package tutorial visit: https://www.npmjs.com/
Here just search the package and you can find how to install, documentation and tutorials as well.
P.S. This is just a very common solution. If your problem still exists you can try the advanced one.
To formalize some of the approaches laid out above:
Create a function that operates on the rows of your dataframe like so:
def f(row):
if row['A'] == row['B']:
val = 0
elif row['A'] > row['B']:
val = 1
else:
val = -1
return val
Then apply it to your dataframe passing in the axis=1
option:
In [1]: df['C'] = df.apply(f, axis=1)
In [2]: df
Out[2]:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.
Edit
Here is the vectorized version
df['C'] = np.where(
df['A'] == df['B'], 0, np.where(
df['A'] > df['B'], 1, -1))
In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png
and drag in to the project.
Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:
I tested on Xcode 5 and an app was submitted without the missing retina icon warning.
If you are a Windows user, you may either remove or update your credentials in Credential Manager.
In Windows 10, go to the below path:
Control Panel → All Control Panel Items → Credential Manager
Or search for "credential manager" in your "Search Windows" section in the Start menu.
Then from the Credential Manager, select "Windows Credentials".
Credential Manager will show many items including your outlook and GitHub repository under "Generic credentials"
You click on the drop down arrow on the right side of your Git: and it will show options to edit and remove. If you remove, the credential popup will come next time when you fetch or pull. Or you can directly edit the credentials there.
The code works well for me.
$str = substr($str ,-(strlen($str)-1));
Maybe, contribute with answers too.
I tried neemzy's approach, but it didn't work for me using 1.2.0-rc.3. The script tag would be inserted into the DOM, but the javascript path would not be loaded. I suspect it was because the javascript i was trying to load was from a different domain/protocol. So I took a different approach, and this is what I came up with, using google maps as an example: (Gist)
angular.module('testApp', []).
directive('lazyLoad', ['$window', '$q', function ($window, $q) {
function load_script() {
var s = document.createElement('script'); // use global document since Angular's $document is weak
s.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
document.body.appendChild(s);
}
function lazyLoadApi(key) {
var deferred = $q.defer();
$window.initialize = function () {
deferred.resolve();
};
// thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
if ($window.attachEvent) {
$window.attachEvent('onload', load_script);
} else {
$window.addEventListener('load', load_script, false);
}
return deferred.promise;
}
return {
restrict: 'E',
link: function (scope, element, attrs) { // function content is optional
// in this example, it shows how and when the promises are resolved
if ($window.google && $window.google.maps) {
console.log('gmaps already loaded');
} else {
lazyLoadApi().then(function () {
console.log('promise resolved');
if ($window.google && $window.google.maps) {
console.log('gmaps loaded');
} else {
console.log('gmaps not loaded');
}
}, function () {
console.log('promise rejected');
});
}
}
};
}]);
I hope it's helpful for someone.
Here is a simple solution using the query-string
library.
const qs = require('query-string')
function addQuery(key, value) {
const q = qs.parse(location.search)
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
// if you are using Turbolinks
// add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)
If you are using react
without react-router
export function useAddQuery() {
const location = window.location;
const addQuery = useCallback(
(key, value) => {
const q = qs.parse(location.search);
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
},
[location]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
If you are using react
with react-router
export function useAddQuery() {
const location = useLocation();
const history = useHistory();
const addQuery = useCallback(
(key, value) => {
let pathname = location.pathname;
let searchParams = new URLSearchParams(location.search);
searchParams.set(key, value);
history.push({
pathname: pathname,
search: searchParams.toString()
});
},
[location, history]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
PS: qs
is the import from query-string
module.
I just took the default Android 3.1, and it was very slow, but since I realised my code was Android 2.3.3 compatible I switched to that. It's about 50% quicker and also the emulator looks more like my phone, and has a keyboard permanently displayed so that it is easier to use.
I would suggest extending TextView, and always using your custom TextView within your XML layouts or wherever you need a TextView. In your custom TextView, override setTypeface
@Override
public void setTypeface(Typeface tf, int style) {
//to handle bold, you could also handle italic or other styles here as well
if (style == 1){
tf = Typeface.createFromAsset(getContext().getApplicationContext().getAssets(), "MuseoSans700.otf");
}else{
tf = Typeface.createFromAsset(getContext().getApplicationContext().getAssets(), "MuseoSans500.otf");
}
super.setTypeface(tf, 0);
}
Just did this this morning. From a command prompt:
adb shell
cd /data/data/YOUR_PACKAGE_NAME/shared_prefs
rm * // to remove all shared preference files
rm YOUR_PREFS_NAME.xml // to remove a specific shared preference file
NOTE: This requires a rooted device such as the stock Android virtual devices, a Genymotion device, or an actual rooted handset/tablet, etc.
Using a subshell substitution to parse the words undoes all the work you are doing to put spaces together.
Try instead:
cat CSV_file | sed -n 1'p' | tr ',' '\n' | while read word; do
echo $word
done
That also increases parallelism. Using a subshell as in your question forces the entire subshell process to finish before you can start iterating over the answers. Piping to a subshell (as in my answer) lets them work in parallel. This matters only if you have many lines in the file, of course.
If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.
I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.
If you are going to call relative.py
directly and i.e. if you really want to import from a top level module you have to explicitly add it to the sys.path
list.
Here is how it should work:
# Add this line to the beginning of relative.py file
import sys
sys.path.append('..')
# Now you can do imports from one directory top cause it is in the sys.path
import parent
# And even like this:
from parent import Parent
If you think the above can cause some kind of inconsistency you can use this instead:
sys.path.append(sys.path[0] + "/..")
sys.path[0]
refers to the path that the entry point was ran from.
For me, restarting Eclipse got rid of this error!
Another option to transform the static method into a static Func or Action. For instance.
Original code:
class Math
{
public static int Add(int x, int y)
{
return x + y;
}
You want to "mock" the Add method, but you can't. Change the above code to this:
public static Func<int, int, int> Add = (x, y) =>
{
return x + y;
};
Existing client code doesn't have to change (maybe recompile), but source stays the same.
Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:
[TestMethod]
public static void MyTest()
{
Math.Add = (x, y) =>
{
return 11;
};
Put whatever logic you want in the method, or just return some hard-coded value, depending on what you're trying to do.
This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.
[edit] I suggest that you add the following Cleanup code to your Unit Test class:
[TestCleanup]
public void Cleanup()
{
typeof(Math).TypeInitializer.Invoke(null, null);
}
Add a separate line for each static class. What this does is, after the unit test is done running, it resets all the static fields back to their original value. That way other unit tests in the same project will start out with the correct defaults as opposed your mocked version.
In my case, i forgot minifyEnabled=true and shrinkResources=true in my debug buildType. I change these values to false, it's worked again!
Here is an another way find value index in complex array in javascript. Hope help somebody indeed. Let us assume we have a JavaScript array as following,
var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];
Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.
We can do that by iterating through the array and comparing value at the given key.
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
You can use the function to find index of a particular element as below,
var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);
Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).
If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp
If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.
Using pygame, you can open a window, get the surface as an array of pixels, and manipulate as you want from there. You'll need to copy your numpy array into the surface array, however, which will be much slower than doing actual graphics operations on the pygame surfaces themselves.
Use this one line query, replace desired_column_name by your column name.
SELECT TABLE_NAME FROM information_schema.columns WHERE column_name = 'desired_column_name';
As Abel said, ES Modules in Node >= 14 no longer have require
by default.
If you want to add it, put this code at the top of your file:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
Source: https://nodejs.org/api/modules.html#modules_module_createrequire_filename
Unfortunately, C++ does not allow you to directly get a callable object referring to an object and one of its member functions. &Foo::doSomething
gives you a "pointer to member function" which refers to the member function but not the associated object.
There are two ways around this, one is to use std::bind
to bind the "pointer to member function" to the this
pointer. The other is to use a lambda that captures the this
pointer and calls the member function.
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
std::function<void(void)> g = [this](){doSomething();};
I would prefer the latter.
With g++ at least binding a member function to this will result in an object three-pointers in size, assigning this to an std::function
will result in dynamic memory allocation.
On the other hand, a lambda that captures this
is only one pointer in size, assigning it to an std::function
will not result in dynamic memory allocation with g++.
While I have not verified this with other compilers, I suspect similar results will be found there.