You can use as below:
string selected = cmbbox.Text;
MessageBox.Show(selected);
I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:
Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.
Once you've got that, you can use a requests.Session()
instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.
Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.
Example
import requests
# Fill in your details here to be posted to the login form.
payload = {
'inUserName': 'username',
'inUserPass': 'password'
}
# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
p = s.post('LOGIN_URL', data=payload)
# print the html returned or something more intelligent to see if it's a successful login page.
print p.text
# An authorised request.
r = s.get('A protected web page url')
print r.text
# etc...
Close the modal box using javascript
$('#product-options').modal('hide');
Open the modal box using javascript
$('#product-options').modal('show');
Toggle the modal box using javascript
$('#myModal').modal('toggle');
Means close the modal if it's open and vice versa.
Replace:
myBinding.Source = ViewModel.SomeString;
with:
myBinding.Source = ViewModel;
Example:
Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);
Your source should be just ViewModel
, the .SomeString
part is evaluated from the Path
(the Path
can be set by the constructor or by the Path
property).
version control is your friend here, do a diff
or equivalent and you should see what's been added/modified.
In fact, removing the component folder might not be enough; with Angular-CLI v1.0, the command ng generate component my-new-component
also edits your app.module.ts
file by adding the respective import
line and the component to the providers
array.
This is a good one: apps-for-android
I had a similar error with a different artifact.
<...> was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
None of the above described solutions worked for me. I finally resolved this in IntelliJ IDEA by File > Invalidate Caches / Restart ... > Invalidate and Restart.
Try using isnull(a), isnotnull(a), nvl(), etc. On some versions(potentially in conjunction with the server settings - atleast with the one I am working on) of hive the 'IS NULL' and 'IS NOT NULL' syntax does not execute the logic when it is compiled. Check here for more information.
Orabig is correct.
You can bind 10.0.2.15 in Ubuntu (VirtualBox) then do a port forwarding from host to guest Ubuntu.
in /etc/redis/redis.conf
bind 10.0.2.15
then, restart redis:
sudo systemctl restart redis
It shall work!
So simple you can use case statement here.
CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN
CASE WHEN ISSUE_DIVISION is null then "Null Value found" //give your option
Else 1 End
ELSE 0 END As Issue_Division_Result
If you want to check on the object itself without interfering with the prototype, use hasOwnProperty()
:
var getIndexIfObjWithOwnAttr = function(array, attr, value) {
for(var i = 0; i < array.length; i++) {
if(array[i].hasOwnProperty(attr) && array[i][attr] === value) {
return i;
}
}
return -1;
}
to also include prototype attributes, use:
var getIndexIfObjWithAttr = function(array, attr, value) {
for(var i = 0; i < array.length; i++) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
I have faced the same issue while fetching elements using jQuery and data-* attribute.
so for your reference the shortest code is here:
This is my HTML Code:
<section data-js="carousel"></section>
<section></section>
<section></section>
<section data-js="carousel"></section>
This is my jQuery selector:
$('section[data-js="carousel"]');
// this will return array of the section elements which has data-js="carousel" attribute.
Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:
g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)
What you asked for is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Might be a very late answer, but this is good and simple.
select * from table_name order by id desc limit 5
This query will return a set of last 5 values(last 5 rows) you 've inserted in your table
This is not specific to Java 8. You are trying to compile something equivalent to:
interface I {
void m();
}
class C implements I {
public void m() throws Exception {} //can't compile
}
Thank you all for your help.
This is what I have used in the end:
SELECT *,
CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%'
THEN 'Valid'
ELSE 'No valid'
END [Validate]
FROM
*table*
ORDER BY [Validate]
Try to check the length of the selector, if it returns you something then the element must exists else not.
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
Use the first if condition for id and the 2nd one for class.
Assuming that your current primary key constraint is called pk_history, you can replace the following lines:
ALTER TABLE history ADD PRIMARY KEY (id)
ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name
with these:
ALTER TABLE history DROP CONSTRAINT pk_history
ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)
If you don't know what the name of the PK is, you can find it with the following query:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'history'
Multiprograming
Running more then one program with in an application to perform a certain task.
Example : In MS WORD, Writing in document and sending Email
Multitasking
Running more then one application to perform a certain task.
Example: listening Song, playing game, work in ms word, excel and other applications simultaneously
Multiprocessing
Running more then one instruction through a processor.
Example When create a file then computer takes Time and date default.
strtotime('2012-01-18T11:45:00+01:00');
// Output : 1326883500
date_format(date_timestamp_set(new DateTime(), 1326883500), 'c');
// Output : 2012-01-18T11:45:00+01:00
date_format(date_create('@'. 1326883500), 'c') . "\n";
// Output : 2012-01-18T10:45:00+00:00
date_format(date_timestamp_set(new DateTime(), 1326883500)->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2012-01-18T05:45:00-05:00
This provides an answer for people who arrive at this Question that may want to link an editor other than vim.
The linked resource, by Github,is likely to be kept up to date, when editors are updated, even if answers on SO (including this one) are not.
Associating Text Editors with git
Github's post shows exactly what to type in to your command line for various editors, including the options/flags specific to each editor for it to work best with git.
Notepad++:
git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Sublime Text:
git config --global core.editor "'c:/Program Files/sublime text 3/subl.exe' -w"
Atom:
git config --global core.editor "atom --wait"
The commands above assume your editor has been installed in the default directory for a windows machine.
The commands basically add the text between double-quotes to .gitconfig
in your home directory.
On a windows machine home is likely to be C:\Users\your-user-name
, where your-user-name is your login name.
From the command line, you can reach this directory by typing in cd ~
.
for example, a command above would be add the following line under the [core]
section like so:
[core]
editor = 'C:/Program Files/sublime text 3/subl.exe' -w
If you have a different editor, just replace with the path to your editor, using either method above. (and hope no flags are needed for optimal usage.)
For me the problem appeared in this situation:
I installed VS2012 and did not need VS2010 anymore. I wanted to get my computer clean and also removed the VS2010 runtime executables, thinking that no other program would use it. Then I wanted to test my DLL by attaching it to a program (let's call it program X). I got the same error message. I thought that I did something wrong when compiling the DLL. However, the real problem was that I attached the DLL to program X, and program X was compiled in VS2010 with debug info. That is why the error was thrown. I recompiled program X in VS2012, and the error was gone.
If all you are looking for is killing a package
pkill package_name
should work
Annotations may be used as an alternative to external configuration files, but cannot be considered a complete replacement. You can find many examples where annotationi have been used to replace configuration files, like Hibernate, JPA, EJB 3 and almost all the technologies included in Java EE.
Anyway this is not always good choice. The purpose of using configuration files is usually to separate the code from the details of the environment where the application is running. In such situations, and mostly when the configuration is used to map the application to the structure of an external system, annotation are not a good replacement for configuration file, as they bring you to include the details of the external system inside the source code of your application. Here external files are to be considered the best choice, otherwise you'll need to modify the source code and to recompile every time you change a relevant detail in the execution environment.
Annotations are much more suited to decorate the source code with extra information that instruct processing tools, both at compile time and at runtime, to handle classes and class structures in special way. @Override
and JUnit's @Test
are good examples of such a usage, already explained in detail in other answers.
In the end the rule is always the same: keep inside the source the things that change with the source, and keep outside the source the things that change independently from the source.
You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:
@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
@Autowired
private WebApplicationContext wac;
}
We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.
Now look at this code
void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
glBegin(GL_TRIANGLES);
x=5*cos(i);
y=5*sin(i);
glVertex2d(x, y);
i=i+.5;
x=5*cos(i);
y=5*sin(i);
glVertex2d(x, y);
glVertex2d(0, 0);
glEnd();
i=i+.5;
}
glEnd();
glutSwapBuffers();
}
I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
The code from the example should not be difficult to adapt to your specific situation:
<script>
function Ctrl($scope) {
$scope.color = 'blue';
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color | json}}</tt><br/>
</form>
I had the same issue for two days now. Disabled SELinux and everything but nothing helped. And I realize it just may not be smart to disable security for a small fix. Then I came upon this article - http://wiki.centos.org/HowTos/SELinux/ that explains how SELinux operates. So this is what I did and it fixed my problem.
Enable access to your main phpmyadmin directory by going to parent directory of phpmyadmin (mine was html) and typing:
chcon -v --type=httpd_sys_content_t phpmyadmin
Now do the same for the index.php by typing:
chcon -v --type=httpd_sys_content_t phpmyadmin/index.php
Now go back and check if you are getting a blank page. If you are, then you are on the right track. If not, go back and check your httpd.config directory settings. Once you do get the blank page with no warnings, proceed.
Now recurse through all the files in your phpmyadmin directory by running:
chron -Rv --type=httpd_sys_content_t phpmyadmin/*
Go back to your phpmyadmin page and see if you are seeing what you need. If you are running a web server that's accessible from outside your network, make sure that you reset your SELinux to the proper security level. Hope this helps!
Andy's solution does not work for me. Here I found another way:
git checkout `git rev-list -n 1 --before="2009-07-27 13:37" master`
You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.
I think what you were looking for in your Range was this:
Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete
Just change the column letters to match your needs.
Logically it does not work and you should reverse your loop:
for (int i = position-1; i >= 0; i--) {
array[i+1] = array[i];
}
Alternatively you can use
System.arraycopy(array, 0, array, 1, position);
None of the above worked for me. I spent too much time clearing other errors that came up. I found this to be the easiest and the best way.
This works for getting JavaFx on Jdk 11, 12 & on OpenJdk12 too!
module thisIsTheNameOfYourProject {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens sample;
}
The entire thing took me only 5mins !!!
You can use pandas.Series.tolist
e.g.:
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
Run:
>>> df['a'].tolist()
You will get
>>> [1, 2, 3]
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.
Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.
Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html
The way is
$ > g++ -lpthread perform.c -o per
$ > time ./per
output is >>
real 0m0.014s
user 0m0.010s
sys 0m0.002s
Simple and easy to understand example by using ternary operators to set selected value in php
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
<option value="<?php echo $id;?>" <?php echo ($id== '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.
Note: for this to work, all of the widgets for a page must have that page (ie: self
) or a descendant as a parent (or master, depending on the terminology you prefer).
Here's a bit of a contrived example to show you the general concept:
try:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
except ImportError:
import Tkinter as tk # python 2
import tkFont as tkfont # python 2
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.
For example, to create the classes individually you can remove the loop (for F in (StartPage, ...)
with this:
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:
Define a helper function like this
function checkWhitespace(inputString){
let stringArray = inputString.split(' ');
let output = true;
for (let el of stringArray){
if (el!=''){
output=false;
}
}
return output;
}
Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.
As an example
let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
// Show Warnings or return warnings
}else {
// // Block of code-probably store input value into database
}
Run VS in Administrator mode and it should work fine.
Use this solution
<!--[if lt IE 9]>
<script src="js/css3-mediaqueries.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap-ie7.css" />
<![endif]-->
This string <script src="js/css3-mediaqueries.js"></script>
enable mediaqueries.
This string <link rel="stylesheet" type="text/css" href="css/bootstrap-ie7.css" />
enable bootstrap fonts.
Tested on Bootstrap 3.3.5
Link to download mediaqieries.js. Link to download bootstrap-ie7.css
If self could be nil in the closure use [weak self].
If self will never be nil in the closure use [unowned self].
The Apple Swift documentation has a great section with images explaining the difference between using strong, weak, and unowned in closures:
I know this is an old one but it comes up top of Google and all the links provided now seem out of date.
This is the latest list of types Facebook accepts: https://developers.facebook.com/docs/reference/opengraph
If you don't use one of these then the type will default to 'website' which is best used for home pages/summarising a web site.
In answer to the OP you would now want to use a place which will allow you to add lat/long location details.
Try this:
{
"ACCOUNT_EXIST": true,
"MultipleContacts": false
}
boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()
Connect to the Guest and find out the ip address:
ifconfig
example of result (ip address is 10.0.2.15):
eth0 Link encap:Ethernet HWaddr 08:00:27:AE:36:99
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
Go to Vbox instance window -> Menu -> Network adapters:
Go to host system and try it in browser:
http://127.0.0.1:8000
or your network ip address (find out on the host machine by running: ipconfig).
In this case port forwarding is not needed, the communication goes over the LAN back to the host.
On the host machine - find out your netw ip address:
ipconfig
example of result:
IP Address. . . . . . . . . . . . : 192.168.5.1
On the guest machine you can communicate directly with the host, e.g. check it with ping:
# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...
@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):
sudo ufw allow 8000
Try to run xcrun simctl delete unavailable
in your terminal.
Original answer: Xcode - free to clear devices folder?
As already mentioned, you will need to use a formatted result; which is all done through the Write()
, WriteLine()
, Format()
, and ToString()
methods.
What has not been mentioned is the Fixed-point Format which allows for a specified number of decimal places. It uses an 'F' and the number following the 'F' is the number of decimal places outputted, as shown in the examples.
Console.WriteLine("{0:F2}", 12); // 12.00 - two decimal places
Console.WriteLine("{0:F0}", 12.3); // 12 - ommiting fractions
According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
The quirky syntax using conditions on the target (described by Mads) is the only supported way to perform conditional execution in core ANT.
ANT is not a programming language and when things get complicated I choose to embed a script within my build as follows:
<target name="prepare-copy" description="copy file based on condition">
<groovy>
if (properties["some.condition"] == "true") {
ant.copy(file:"${properties["some.dir"]}/true", todir:".")
}
</groovy>
</target>
ANT supports several languages (See script task), my preference is Groovy because of it's terse syntax and because it plays so well with the build.
Apologies, David I am not a fan of ant-contrib.
One important distinction between the two (which is visible in the Reflected code) is that SelectedValue will return an empty string if a nothing is selected, whereas SelectedItem.Value will throw a NullReference exception.
Not an answer to your question, but I wouldn't use case-sensitive shortened URLs. They are hard to remember, usually unreadable (many fonts render 1 and l, 0 and O and other characters very very similar that they are near impossible to tell the difference) and downright error prone. Try to use lower or upper case only.
Also, try to have a format where you mix the numbers and characters in a predefined form. There are studies that show that people tend to remember one form better than others (think phone numbers, where the numbers are grouped in a specific form). Try something like num-char-char-num-char-char. I know this will lower the combinations, especially if you don't have upper and lower case, but it would be more usable and therefore useful.
In recent versions of Git you can add multiple pushurl
s for a given remote. Use the following to add two pushurl
s to your origin
:
git remote set-url --add --push origin git://original/repo.git
git remote set-url --add --push origin git://another/repo.git
So when you push to origin
, it will push to both repositories.
UPDATE 1: Git 1.8.0.1 and 1.8.1 (and possibly other versions) seem to have a bug that causes --add
to replace the original URL the first time you use it, so you need to re-add the original URL using the same command. Doing git remote -v
should reveal the current URLs for each remote.
UPDATE 2: Junio C. Hamano, the Git maintainer, explained it's how it was designed. Doing git remote set-url --add --push <remote_name> <url>
adds a pushurl
for a given remote, which overrides the default URL for pushes. However, you may add multiple pushurl
s for a given remote, which then allows you to push to multiple remotes using a single git push
. You can verify this behavior below:
$ git clone git://original/repo.git
$ git remote -v
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.'
remote.origin.url=git://original/repo.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
Now, if you want to push to two or more repositories using a single command, you may create a new remote named all
(as suggested by @Adam Nelson in comments), or keep using the origin
, though the latter name is less descriptive for this purpose. If you still want to use origin
, skip the following step, and use origin
instead of all
in all other steps.
So let's add a new remote called all
that we'll reference later when pushing to multiple repositories:
$ git remote add all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch) <-- ADDED
all git://original/repo.git (push) <-- ADDED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git <-- ADDED
remote.all.fetch=+refs/heads/*:refs/remotes/all/* <-- ADDED
Then let's add a pushurl
to the all
remote, pointing to another repository:
$ git remote set-url --add --push all git://another/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push) <-- CHANGED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git <-- ADDED
Here git remote -v
shows the new pushurl
for push, so if you do git push all master
, it will push the master
branch to git://another/repo.git
only. This shows how pushurl
overrides the default url (remote.all.url).
Now let's add another pushurl
pointing to the original repository:
$ git remote set-url --add --push all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)
all git://original/repo.git (push) <-- ADDED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git
remote.all.pushurl=git://original/repo.git <-- ADDED
You see both pushurl
s we added are kept. Now a single git push all master
will push the master
branch to both git://another/repo.git
and git://original/repo.git
.
It does have to be wrapped in an <xsl:choose> since it's a when. And lowercase the "and".
<xsl:choose>
<xsl:when test="4 < 5 and 1 < 2" >
<!-- do something -->
</xsl:when>
<xsl:otherwise>
<!-- do something else -->
</xsl:otherwise>
</xsl:choose>
If some one working on monorepo following react-native-web-monorepo than you need to config-overrides.js
file in packages/web
. you need to add resolveApp('../../node_modules/react-native-ratings'),
in that file...
My complete config-override.js
file is
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
// our packages that will now be included in the CRA build step
const appIncludes = [
resolveApp('src'),
resolveApp('../components/src'),
resolveApp('../../node_modules/@react-navigation'),
resolveApp('../../node_modules/react-navigation'),
resolveApp('../../node_modules/react-native-gesture-handler'),
resolveApp('../../node_modules/react-native-reanimated'),
resolveApp('../../node_modules/react-native-screens'),
resolveApp('../../node_modules/react-native-ratings'),
resolveApp('../../node_modules/react-navigation-drawer'),
resolveApp('../../node_modules/react-navigation-stack'),
resolveApp('../../node_modules/react-navigation-tabs'),
resolveApp('../../node_modules/react-native-elements'),
resolveApp('../../node_modules/react-native-vector-icons'),
];
module.exports = function override(config, env) {
// allow importing from outside of src folder
config.resolve.plugins = config.resolve.plugins.filter(
plugin => plugin.constructor.name !== 'ModuleScopePlugin'
);
config.module.rules[0].include = appIncludes;
config.module.rules[1] = null;
config.module.rules[2].oneOf[1].include = appIncludes;
config.module.rules[2].oneOf[1].options.plugins = [
require.resolve('babel-plugin-react-native-web'),
require.resolve('@babel/plugin-proposal-class-properties'),
].concat(config.module.rules[2].oneOf[1].options.plugins);
config.module.rules = config.module.rules.filter(Boolean);
config.plugins.push(
new webpack.DefinePlugin({ __DEV__: env !== 'production' })
);
return config
};
I prefer not to alter the df
.
An option is to retrieve the index
of the start
and end
dates:
import numpy as np
import pandas as pd
#Dummy DataFrame
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')
#Get the index of the start and end dates respectively
start = df[df['date']=='2017-01-07'].index[0]
end = df[df['date']=='2017-01-14'].index[0]
#Show the sliced df (from 2017-01-07 to 2017-01-14)
df.loc[start:end]
which results in:
0 1 2 date
6 0.5 0.8 0.8 2017-01-07
7 0.0 0.7 0.3 2017-01-08
8 0.8 0.9 0.0 2017-01-09
9 0.0 0.2 1.0 2017-01-10
10 0.6 0.1 0.9 2017-01-11
11 0.5 0.3 0.9 2017-01-12
12 0.5 0.4 0.3 2017-01-13
13 0.4 0.9 0.9 2017-01-14
If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.
javascript:
<script language="javascript">
setTimeout(function(){
window.location.reload(1);
}, 30000);
</script>
If you want to do it using XAML set the property isReadOnly
to true
.
On the documentation:
http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat
It says:
(...) if you know the matrix element type, e.g. it is float, then you can use at<>() method
That is, you can use:
Mat M(100, 100, CV_64F);
cout << M.at<double>(0,0);
Maybe it is easier to use the Mat_
class. It is a template wrapper for Mat
.
Mat_
has the operator()
overloaded in order to access the elements.
try to ad the following in your CSS:
body, html{
padding:0;
margin:0;
}
Neither of these answers would work for me, not the Preferences NLS configuration option or the ALTER statement. This was the only approach that worked in my case:
dbms_session.set_nls('nls_date_format','''DD-MM-YYYY HH24:MI:SS''');
*added after the BEGIN statement
I am using PL/SQL Developer v9.03.1641
Hopefully this is of help to someone!
Here's how I did it, I think the most elegant way I could. With this solution, the only things you need to do in your layouts are:
xmlns
declarationTextView
s source text namespace from android to your new namespaceTextView
s with x.y.z.JustifiedTextView
Here's the code. Works perfectly fine on my phones (Galaxy Nexus Android 4.0.2, Galaxy Teos Android 2.1). Feel free, of course, to replace my package name with yours.
/assets/justified_textview.css:
body {
font-size: 1.0em;
color: rgb(180,180,180);
text-align: justify;
}
@media screen and (-webkit-device-pixel-ratio: 1.5) {
/* CSS for high-density screens */
body {
font-size: 1.05em;
}
}
@media screen and (-webkit-device-pixel-ratio: 2.0) {
/* CSS for extra high-density screens */
body {
font-size: 1.1em;
}
}
/res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="JustifiedTextView">
<attr name="text" format="reference" />
</declare-styleable>
</resources>
/res/layout/test.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/net.bicou.myapp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<net.bicou.myapp.widget.JustifiedTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
myapp:text="@string/surv1_1" />
</LinearLayout>
</ScrollView>
/src/net/bicou/myapp/widget/JustifiedTextView.java:
package net.bicou.myapp.widget;
import net.bicou.myapp.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebView;
public class JustifiedTextView extends WebView {
public JustifiedTextView(final Context context) {
this(context, null, 0);
}
public JustifiedTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public JustifiedTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (attrs != null) {
final TypedValue tv = new TypedValue();
final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.JustifiedTextView, defStyle, 0);
if (ta != null) {
ta.getValue(R.styleable.JustifiedTextView_text, tv);
if (tv.resourceId > 0) {
final String text = context.getString(tv.resourceId).replace("\n", "<br />");
loadDataWithBaseURL("file:///android_asset/",
"<html><head>" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"justified_textview.css\" />" +
"</head><body>" + text + "</body></html>",
"text/html", "UTF8", null);
setTransparentBackground();
}
}
}
}
public void setTransparentBackground() {
try {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
} catch (final NoSuchMethodError e) {
}
setBackgroundColor(Color.TRANSPARENT);
setBackgroundDrawable(null);
setBackgroundResource(0);
}
}
We need to set the rendering to software in order to get transparent background on Android 3+. Hence the try-catch for older versions of Android.
Hope this helps!
PS: please not that it might be useful to add this to your whole activity on Android 3+ in order to get the expected behavior:
android:hardwareAccelerated="false"
"As with bootstrap’s own plugins, datepicker provides a data-api that can be used to instantiate datepickers without the need for custom javascript..."
Boostrap DatePicker Documentation
Maybe you want to set format without DatePicker instance, for that, you have to add the property data-date-format="DateFormat"
to main Div tag, for example:
<div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
<input type="text" name="YourName" id="YourId" class="YourClass">
</div>
Per Mikaël Mayer's answer, this is no longer a problem, and my answer is obsolete (go()
now returns 30
after mucking with the console). This was fixed in July 2013, according to the bug report linked above in gabrielmaldi's comment. It alarms me that I'm still getting upvotes - makes me think the upvoter doesn't understand either the question or my answer.
I'll leave my original answer here for historical reasons, but go upvote Mikaël's answer instead.
The trick is that you can't change a local variable directly, but you can modify the properties of an object. You can also modify the value of a global variable:
var g_n = 0;
function go()
{
var n = 0;
var o = { n: 0 };
return g_n + n + o.n; // breakpoint here
}
console:
> g_n = 10
10
> g_n
10
> n = 10
10
> n
0
> o.n = 10
10
> o.n
10
Check the result of go()
after setting the breakpoint and running those calls in the console, and you'll find that the result is 20, rather than 0 (but sadly, not 30).
Try using .pull-left to left align image along with text.
Ex:
<p>At the time all text elements goes here.At the time all text elements goes here. At the time all text elements goes here.<img src="images/hello-missing.jpg" class="pull-left img-responsive" style="padding:15px;" /> to uncovering the truth .</p>
You want to create an Object, not an Array.
Like so,
var Map = {};
Map['key1'] = 'value1';
Map['key2'] = 'value2';
You can check if the key exists in multiple ways:
Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...
To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.
Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.
From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:
E:first-child
, E:hover
, E > F
(Child combinator), E + F
(Adjacent sibling combinator), E ~ F
(General sibling combinator). This unfortunately means resorting to workarounds like inline styles.white-space
won't work.background-image
property won't work.height
, width
, and the max-
versions are either not usable or have bugs for certain elements.display
, float
s and position
are all out).In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.
PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top
" where you probably meant to use vertical-align
. Also: cell-padding
for td
s doesn't exist.
You can use git add -i
to get an interactive version of git add
, although that's not exactly what you're after. The simplest thing to do is, after having git add
ed, use git status
to see what is staged or not.
Using git add .
isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).
You can solve it like this:
git reset --hard sha
where sha
e.g.: 85a108ec5d8443626c690a84bc7901195d19c446
You can get the desired sha with the command:
git log
I am not aware of any libraries to do this (but I am sure there are many that can) but if you can already create HTML from the crystal report why not use XSLT to clean up the markup?
=
, the indent command can take motions. So, gg
to get the start of the file, =
to indent, G
to the end of the file, gg=G
.
For IE8 & IE9 you need to use XDomainRequest (XDR). If you look below you'll see it's in a sort of similar formatting as $.ajax. As far as my research has got me I can't get this cross-domain working in IE6 & 7 (still looking for a work-around for this). XDR first came out in IE8 (it's in IE9 also). So basically first, I test for 6/7 and do no AJAX.
IE10+ is able to do cross-domain normally like all the other browsers (congrats Microsoft... sigh)
After that the else if tests for 'XDomainRequest in window (apparently better than browser sniffing) and does the JSON AJAX request that way, other wise the ELSE does it normally with $.ajax.
Hope this helps!! Took me forever to get this all figured out originally
Information on the XDomainRequest object
// call with your url (with parameters)
// 2nd param is your callback function (which will be passed the json DATA back)
crossDomainAjax('http://www.somecrossdomaincall.com/?blah=123', function (data) {
// success logic
});
function crossDomainAjax (url, successCallback) {
// IE8 & 9 only Cross domain JSON GET request
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(); // Use Microsoft XDR
xdr.open('get', url);
xdr.onload = function () {
var dom = new ActiveXObject('Microsoft.XMLDOM'),
JSON = $.parseJSON(xdr.responseText);
dom.async = false;
if (JSON == null || typeof (JSON) == 'undefined') {
JSON = $.parseJSON(data.firstChild.textContent);
}
successCallback(JSON); // internal function
};
xdr.onerror = function() {
_result = false;
};
xdr.send();
}
// IE7 and lower can't do cross domain
else if (navigator.userAgent.indexOf('MSIE') != -1 &&
parseInt(navigator.userAgent.match(/MSIE ([\d.]+)/)[1], 10) < 8) {
return false;
}
// Do normal jQuery AJAX for everything else
else {
$.ajax({
url: url,
cache: false,
dataType: 'json',
type: 'GET',
async: false, // must be set to false
success: function (data, success) {
successCallback(data);
}
});
}
}
If the error message is just
"Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.", then grant the login permission for 'NT AUTHORITY\NETWORK SERVICE'
by using
"sp_grantlogin 'NT AUTHORITY\NETWORK SERVICE'"
else if the error message is like
"Cannot open database "Phaeton.mdf" requested by the login. The login failed. Login failed for user 'NT AUTHORITY\NETWORK SERVICE'."
try using
"EXEC sp_grantdbaccess 'NT AUTHORITY\NETWORK SERVICE'"
under your "Phaeton" database.
//To delete all the files of a specific folder & subfolder
public static void deleteFiles(File directory, Context c) {
try {
for (File file : directory.listFiles()) {
if (file.isFile()) {
final ContentResolver contentResolver = c.getContentResolver();
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
if (file.exists()) {
file.delete();
if (file.exists()) {
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if (file.exists()) {
c.deleteFile(file.getName());
}
}
}
} else
deleteFiles(file, c);
}
} catch (Exception e) {
}
}
here is your solution it will also refresh the gallery as well.
For my case, it is solved by changing the properties of edmx file.
this solved the problem for me. The problem is, when the container try to find the meta data, it cant find it. so simply make it in the same assembly. this solution will not work if you have your edmx files in another assembly
Hope it might help someone instantly.
In Python 2.7: By default, division operator will return integer output.
to get the result in double multiple 1.0 to "dividend or divisor"
100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857
In Python 3
// => used for integer output
/ => used for double output
100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0 # floating-point result if divsor or dividend real
Another way is:
f = open("|ls")
foo = f.read()
Note that's the "pipe" character before "ls" in open. This can also be used to feed data into the programs standard input as well as reading its standard output.
If you have specific chars should be:
Collection<Character> specificChars = Arrays.asList('A', 'D', 'E'); // more chars
char symbol = 'Y';
System.out.println(specificChars.contains(symbol)); // false
symbol = 'A';
System.out.println(specificChars.contains(symbol)); // true
Use StringBuilder
StringBuilder sb = new StringBuilder(String.valueOf(a));
sb.append(String.valueOf(b));
sb.append(String.valueOf(c));
sb.append(String.valueOf(d));
sb.append(String.valueOf(e));
System.out.print(sb.toString());
Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.
.divider{
position:absolute;
left:50%;
top:10%;
bottom:10%;
border-left:1px solid white;
}
I was answering similar question and got yet another idea how to achieve this without use of eval()
:
const source = "alert('test')";
const el = document.createElement("script");
el.src = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
document.head.appendChild(el);
In the code above you basically create Blob, containing your script, in order to create Object URL (representation of File or Blob object in browser memory). Since you have src
property on <script>
tag, the script will be executed the same way as if it was loaded from any other URL.
To create a complete link to another page from a template, you can use this:
{{ request.META.HTTP_HOST }}{% url 'views.my_view' my_arg %}
request.META.HTTP_HOST gives the host name, and url gives the relative name. The template engine then concatenates them into a complete url.
(similar as Gustavo said, but additionally: )
For any previously search, you can do simply:
:%s///gn
A pattern is not needed, because it is already in the search-register (@/
).
"%" - do s/
in the whole file
"g" - search global (with multiple hits in one line)
"n" - prevents any replacement of s/
-- nothing is deleted! nothing must be undone!
(see: :help s_flag
for more informations)
(This way, it works perfectly with "Search for visually selected text", as described in vim-wikia tip171)
The changed it from change
to selectionChange
.
<mat-select (change)="doSomething($event)">
is now
<mat-select (selectionChange)="doSomething($event)">
This is the approach to do this: -
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'DBName' AND
TABLE_SCHEMA = 'SchemaName' AND
TABLE_NAME = 'TableName' AND
COLUMN_NAME = 'ColumnName')
BEGIN
ALTER TABLE DBName.SchemaName.TableName ALTER COLUMN ColumnName [data type] NULL
END
If you don't have any schema then delete the schema line because you don't need to give the default schema.
A multi-producers and multi-consumers example, verified. It should be easy to modify it to cover other cases, single/multi producers, single/multi consumers.
from multiprocessing import Process, JoinableQueue
import time
import os
q = JoinableQueue()
def producer():
for item in range(30):
time.sleep(2)
q.put(item)
pid = os.getpid()
print(f'producer {pid} done')
def worker():
while True:
item = q.get()
pid = os.getpid()
print(f'pid {pid} Working on {item}')
print(f'pid {pid} Finished {item}')
q.task_done()
for i in range(5):
p = Process(target=worker, daemon=True).start()
# send thirty task requests to the worker
producers = []
for i in range(2):
p = Process(target=producer)
producers.append(p)
p.start()
# make sure producers done
for p in producers:
p.join()
# block until all workers are done
q.join()
print('All work completed')
Explanation:
I'm guessing that you actually want Omega
to be a string containing an uppercase omega? In that case, you can write:
var Omega = '\u03A9';
(Because Ω is the Unicode character with codepoint U+03A9; that is, 03A9
is 937
, except written as four hexadecimal digits.)
Take note, with full paths the line: [MethodImpl(MethodImplOptions.Synchronized)]
should look like
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
No one seems to have mentioned about the negative infinity explicitly, so I think I should add it.
For negative infinity:
-math.inf
For positive infinity (just for the sake of completeness):
math.inf
Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...
As others wrote before me, at the end its what being used by your project/team/company.
Personally, I am not using cc
extension, I am trying to lower the number of extensions and not increase them, unless there's a clear value (in my opinion).
For what its worth, this is what I'm using:
c
- Pure C code only, no classes or structs with methods.
cpp
- C++ code
hpp
- Headers only code. Implementations are in the headers (like template classes)
h
- header files for both C/C++. I agree another distinction can be made, but as I wrote, I am trying to lower the number of extensions for simplicity. At least from the C++ projects I've worked in, h
files for pure-C are more rare, therefore I did not want to add another extension.
With gnuplot using gplot.py
from gplot import *
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
gplot.log('y')
gplot(*zip(*l))
What you basically want to do is to force push your local branch, in order to overwrite the remote one.
If you want a more detailed explanation of each of the following commands, then see my details section below. You basically have 4 different options for force pushing with Git:
git push <remote> <branch> -f
git push origin master -f # Example
git push <remote> -f
git push origin -f # Example
git push -f
git push <remote> <branch> --force-with-lease
If you want a more detailed explanation of each command, then see my long answers section below.
Warning: force pushing will overwrite the remote branch with the state of the branch that you're pushing. Make sure that this is what you really want to do before you use it, otherwise you may overwrite commits that you actually want to keep.
You can completely specify specific branches and a remote. The -f
flag is the short version of --force
git push <remote> <branch> --force
git push <remote> <branch> -f
When the branch to push branch is omitted, Git will figure it out based on your config settings. In Git versions after 2.0, a new repo will have default settings to push the currently checked-out branch:
git push <remote> --force
while prior to 2.0, new repos will have default settings to push multiple local branches. The settings in question are the remote.<remote>.push
and push.default
settings (see below).
When both the remote and the branch are omitted, the behavior of just git push --force
is determined by your push.default
Git config settings:
git push --force
As of Git 2.0, the default setting, simple
, will basically just push your current branch to its upstream remote counter-part. The remote is determined by the branch's branch.<remote>.remote
setting, and defaults to the origin repo otherwise.
Before Git version 2.0, the default setting, matching
, basically just pushes all of your local branches to branches with the same name on the remote (which defaults to origin).
You can read more push.default
settings by reading git help config
or an online version of the git-config(1) Manual Page.
--force-with-lease
Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:
git push <remote> <branch> --force-with-lease
You can learn more details about how to use --force-with-lease
by reading any of the following:
setattr(x, attr, 'magic')
For help on it:
>>> help(setattr)
Help on built-in function setattr in module __builtin__:
setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
Edit: However, you should note (as pointed out in a comment) that you can't do that to a "pure" instance of object
. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.
Since the third version of Swift you can do the following:
let desiredString = NSString(data: yourData, encoding: String.Encoding.utf8.rawValue)
simialr to what Sunkas advised.
The solution I use is the following:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42" value="The answer">
</datalist>
Then access the value to be sent to the server using JavaScript like this:
var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;
Hope it helps.
This works pretty well with using optional matches (prints after href=
) and gets the link only. Tested on http://pythex.org/
(?:href=['"])([:/.A-z?<_&\s=>0-9;-]+)
Oputput:
Match 1. /wiki/Main_Page
Match 2. /wiki/Portal:Contents
Match 3. /wiki/Portal:Featured_content
Match 4. /wiki/Portal:Current_events
Match 5. /wiki/Special:Random
Match 6. //donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&utm_medium=sidebar&utm_campaign=C13_en.wikipedia.org&uselang=en
I tried the above but I'm getting a database error complaining that the foreign key field in the Child table can not be NULL. Is there a way to tell JPA to automatically set this foreign key into the Child object so it can automatically save children objects?
Well, there are two things here.
First, you need to cascade the save operation (but my understanding is that you are doing this or you wouldn't get a FK constraint violation during inserts in the "child" table)
Second, you probably have a bidirectional association and I think that you're not setting "both sides of the link" correctly. You are supposed to do something like this:
Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);
List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChildren(children);
session.save(parent);
A common pattern is to use link management methods:
@Entity
public class Parent {
@Id private Long id;
@OneToMany(mappedBy="parent")
private List<Child> children = new ArrayList<Child>();
...
protected void setChildren(List<Child> children) {
this.children = children;
}
public void addToChildren(Child child) {
child.setParent(this);
this.children.add(child);
}
}
And the code becomes:
Parent parent = new Parent();
...
Child c1 = new Child();
...
parent.addToChildren(c1);
session.save(parent);
References
You can swap variables with or without using a temporary variable.
Here is an article that provides multiple methods to swap numbers without temp variable :
http://topjavatutorial.com/java/java-programs/swap-two-numbers-without-a-temporary-variable-in-java/
command to remove cordova and ionic
sudo npm uninstall -g ionic
Marquee (<marquee>
) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!
As mentioned in the React documentation, there is no guarantee of setState
being fired synchronously, so your console.log
may return the state prior to it updating.
Michael Parker mentions passing a callback within the setState
. Another way to handle the logic after state change is via the componentDidUpdate
lifecycle method, which is the method recommended in React docs.
Generally we recommend using componentDidUpdate() for such logic instead.
This is particularly useful when there may be successive setState
s fired, and you would like to fire the same function after every state change. Rather than adding a callback to each setState
, you could place the function inside of the componentDidUpdate
, with specific logic inside if necessary.
// example
componentDidUpdate(prevProps, prevState) {
if (this.state.value > prevState.value) {
this.foo();
}
}
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
Table::where('id', 1)->get(['name','surname']);
Sort may be omitted if order is not significant
uniq -c <source_file>
or
echo "$list" | uniq -c
if the source list is a variable
Don't use a service for this. Create a normal application and create a scheduled task to run it.
This is the commonly held best practice. Jon Galloway agrees with me. Or maybe its the other way around. Either way, the fact is that it is not best practices to create a windows service to perform an intermittent task run off a timer.
"If you're writing a Windows Service that runs a timer, you should re-evaluate your solution."
–Jon Galloway, ASP.NET MVC community program manager, author, part time superhero
Or, you can use my query here, should be simpler then having to create sProcs for each DB you want to search: FullParam SQL Blog
/* Reto Egeter, fullparam.wordpress.com */
DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE @TableName IS NOT NULL
BEGIN
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF @TableName IS NOT NULL
BEGIN
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + @TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + @TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO @ColumnNameTable
EXEC (@sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
BEGIN
PRINT @ColumnName
SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(@sql)
IF @@ROWCOUNT > 0 IF @FullRowResult = 1
BEGIN
SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
EXEC(@sql)
END
DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
END
END
END
SET NOCOUNT OFF
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results GROUP BY TableName, ColumnName, ColumnValue, ColumnType
PUSHD path
Takes you to the directory specified by path.
POPD
Takes you back to the directory you "pushed" from.
When I need to write short code or a one-liner, I use this "hack":
'Hello World'.replace(/./g, function (char) {
alert(char);
return char; // this is optional
});
This won't count newlines so that can be a good thing or a bad thing. If you which to include newlines, replace: /./
with /[\S\s]/
. The other one-liners you may see probably use .split()
which has many problems
Also you can use, this Macro to assign Descriptions to arguments and the UDF:
Private Sub RegisterMyFunction()
Application.MacroOptions _
Macro:="SampleFunction", _ '' Your UDF name
Description:="calculates a result based on provided inputs", _
Category:="My UDF Category", _ '' Or use numbers, a list in the link below
ArgumentDescriptions:=Array( _ '' One by each argument
"is the first argument. tell the user what it does", _
"is the second argument. tell the user what it does")
End Sub
Credits to Kendall and the original post here. For the UDF Categories
Python.org has an excellent section on strings here. Scroll down to where it says "slice notation".
String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));
Use set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "/some/full/path/to/bin")
You can also use sqlcmd
mode for this (enable this on the "Query" menu in Management Studio).
:setvar dbname "TEST"
CREATE DATABASE $(dbname)
GO
ALTER DATABASE $(dbname) SET COMPATIBILITY_LEVEL = 90
GO
ALTER DATABASE $(dbname) SET RECOVERY SIMPLE
GO
EDIT:
Check this MSDN article to set parameters via the SQLCMD tool.
This depends on the alphabet but for the english one, try this:
String input = "abc".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
int position = input.charAt(i) - 'a' + 1;
}
min-width
and max-width
properties do not work the way you expect for table cells. From spec:
In CSS 2.1, the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.
This hasn't changed in CSS3.
If you are using Url.Action
inside JavaScript then you can
var personId="someId";
$.ajax({
type: 'POST',
url: '@Url.Action("CreatePerson", "Person")',
dataType: 'html',
data: ({
//insert your parameters to pass to controller
id: personId
}),
success: function() {
alert("Successfully posted!");
}
});
Use the :w
command with a filename:
:w other_filename
SomeProperty.HasValue I think it's what you're looking for.
EDIT : btw, you can write System.Guid?
instead of Nullable<System.Guid>
;)
You need either of the following depending on the type of the container of T
elements you pass to the builder (Collection<T>
or T[]
):
Collection<T> YOUR_COLLECTION
:Collections.unmodifiableList(new ArrayList<>(YOUR_COLLECTION));
T[] YOUR_ARRAY
:Arrays.asList(YOUR_ARRAY);
Simple as that
Or you could convert the sqlite3.Rows to a dictionary as follows. This will give a dictionary with a list for each row.
def from_sqlite_Row_to_dict(list_with_rows):
''' Turn a list with sqlite3.Row objects into a dictionary'''
d ={} # the dictionary to be filled with the row data and to be returned
for i, row in enumerate(list_with_rows): # iterate throw the sqlite3.Row objects
l = [] # for each Row use a separate list
for col in range(0, len(row)): # copy over the row date (ie. column data) to a list
l.append(row[col])
d[i] = l # add the list to the dictionary
return d
Open a Command Prompt, then execute this command:
icacls "c:\somelocation\of\path" /q /c /t /grant Users:F
F
gives Full Access.
/q /c /t
applies the permissions to subfolders.
Note: Sometimes "Run as Administrator" will help.
I would like to add to the answer provided by Sangam Belose. Here's his code:
select ('id') as id, ('time') as time, ('unit') as unit
UNION ALL
SELECT * INTO OUTFILE 'C:/Users/User/Downloads/data.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM sensor
However, if you have not set up your "secure_file_priv"
within the variables, it may not work. For that, check the folder set on that variable by:
SHOW VARIABLES LIKE "secure_file_priv"
The output should look like this:
mysql> show variables like "%secure_file_priv%";
+------------------+------------------------------------------------+
| Variable_name | Value |
+------------------+------------------------------------------------+
| secure_file_priv | C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ |
+------------------+------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
You can either change this variable or change the query to output the file to the default path showing.
Here is a working example for kramdown following @Yarin's answer.
A simple paragraph with a class attribute.
{:.yourClass}
Reference: https://kramdown.gettalong.org/syntax.html#inline-attribute-lists
I had this issue on mac 10.10.5 Yosemite
What I did to solve this
cd /usr/local/var/mysql
sudo rm *.err && sudo rm *.pid
sudo reboot
sudo mysql.server start
If you're just looking to do this from a debugging standpoint, you can use a Firefox plugin such as JSONovich to view the JSON content.
The new version of Firefox that is currently in beta is slated to natively support this (much like XML)
You can use:
SET PASSWORD FOR 'root' = PASSWORD('elephant7');
or, in latest versions:
SET PASSWORD FOR root = 'elephant7'
You can also use:
UPDATE user SET password=password('elephant7') WHERE user='root';
but in Mysql 5.7 the field password is no more there, and you have to use:
UPDATE user SET authentication_string=password('elephant7') WHERE user='root';
Regards
If you are here because your pytorch always gives False
for torch.cuda.is_available()
that's probably because you installed your pytorch version without GPU support. (Eg: you coded up in laptop then testing on server).
The solution is to uninstall and install pytorch again with the right command from pytorch downloads page. Also refer this pytorch issue.
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
If you have common field in both table then it's so easy !....
Table-1 = table where you want to update. Table-2 = table where you from take data.
$qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`");
$resultArray = array();
while ($row = mysql_fetch_array($qry_asseet_list)) {
$resultArray[] = $row;
}
foreach($resultArray as $rec) {
$a = $rec['primary key field'];
$cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a");
$cuttable = mysql_fetch_assoc($cuttable_qry);
echo $x= $cuttable['Table-2 field']; echo " ! ";
echo $y= $cuttable['Table-2 field'];echo " ! ";
echo $z= $cuttable['Table-2 field'];echo " ! ";
$k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;");
if ($k) {
echo "done";
} else {
echo mysql_error();
}
}
A bit late but I tried this and it worked to make the Recaptcha responsive on screens smaller than 460px width. You can't use css selector to select elements inside the iframe. So, better use the outermost parent element which is the class g-recaptcha to basically zoom-out i.e transform the size of the entire container. Here's my code which worked:
@media(max-width:459.99px) {
.modal .g-recaptcha {
transform:scale(0.75);
-webkit-transform:scale(0.75); }
}
}
you can use this to get the data of the last 30 days based on a column.
WHERE DATEDIFF(dateColumn,CURRENT_TIMESTAMP) BETWEEN 0 AND 30
First of all, you need to check that the IIS is installed in your machine, for that you can go to:
Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'
If not, check it, and Press Accept to install it.
Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).
Edit: You should have something like this:
You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)]
and further in component file assign default
value to it.
In your_component_file.ts
this.selectedCountry = default;
In your_component_template.html
<select id="country" formControlName="country" [(ngModel)]="selectedCountry">
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
you can use this module -> https://github.com/jiahut/ng.lodash
this is for lodash
so does underscore
You should join T1 and T2 tables using sql joins in order to analyze from two tables. Link for learn joins : https://www.w3schools.com/sql/sql_join.asp
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
Look at the constructor for String
String str = new String(bytes, StandardCharsets.UTF_8);
And if you're feeling lazy, you can use the Apache Commons IO library to convert the InputStream to a String directly:
String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
If you want a list of lists:
>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]
If a list of tuples is OK:
>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]
You can also use search function without parameters:
jQuery("#id").autocomplete("search", "");
Run below command where pom.xml
is placed:
mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
And start your remote java application with debugging option on port 5005
Below you can find my implementation of gradient descent for linear regression problem.
At first, you calculate gradient like X.T * (X * w - y) / N
and update your current theta with this gradient simultaneously.
Here is the python code:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import random
def generateSample(N, variance=100):
X = np.matrix(range(N)).T + 1
Y = np.matrix([random.random() * variance + i * 10 + 900 for i in range(len(X))]).T
return X, Y
def fitModel_gradient(x, y):
N = len(x)
w = np.zeros((x.shape[1], 1))
eta = 0.0001
maxIteration = 100000
for i in range(maxIteration):
error = x * w - y
gradient = x.T * error / N
w = w - eta * gradient
return w
def plotModel(x, y, w):
plt.plot(x[:,1], y, "x")
plt.plot(x[:,1], x * w, "r-")
plt.show()
def test(N, variance, modelFunction):
X, Y = generateSample(N, variance)
X = np.hstack([np.matrix(np.ones(len(X))).T, X])
w = modelFunction(X, Y)
plotModel(X, Y, w)
test(50, 600, fitModel_gradient)
test(50, 1000, fitModel_gradient)
test(100, 200, fitModel_gradient)
This is the job for style
property:
document.getElementById("remember").style.visibility = "visible";
Hope this helps. Trick is to use absolute positioning and configure the top and left columns. Of course "dead center" will depend on the size of the object/div you are embedding, so you will need to do some work. For a login window I used the following - it also has some safety with max-width and max-height that may actually be of use to you in your example. Configure the values below to your requirement.
div#wrapper {
border: 0;
width: 65%;
text-align: left;
position: absolute;
top: 20%;
left: 18%;
height: 50%;
min-width: 600px;
max-width: 800px;
}
If anyone looking for a solution with (.less) try below. Open your main or common less file and use like below.
@import (css) url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
body{
font-family: "Open Sans", sans-serif;
}
Update with ES6: If your concern is having a sorted object to iterate through (which is why i'd imagine you want your object properties sorted), you can use the Map object.
You can insert your (key, value) pairs in sorted order and then doing a for..of
loop will guarantee having them loop in the order you inserted them
var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
console.log(key + " = " + value);
}
// 0 = zero
// 1 = one
Please check if your code is returning multiple res.send()
statements for a single request. Like when I had this issue....
I was this issue in my restify node application. The mistake was that
switch (status) {
case -1:
res.send(400);
case 0:
res.send(200);
default:
res.send(500);
}
I was handling various cases using switch without writing break. For those little familiar with switch case know that without break, return keywords. The code under case and next lines of it will be executed no matter what. So even though I want to send single res.send
, due to this mistake it was returning multiple res.send
statements, which prompted
error: can't set headers after they are sent to the client.
Which got resolved by adding this or using return before each res.send()
method like return res.send(200)
switch (status) {
case -1:
res.send(400);
break;
case 0:
res.send(200);
break;
default:
res.send(500);
break;
}
here is one line code
name = (city.getName() != null) ? city.getName() : "N/A";
here is example how it work, run below code in js file and understand the result. This ("Data" != null)
is condition as we do in normal if()
and "Data"
is statement when this condition became true. this " : "
act as else and "N/A"
is statement for else condition. Hope this help you to understand the logic.
name = ("Data" != null) ? "Data" : "N/A";_x000D_
_x000D_
console.log(name);
_x000D_
If copy-dependencies, unpack, pack, etc., are important for your project you shouldn't ignore it. You have to enclose your <plugins>
in <pluginManagement>
tested with Eclipse Indigo SR1, maven 2.2.1
env.OrderByDescending(x => x.ReportDate)
How about this code -
public static void main(String[] args) {
//Lets say we have a elements in array
int[] a = {13,65,13,67,88,65,88,23,65,88,92};
List<Integer> ls1 = new ArrayList<>();
List<Integer> ls2 = new ArrayList<>();
Set<Integer> ls3 = new TreeSet<>();
//Adding each element of the array in the list
for(int i=0;i<a.length;i++) {
{
ls1.add(a[i]);
}
}
//Iterating each element in the arrary
for (Integer eachInt : ls1) {
//If the list2 contains the iterating element, then add that into set<> (as this would be a duplicate element)
if(ls2.contains(eachInt)) {
ls3.add(eachInt);
}
else {ls2.add(eachInt);}
}
System.out.println("Elements in array or ls1"+ls1);
System.out.println("Duplicate Elements in Set ls3"+ls3);
}
I came here with the same Error, though one with a different origin.
It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.
An int
type is expected, not a np.float64
Solution: Try to install numpy 1.11.0
sudo pip install -U numpy==1.11.0.
The simplest way, based on @nosklo's comment and answer:
import tempfile
tmp = tempfile.mkdtemp()
But if you want to manually control the creation of the directories:
import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:
from shutil import rmtree
rmtree(tmp, ignore_errors=True)
This is similar to what applications like Google Chrome and Linux systemd
do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.
Reassign again. Like example = new String[(size)]
As I find it best to explain by example and none of the answers seem to do that...
A practical example of using reflections would be a Java Language Server written in Java or a PHP Language Server written in PHP, etc. Language Server gives your IDE abilities like autocomplete, jump to definition, context help, hinting types and more. In order to have all tag names (words that can be autocompleted) to show all the possible matches as you type the Language Server has to inspect everything about the class including doc blocks and private members. For that it needs a reflection of said class.
A different example would be a unit-test of a private method. One way to do so is to create a reflection and change the method's scope to public in the test's set-up phase. Of course one can argue private methods shouldn't be tested directly but that's not the point.
In centos 7 this works for me :
yum install mariadb-devel
pip install mysqlclient
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow
is a method defined for activities, and won't require you to find a View
first.
public static bool EqualsAny<T>(IEquatable<T> value, params T[] possibleMatches) {
foreach (T t in possibleMatches) {
if (value.Equals(t))
return true;
}
return false;
}
public static bool EqualsAny<T>(IEquatable<T> value, IEnumerable<T> possibleMatches) {
foreach (T t in possibleMatches) {
if (value.Equals(t))
return true;
}
return false;
}
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
By default, the C library buffers the output until it sees a return. To print out the results immediately, use fflush
:
while((c=getchar())!= EOF)
{
putchar(c);
fflush(stdout);
}
if you have subl set up to be called from the command line, the proper command to open the current directory is:
subl .
"OS X Command Line" is a link on how to make sure everything is set up.
@RSC
for me the critical addition in Xcode Version 6.2 (6C86e) is in override func viewDidLoad()
self.input.delegate = self;
Tried getting it to work with the return key for hours till I found your post, RSC. Thank you!
Also, if you want to hide the keyboard if you touch anywhere else on the screen:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
}
The problem with taking IEnumerable
as a parameter is that it tells callers "I wish to enumerate this". It doesn't tell them how many times you wish to enumerate.
I can change the objects parameter to be List and then avoid the possible multiple enumeration but then I don't get the highest object that I can handle.
The goal of taking the highest object is noble, but it leaves room for too many assumptions. Do you really want someone to pass a LINQ to SQL query to this method, only for you to enumerate it twice (getting potentially different results each time?)
The semantic missing here is that a caller, who perhaps doesn't take time to read the details of the method, may assume you only iterate once - so they pass you an expensive object. Your method signature doesn't indicate either way.
By changing the method signature to IList
/ICollection
, you will at least make it clearer to the caller what your expectations are, and they can avoid costly mistakes.
Otherwise, most developers looking at the method might assume you only iterate once. If taking an IEnumerable
is so important, you should consider doing the .ToList()
at the start of the method.
It's a shame .NET doesn't have an interface that is IEnumerable + Count + Indexer, without Add/Remove etc. methods, which is what I suspect would solve this problem.
"currently yes but i think it might cause problems at peak moments" I can confirm, that I had a problem where I got timeouts because of peak requests. After I set the max pool size, the application ran without any problems. IIS 7.5 / ASP.Net
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');
Add this code to your page:
<script type="text/javascript">
$(document).ready(function() {
$("input[type='submit']").click(function(){
$(this).css('background-color','red');
});
});
</script>
Try this or purpose will solve with lesser no of steps
for (int i = 0; i < a.length; i++)
{
for (int k = i+1; k < a.length; k++)
{
if (a[i] != a[k])
{
System.out.println(a[i]+"not the same with"+a[k]+"\n");
}
}
}
There are situations where you can't use the (quite convincing) with... for...
structure. In that case, do the following:
line = self.fo.readline()
if len(line) != 0:
if 'str' in line:
break
This will work because the the readline()
leaves a trailing newline character, where as EOF is just an empty string.
You could mess with the margins: http://jsfiddle.net/zV2p4/
But you would probably be better off using position: absolute
. This does not change display: block
, but it will make the width auto. To fix this, make the divs width: 100%
If your enum starts with 0 and the increment is always 1.
enum enumType
{
A = 0,
B,
C,
enumTypeEnd
};
for(int i=0; i<enumTypeEnd; i++)
{
enumType eCurrent = (enumType) i;
}
If not I guess the only why is to create something like a
vector<enumType> vEnums;
add the items, and use normal iterators....
You can add classes or style attributes on an element by element basis.
For example:
<a name="myelement" onclick="this.style.color='#FF0';">text</a>
Where you could do this.style.background, this.style.font-size, etc. You can also apply a style using this same method ala
this.className='classname';
If you want to do this in a javascript function, you can use getElementByID rather than 'this'.
https://github.com/cscott/jsshaper implements a translator from JavaScript 1.8 to ECMAScript 5.1, which would allow you to use 'for each' in code running on webkit or node.
In 2015 I would go with:
Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.
Or just wait for ECMA6, 7, ... :)
In general I would consider setting up of an environment variable (like PYTHONPATH)
to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.
Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the
test environment as well, leading to situations like the tests running fine for a
particular developer but probably failing when some one launches the tests.
Mike Schilling's solution with error handling with a shortcut for the error event handler.
function copyFile(source, target, cb) {
var cbCalled = false;
var rd = fs.createReadStream(source);
rd.on("error", done);
var wr = fs.createWriteStream(target);
wr.on("error", done);
wr.on("close", function(ex) {
done();
});
rd.pipe(wr);
function done(err) {
if (!cbCalled) {
cb(err);
cbCalled = true;
}
}
}
Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original.
browsing sometime ago, found this site, have you tried this alternative?
li{
list-style-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAE0lEQVQIW2NkYGD4D8RwwEi6AACaVAQBULo4sgAAAABJRU5ErkJggg==");
}
sounds hard, but you can make your own png image/pattern here, then copy/paste your code and customize your bullets =) stills elegant?
EDIT:
following the idea of @lea-verou on the other answer and applying this philosophy of outside sources enhancement I've come to this other solution:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
i.e.: fa-angle-right []
and use the last part of f... followed by a number like this, with the font-family
too:
li:before {
content: "\f105";
font-family: FontAwesome;
color: red; /* or whatever color you prefer */
margin-right: 4px;
}
and that's it! now you have custom bullet tips too =)
Have you checked the docstring of write()
? It says:
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
So you need to convert y
to str
first.
Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0)
to get to the beginning of the file.`
Edit: As for the IOError
, this issue seems related. A cite from there:
For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.
So, I suggest you try f.seek(0)
and maybe the problem goes away.
I would say that first and foremost: be consistent.
I reckon you are almost there with the conventions that you have outlined in your question. A couple of comments though:
Points 1 and 2 are good I reckon.
Point 3 - sadly this is not always possible. Think about how you would cope with a single table foo_bar
that has columns foo_id
and another_foo_id
both of which reference the foo
table foo_id
column. You might want to consider how to deal with this. This is a bit of a corner case though!
Point 4 - Similar to Point 3. You may want to introduce a number at the end of the foreign key name to cater for having more than one referencing column.
Point 5 - I would avoid this. It provides you with little and will become a headache when you want to add or remove columns from a table at a later date.
Some other points are:
Index Naming Conventions
You may wish to introduce a naming convention for indexes - this will be a great help for any database metadata work that you might want to carry out. For example you might just want to call an index foo_bar_idx1
or foo_idx1
- totally up to you but worth considering.
Singular vs Plural Column Names
It might be a good idea to address the thorny issue of plural vs single in your column names as well as your table name(s). This subject often causes big debates in the DB community. I would stick with singular forms for both table names and columns. There. I've said it.
The main thing here is of course consistency!
Had the same ssl-problem on my developer machine (php 7, xampp on windows) with a self signed certificate trying to fopen a "https://localhost/..."-file. Obviously the root-certificate-assembly (cacert.pem) didn't work. I just copied manually the code from the apache server.crt-File in the downloaded cacert.pem and did the openssl.cafile=path/to/cacert.pem entry in php.ini
Don’t need to specify a type
value of “text/css”
Every time you link to a CSS file:
<link rel="stylesheet" type="text/css" href="file.css">
You can simply write:
<link rel="stylesheet" href="file.css">
Try to use (focus)
and (focusout)
instead of onfocus
and onfocusout
like this : -
<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">
also you can use like this :-
some people prefer the on- prefix alternative, known as the canonical form:
<input name="date" type="text" on-focus="focusFunction()" on-focusout="focusOutFunction()">
Know more about event binding see here.
you have to use HostListner for your use case
Angular will invoke the decorated method when the host element emits the specified event.
@HostListener
is a decorator for the callback/event handler method
See my Update working Plunker.
Working Example Working Stackblitz
Some other events can be used in angular -
(focus)="myMethod()"
(blur)="myMethod()"
(submit)="myMethod()"
(scroll)="myMethod()"
Most likely you're looking for something like
var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();
provided that this is not something which happens on page load, in which case it should already be there from the start.
>>> import sys
>>> import traceback
>>> try:
... 5 / 0
... except ZeroDivisionError as e:
... type_, value_, traceback_ = sys.exc_info()
>>> traceback.format_tb(traceback_)
[' File "<stdin>", line 2, in <module>\n']
>>> value_
ZeroDivisionError('integer division or modulo by zero',)
>>> type_
<type 'exceptions.ZeroDivisionError'>
>>>
>>> 5 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
You use sys.exc_info() to collect the information and the functions in the traceback
module to format it.
Here are some examples for formatting it.
The whole exception string is at:
>>> ex = traceback.format_exception(type_, value_, traceback_)
>>> ex
['Traceback (most recent call last):\n', ' File "<stdin>", line 2, in <module>\n', 'ZeroDivisionError: integer division or modulo by zero\n']
Type casting of sockaddr
to sockaddr_in
and retrieval of ipv4 using inet_ntoa
char * ip = inet_ntoa(((struct sockaddr_in *)sockaddr)->sin_addr);
In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction()
but instead wrap your code in DB::beginTransaction
and DB::commit
/DB::rollback()
:
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();
// all good
} catch (\Exception $e) {
DB::rollback();
// something went wrong
}
See the transaction docs.
It seems there is no way to do this without custom view. You can get the title view:
View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android"));
But changing of gravity
or layout_gravity
doesn't have an effect.
The problem in the ActionBarView
, which layout its children by itself so changing of layout params of its children also doesn't have an effect.
To see this excecute following code:
ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);
Important question. The server I use (Ubuntu 12.04) had easy_install3
but not pip3
. This is how I installed Pip and then other packages to my home folder
Asked admin to install Ubuntu package python3-setuptools
Installed pip
Like this:
easy_install3 --prefix=$HOME/.local pip
mkdir -p $HOME/.local/lib/python3.2/site-packages
easy_install3 --prefix=$HOME/.local pip
Like this:
PATH="$HOME/.local/bin:$PATH"
echo PATH="$HOME/.local/bin:$PATH" > $HOME/.profile
like this
pip3 install --user httpie
# test httpie package
http httpbin.org
There is no runtime performance cost to using var. Though, I would suspect there to be a compiling performance cost as the compiler needs to infer the type, though this will most likely be negligable.
You can do it easily with ouzo goodies
$result = array_map(Functions::extract()->id, $arr);
or with Arrays (from ouzo goodies)
$result = Arrays::map($arr, Functions::extract()->id);
Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract
See also functional programming with ouzo (I cannot post a link).
The lock event ID is 4800, and the unlock is 4801. You can find them in the Security logs. You probably have to activate their auditing using Local Security Policy (secpol.msc, Local Security Settings in Windows XP) -> Local Policies -> Audit Policy. For Windows 10 see the picture below.
Look in Description of security events in Windows 7 and in Windows Server 2008 R2 under Subcategory: Other Logon/Logoff Events.
In order to add an EventListener to an element in angular 2+, we can use the method listen of the Renderer2 service (Renderer is deprecated, so use Renderer2):
listen(target: 'window'|'document'|'body'|any, eventName: string, callback: (event: any) => boolean | void): () => void
Example:
export class ListenDemo implements AfterViewInit {
@ViewChild('testElement')
private testElement: ElementRef;
globalInstance: any;
constructor(private renderer: Renderer2) {
}
ngAfterViewInit() {
this.globalInstance = this.renderer.listen(this.testElement.nativeElement, 'click', () => {
this.renderer.setStyle(this.testElement.nativeElement, 'color', 'green');
});
}
}
Note:
When you use this method to add an event listener to an element in the dom, you should remove this event listener when the component is destroyed
You can do that this way:
ngOnDestroy() {
this.globalInstance();
}
The way of use of ElementRef
in this method should not expose your angular application to a security risk. for more on this referrer to ElementRef security risk angular 2
You can do this without importing os or other libs.
If you want to get the path of current python script, use: __file__
If you want to get only the filename without .py extension, use this:
__file__.rsplit("/", 1)[1].split('.')[0]
@Drewid's answer didn't work in my Firefox 25 if the flash plugin is just disabled but installed.
@invertedSpear's comment in that answer worked in firefox but not in any IE version.
So combined both their code and got this. Tested in Google Chrome 31, Firefox 25, IE 8-10. Thanks Drewid and invertedSpear :)
var hasFlash = false;
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) {
hasFlash = true;
}
} catch (e) {
if (navigator.mimeTypes
&& navigator.mimeTypes['application/x-shockwave-flash'] != undefined
&& navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
hasFlash = true;
}
}
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
I fix it on my notebook. The rsyslog service did not listen on socket service.
I config this line bellow in /etc/rsyslog.conf
file and solved the problem:
$SystemLogSocketName /dev/log