You can simply use padding-left:60% (for ex) to align your content to right and simultaneously wrap the content in responsive container (I required navbar in my case) to ensure it works in all examples.
Try this
RelativeLayout relative = (RelativeLayout) findViewById(R.id.widget29);
relative.setBackgroundResource(0);
Check the setBackground functions in the RelativeLayout documentation
You can use an IF to test:
check:
@[ "${var}" ] || ( echo ">> var is not set"; exit 1 )
Result:
$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1
use the
innerHTML
property and access the td
using getElementById()
as always.
#if defined(CONDITION1) || defined(CONDITION2)
should work. :)
#ifdef
is a bit less typing, but doesn't work well with more complex conditions
To use Lambda expression you need to either create your own functional interface or use Java functional interface for operation that require two integer and return as value. IntBinaryOperator
Using user defined functional interface
interface TwoArgInterface {
public int operation(int a, int b);
}
public class MyClass {
public static void main(String javalatte[]) {
// this is lambda expression
TwoArgInterface plusOperation = (a, b) -> a + b;
System.out.println("Sum of 10,34 : " + plusOperation.operation(10, 34));
}
}
Using Java functional interface
import java.util.function.IntBinaryOperator;
public class MyClass1 {
static void main(String javalatte[]) {
// this is lambda expression
IntBinaryOperator plusOperation = (a, b) -> a + b;
System.out.println("Sum of 10,34 : " + plusOperation.applyAsInt(10, 34));
}
}
this code can be useful for you.
example of cursor use in sql server
DECLARE sampleCursor CURSOR FOR
SELECT K.Id FROM TableA K WHERE ....;
OPEN sampleCursor
FETCH NEXT FROM sampleCursor INTO @Id
WHILE @@FETCH_STATUS <> -1
BEGIN
UPDATE TableB
SET
...
git checkout .
will works otherwise it won't workSelect count(created_date) total
, created_dt
from table
group by created_date
order by created_date desc
A cookie is simply a short text string that is sent back and forth between the client and the server. You could store name=bob; password=asdfas
in a cookie and send that back and forth to identify the client on the server side. You could think of this as carrying on an exchange with a bank teller who has no short term memory, and needs you to identify yourself for each and every transaction. Of course using a cookie to store this kind information is horrible insecure. Cookies are also limited in size.
Now, when the bank teller knows about his/her memory problem, He/She can write down your information on a piece of paper and assign you a short id number. Then, instead of giving your account number and driver's license for each transaction, you can just say "I'm client 12"
Translating that to Web Servers: The server will store the pertinent information in the session object, and create a session ID which it will send back to the client in a cookie. When the client sends back the cookie, the server can simply look up the session object using the ID. So, if you delete the cookie, the session will be lost.
One other alternative is for the server to use URL rewriting to exchange the session id.
Suppose you had a link - www.myserver.com/myApp.jsp
You could go through the page and rewrite every URL as www.myserver.com/myApp.jsp?sessionID=asdf
or even www.myserver.com/asdf/myApp.jsp
and exchange the identifier that way. This technique is handled by the web application container and is usually turned on by setting the configuration to use cookieless sessions.
On Mac OS X, neither of these regex syntaxes work inside sed for matching whole words
\bmyWord\b
\<myWord\>
Hear me now and believe me later, this ugly syntax is what you need to use:
/[[:<:]]myWord[[:>:]]/
So, for example, to replace mint with minty for whole words only:
sed "s/[[:<:]]mint[[:>:]]/minty/g"
Source: re_format man page
For a single item enumerable in java it would be Collections.singleton("string");
In c# this is going to be more efficient than a new List:
public class SingleEnumerator<T> : IEnumerable<T>
{
private readonly T m_Value;
public SingleEnumerator(T value)
{
m_Value = value;
}
public IEnumerator<T> GetEnumerator()
{
yield return m_Value;
}
IEnumerator IEnumerable.GetEnumerator()
{
yield return m_Value;
}
}
but is there a simpler way using the framework?
You'll need to deal with File System Object
. See this OpenTextFile
method sample.
Facebook.com og:image is 325x325 (1:1 aspect ratio, square)
$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
I had this exact same problem. For me, this was the only thing that worked:
div.mainContainer { padding-top: 1px; }
It actually works with any number that's not zero. I really have no idea why this took care of it. I'm not that knowledgeable about CSS and HTML and it seems counterintuitive. Setting the body, html, h1
margins and paddings to 0 had no effect for me. I also had an h1
at the top of my page
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
First check the list:-
git stash list
copy the index you wanted to pop from the stash list
git stash pop stash@{index_number}
eg.:
git stash pop stash@{1}
docker ps -s will show the size of running containers only.
To check the size of all containers use docker ps -as
I opened up services.msc from the command prompt and disabled SQL Server reporting services
& SQL Server analysis services. These services were using port 80.
Then I restarted WAMP Server and it started working properly as before.
I'm sticking to the question as the title states and not the discussion. Which view is top visible on any given point?
@implementation UIView (Extra)
- (UIView *)findTopMostViewForPoint:(CGPoint)point
{
for(int i = self.subviews.count - 1; i >= 0; i--)
{
UIView *subview = [self.subviews objectAtIndex:i];
if(!subview.hidden && CGRectContainsPoint(subview.frame, point))
{
CGPoint pointConverted = [self convertPoint:point toView:subview];
return [subview findTopMostViewForPoint:pointConverted];
}
}
return self;
}
- (UIWindow *)topmostWindow
{
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
return win1.windowLevel - win2.windowLevel;
}] lastObject];
return topWindow;
}
@end
Can be used directly with any UIWindow as receiver or any UIView as receiver.
Your for
loop has no loop body:
elif option == 2:
print "please enter a number"
for x in range(x, 1, 1):
elif option == 0:
Actually, the whole if option == 1:
block has indentation problems. elif option == 2:
should be at the same level as the if
statement.
Hide And Show parent view of Activity Indicator
constructor(props) {
super(props)
this.state = {
isHidden: false
}
}
Hide and Show as Follow
{
this.state.isHidden ? <View style={style.activityContainer} hide={false}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}
Full reference
render() {
return (
<View style={style.mainViewStyle}>
<View style={style.signinStyle}>
<TextField placeholder='First Name' keyboardType='default' onChangeFirstName={(text) => this.setState({firstName: text.text})}/>
<TextField placeholder='Last Name' keyboardType='default' onChangeFirstName={(text) => this.setState({lastName: text.text})}/>
<TextField placeholder='Email' keyboardType='email-address' onChangeFirstName={(text) => this.setState({email: text.text})}/>
<TextField placeholder='Phone Number' keyboardType='phone-pad' onChangeFirstName={(text) => this.setState({phone: text.text})}/>
<TextField placeholder='Password' secureTextEntry={true} keyboardType='default' onChangeFirstName={(text) => this.setState({password: text.text})}/>
<Button style={AppStyleSheet.buttonStyle} title='Sign up' onPress={() => this.onSignupPress()} color='red' backgroundColor='black'/>
</View>
{
this.state.isHidden ? <View style={style.activityContainer}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}
</View>
);
}
On Button presss set state as follow
onSignupPress() {
this.setState({isHidden: true})
}
When you need to hide
this.setState({isHidden: false})
You can also do:
tree | grep filename
This pipes the output of the tree command to grep for a search. This will only tell you whether the file exists though.
For 4.x version
$('#select2Id').val(__INDEX__).trigger('change');
to select value with INDEX
$('#select2Id').val('').trigger('change');
to select nothing (show placeholder if it is)
One technique, suggested by this article, would be to do this:
<img style="background:url(thumbnail1.jpg)" src="magnifying_glass.png" />
If you're using guava (and you should be, see effective java item #15):
ImmutableList<String> list = ImmutableList.copyOf(s.split(","));
There is a good stackoverflow answer here by Mark Rajcok:
AngularJS directive controllers requiring parent directive controllers?
with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/
<div ng-controller="MyCtrl">
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
this.componentFunction = function() {
$scope.screenCtrl.doSomethingScreeny();
}
},
link: function(scope, element, attrs, screenCtrl) {
scope.screenCtrl = screenCtrl
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
If there is only ever one line then do something like this:
using System;
using System.IO;
class Program
{
static void Main()
{
String[] values = File.ReadAllText(@"d:\test.csv").Split(',');
}
}
So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.
While ENV
, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG
and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args
at every build without changing our docker file.
For more details, you can refer this.
You should map your virtual network drive in Windows.
net use x: \\vboxsvr\<your_shared_folder_name>
X:
in My Computer
In your case execute net use x: \\vboxsvr\win7
For those, who use 'copy' command in Build Events (Pre-build event command line or/and Post-build event command line) from Project -> Properties: target folder should exist
First, the second is not equivalent to the other two. $#array
returns the last index of the array, which is one less than the size of the array.
The other two are virtually the same. You are simply using two different means to create scalar context. It comes down to a question of readability.
I personally prefer the following:
say 0+@array; # Represent @array as a number
I find it clearer than
say scalar(@array); # Represent @array as a scalar
and
my $size = @array;
say $size;
The latter looks quite clear alone like this, but I find that the extra line takes away from clarity when part of other code. It's useful for teaching what @array
does in scalar context, and maybe if you want to use $size
more than once.
It sounds like a slippery slope to something that'd be posted on thedailywtf.com, "ManagerOfPeopleWhoHaveMortgages", etc.
I suppose it's right that one monolithic Manager class is not good design, but using 'Manager' is not bad. Instead of UserManager we might break it down to UserAccountManager, UserProfileManager, UserSecurityManager, etc.
'Manager' is a good word because it clearly shows a class is not representing a real-world 'thing'. 'AccountsClerk' - how am I supposed to tell if that's a class which manages user data, or represents someone who is an Accounts Clerk for their job?
The real answer is no (at least not by itself). You can still write your own code to do it.
If the function return Nothing, you can try this below
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != Nothing)
{
...
}
<input type="text" autocomplete="off" />
I had this problem too but it looks like it depends on the Kubernetes offering and how everything was installed. In Azure, if you are using acs-engine install, you can find the shell script that is actually being run to provision it at:
/opt/azure/containers/provision.sh
To get a more fine-grained understanding, just read through it and run the commands that it specifies. For me, I had to run as root:
systemctl enable kubectl
systemctl restart kubectl
I don't know if the enable is necessary and I can't say if these will work with your particular installation, but it definitely worked for me.
You can use List as a classifier for many fields, but you need wrap null values into Optional:
Function<String, List> classifier = (item) -> List.of(
item.getFieldA(),
item.getFieldB(),
Optional.ofNullable(item.getFieldC())
);
Map<List, List<Item>> grouped = items.stream()
.collect(Collectors.groupingBy(classifier));
The technique I use for having percentage width of the parent is adding an extra spacer view in combination with some flexbox. This will not apply to all scenarios but it can be very helpful.
So here we go:
class PercentageWidth extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.percentageWidthView}>
{/* Some content */}
</View>
<View style={styles.spacer}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row'
},
percentageWidthView: {
flex: 60
},
spacer: {
flex: 40
}
});
Basically the flex property is the width relative to the "total" flex of all items in the flex container. So if all items sum to 100 you have a percentage. In the example I could have used flex values 6 & 4 for the same result, so it's even more FLEXible.
If you want to center the percentage width view: add two spacers with half the width. So in the example it would be 2-6-2.
Of course adding the extra views is not the nicest thing in the world, but in a real world app I can image the spacer will contain different content.
This worked for me on Ubuntu 16.04 with v5.7.15 MySQL:
First, make sure you have mysql-client installed (sudo apt-get install mysql-client
).
Open terminal and login:
mysql -uroot -p
(then type your password)
After that:
use mysql;
update user set authentication_string=password(''), plugin='mysql_native_password' where user='root';
(tnx @Stanislav Karakhanov)
And the very last important thing is to reset mysql service:
sudo service mysql restart
You should now be able to login (without passsword) also by using MySQL Workbench.
If you want to have cd functionality (assuming shell=True) and still want to change the directory in terms of the Python script, this code will allow 'cd' commands to work.
import subprocess
import os
def cd(cmd):
#cmd is expected to be something like "cd [place]"
cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
out = p.stdout.read()
err = p.stderr.read()
# read our output
if out != "":
print(out)
os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline
if err != "":
print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
return
You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.
Usually, you can login as the postgres user:
Open a Terminal and do sudo su postgres
.
Now, after entering your admin password, you are able to launch psql
and do
CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';
This creates a new admin user. If you want to list the existing users, you could also do
\du
to list all users and then
ALTER USER yourusername WITH PASSWORD 'yournewpass';
In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.
<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>
Will give you:
What the...heck is going on?
and not
What the...
heck is going on?
You can also pass value directly via URL.
If you want to call method
public static void calling(string name){....}
then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya);
webrequest.Method = "GET";
webrequest.ContentType = "application/text";
Just make sure you are using ?Object = value
in URL
Sadly, I am not aware of a way to do this in sh. However, using bash (starting in version 3.0.0, which is probably what you have), you can use the =~ operator like this:
#!/bin/bash
CURRENT_DIR=`pwd`
if [[ "$CURRENT_DIR" =~ "String1" ]]
then
echo "String1 present"
elif [[ "$CURRENT_DIR" =~ "String2" ]]
then
echo "String2 present"
else
echo "Else"
fi
As an added bonus (and/or a warning, if your strings have any funny characters in them), =~ accepts regexes as the right operand if you leave out the quotes.
I just solved this issue myself. You were on the right track.
@media (min-width: 1200px) {
.container{
max-width: 970px;
}
}
Here we say: On viewports 1200px or larger - set container max-width to 970px. This will overwrite the standard class that currently sets max-width to 1170px for that range.
NOTE: Make sure you include this AFTER the bootstrap.css stuff (everyone has made this little mistake in the past).
Hope this helps.. good luck!
Simply call window.frameElement
from your framed page.
If the page is not in a frame then frameElement
will be null
.
The other way (getting the window element inside a frame is less trivial) but for sake of completeness:
/**
* @param f, iframe or frame element
* @return Window object inside the given frame
* @effect will append f to document.body if f not yet part of the DOM
* @see Window.frameElement
* @usage myFrame.document = getFramedWindow(myFrame).document;
*/
function getFramedWindow(f)
{
if(f.parentNode == null)
f = document.body.appendChild(f);
var w = (f.contentWindow || f.contentDocument);
if(w && w.nodeType && w.nodeType==9)
w = (w.defaultView || w.parentWindow);
return w;
}
Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...
for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}
Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.
That only works for numbers less than 1.
select to_char(12.34, '0D99') from dual;
-- Result: #####
This won't work.
You could do something like this but this results in leading whitespaces:
select to_char(12.34, '999990D99') from dual;
-- Result: ' 12,34'
Ultimately, you could add a TRIM to get rid of the whitespaces again but I wouldn't consider that a proper solution either...
select trim(to_char(12.34, '999990D99')) from dual;
-- Result: 12,34
Again, this will only work for numbers with 6 digits max.
Edit: I wanted to add this as a comment on DCookie's suggestion but I can't.
The following would do but only will replace one occurence:
"string".replace('/', 'ForwardSlash');
For a global replacement, or if you prefer regular expressions, you just have to escape the slash:
"string".replace(/\//g, 'ForwardSlash');
Simplest of All Solutions:
Use:
filtered_df = df[(df['col1'] >= 1) & (df['col1'] <= 5)]
Another Example, To filter the dataframe for values belonging to Feb-2018, use the below code
filtered_df = df[(df['year'] == 2018) & (df['month'] == 2)]
I collaborated with one of my coworkers to start the PyRestTest framework for this reason: https://github.com/svanoort/pyresttest
Although you can work with the tests in Python, the normal test format is in YAML.
Sample test suite for a basic REST app -- verifies that APIs respond correctly, checking HTTP status codes, though you can make it examine response bodies as well:
---
- config:
- testset: "Tests using test app"
- test: # create entity
- name: "Basic get"
- url: "/api/person/"
- test: # create entity
- name: "Get single person"
- url: "/api/person/1/"
- test: # create entity
- name: "Get single person"
- url: "/api/person/1/"
- method: 'DELETE'
- test: # create entity by PUT
- name: "Create/update person"
- url: "/api/person/1/"
- method: "PUT"
- body: '{"first_name": "Gaius","id": 1,"last_name": "Baltar","login": "gbaltar"}'
- headers: {'Content-Type': 'application/json'}
- test: # create entity by POST
- name: "Create person"
- url: "/api/person/"
- method: "POST"
- body: '{"first_name": "Willim","last_name": "Adama","login": "theadmiral"}'
- headers: {Content-Type: application/json}
The best way is to use the following code:
<a href="<?php echo base_url() ?>directory_name/filename.php">Link</a>
From Java8:
import java.time.Instant;
import java.util.Date;
Date date = Date.from(Instant.parse("2000-01-01T00:00:00.000Z"))
In python 3, to get text output:
import io
import urllib.request
response = urllib.request.urlopen("http://google.com")
text = io.TextIOWrapper(response)
android studio 4.1.1
applicationVariants.all { variant ->
variant.outputs.all { output ->
def reversion = "118"
def date = new java.text.SimpleDateFormat("yyyyMMdd").format(new Date())
def versionName = defaultConfig.versionName
outputFileName = "MyApp_${versionName}_${date}_${reversion}.apk"
}
}
You can use FindIndex
var index = Array.FindIndex(myArray, row => row.Author == "xyz");
Edit: I see you have an array of string, you can use any code to match, here an example with a simple contains:
var index = Array.FindIndex(myArray, row => row.Contains("Author='xyz'"));
Maybe you need to match using a regular expression?
This code works in my case, after a lot of research. You will require to install the request npm package.
var url = "http://api.example.com/api/v1/?param1=1¶m2=2";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.checkApi = function (req, res) {
// do the GET request
request.get({
url: url,
headers: {
"Authorization": auth
}
}, function (error, response, body) {
if(error)
{ console.error("Error while communication with api and ERROR is : " + error);
res.send(error);
}
console.log('body : ', body);
res.send(body);
});
}
Just use
$('#SelectBoxId option:selected').text();
For Getting text as listed
$('#SelectBoxId').val();
For Getting selected Index value
I changed my layout XML file name and found out later that of the XML file (widget provider in this case) still refers to the old layout XML which doesn't exist, and that prevented the auto generation/correction of R class.
Date.parse()
isn't a constructor, its a static method.
So, just use
var timeInMillis = Date.parse(s);
instead of
var timeInMillis = new Date.parse(s);
If you want to grab the query parameter value in the URL, follow below code pieces
//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid
If you want to grab the URL parameter using Express param function
Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.
This can be used for validations or grabbing important information about item.
An example for this would be:
// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {
// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';
// save name to the request
req.tagid= modified;
next();
});
// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});
In python, we start defining a function with "def" and generally, but not necessarily, end the function with "return".
A function of variable x is denoted as f(x). What this function does? Suppose, this function adds 2 to x. So, f(x)=x+2
Now, the code of this function will be:
def A_function (x):
return x + 2
After defining the function, you can use that for any variable and get result. Such as:
print A_function (2)
>>> 4
We could just write the code slightly differently, such as:
def A_function (x):
y = x + 2
return y
print A_function (2)
That would also give "4".
Now, we can even use this code:
def A_function (x):
x = x + 2
return x
print A_function (2)
That would also give 4. See, that the "x" beside return actually means (x+2), not x of "A_function(x)".
I guess from this simple example, you would understand the meaning of return command.
After all i got the answer thanks to wikisona, first the beans:
@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
return new TomcatEmbeddedServletContainerFactory() {
@Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatEmbeddedServletContainer(tomcat);
}
@Override
protected void postProcessContext(Context context) {
ContextResource resource = new ContextResource();
resource.setName("jdbc/myDataSource");
resource.setType(DataSource.class.getName());
resource.setProperty("driverClassName", "your.db.Driver");
resource.setProperty("url", "jdbc:yourDb");
context.getNamingResources().addResource(resource);
}
};
}
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myDataSource");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource)bean.getObject();
}
the full code it's here: https://github.com/wilkinsona/spring-boot-sample-tomcat-jndi
Note that as others have pointed out mysql_real_escape_string() will solve the problem (as will addslashes), however you should always use mysql_real_escape_string() for security reasons - consider:
SELECT * FROM valid_users WHERE username='$user' AND password='$password'
What if the browser sends
user="admin' OR (user=''"
password="') AND ''='"
The query becomes:
SELECT * FROM valid_users
WHERE username='admin' OR (user='' AND password='') AND ''=''
i.e. the security checks are completely bypassed.
C.
I believe you want bgcolor. Something like this:
document.getElementById("button").bgcolor="#ffffff";
Here are a couple of demos that might help:
Rule of three in C++ is a fundamental principle of the design and the development of three requirements that if there is clear definition in one of the following member function, then the programmer should define the other two members functions together. Namely the following three member functions are indispensable: destructor, copy constructor, copy assignment operator.
Copy constructor in C++ is a special constructor. It is used to build a new object, which is the new object equivalent to a copy of an existing object.
Copy assignment operator is a special assignment operator that is usually used to specify an existing object to others of the same type of object.
There are quick examples:
// default constructor
My_Class a;
// copy constructor
My_Class b(a);
// copy constructor
My_Class c = a;
// copy assignment operator
b = a;
I found that the answer by cballou was no longer working in Firefox as of Jan. 2014. Specifically, if (self.pageYOffset)
didn't trigger if the client had scrolled right, but not down - because 0
is a falsey number. This went undetected for a while because Firefox supported document.body.scrollLeft
/Top
, but this is no longer working for me (on Firefox 26.0).
Here's my modified solution:
var getPageScroll = function(document_el, window_el) {
var xScroll = 0, yScroll = 0;
if (window_el.pageYOffset !== undefined) {
yScroll = window_el.pageYOffset;
xScroll = window_el.pageXOffset;
} else if (document_el.documentElement !== undefined && document_el.documentElement.scrollTop) {
yScroll = document_el.documentElement.scrollTop;
xScroll = document_el.documentElement.scrollLeft;
} else if (document_el.body !== undefined) {// all other Explorers
yScroll = document_el.body.scrollTop;
xScroll = document_el.body.scrollLeft;
}
return [xScroll,yScroll];
};
Tested and working in FF26, Chrome 31, IE11. Almost certainly works on older versions of all of them.
The answer is not to add a newline after writing your string. That may solve a different problem. What you are asking is how to add a newline before you start appending your string. If you want to add a newline, but only if one does not already exist, you need to find out first, by reading the file.
For example,
with open('hst.txt') as fobj:
text = fobj.read()
name = 'Bob'
with open('hst.txt', 'a') as fobj:
if not text.endswith('\n'):
fobj.write('\n')
fobj.write(name)
You might want to add the newline after name, or you may not, but in any case, it isn't the answer to your question.
To produce key events without Windows Forms Context, We can use the following method,
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
sample code is given below:
const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28; //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
//Press the key
keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
return 0;
}
List of Virtual Keys are defined here.
To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html
Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like
'C:/xxxxxx/pom.xml' already exists in VFS
Here is what I found would work.
echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only
Here's a comprehensive yet non-exhaustive list of examples of list
operations and whether or not they are thread safe.
Hoping to get an answer regarding the obj in a_list
language construct here.
Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.
You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/
Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.
This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
Working solution for MVC
public ActionResult Index()
{
string fileName = "test.pdf";
string fileName1 = "test.vsix";
string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\test\test.pdf");
byte[] fileBytes1 = System.IO.File.ReadAllBytes(@"C:\test\test.vsix");
byte[] compressedBytes;
using (var outStream = new MemoryStream())
{
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
using (var entryStream = fileInArchive.Open())
using (var fileToCompressStream = new MemoryStream(fileBytes))
{
fileToCompressStream.CopyTo(entryStream);
}
var fileInArchive1 = archive.CreateEntry(fileName1, CompressionLevel.Optimal);
using (var entryStream = fileInArchive1.Open())
using (var fileToCompressStream = new MemoryStream(fileBytes1))
{
fileToCompressStream.CopyTo(entryStream);
}
}
compressedBytes = outStream.ToArray();
}
return File(compressedBytes, "application/zip", fileNameZip);
}
What for..in loop does is that it creates a new variable (var someVariable) and then stores each property of the given object in this new variable(someVariable) one by one. Therefore if you use block {}, you can iterate. Consider the following example.
var obj = {
name:'raman',
hobby:'coding',
planet:'earth'
};
for(var someVariable in obj) {
//do nothing..
}
console.log(someVariable); // outputs planet
Using the constraints
features UniqueConstraint
is preferred over unique_together.
From the Django documentation for unique_together
:
Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.
For example:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
]
You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True
and create and run migration.
Just my solution with dropdown image (inline svg)
select.form-control {
-webkit-appearance: none;
-webkit-border-radius: 0px;
background-image: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24' viewBox='0 0 24 24'><path fill='%23444' d='M7.406 7.828l4.594 4.594 4.594-4.594 1.406 1.406-6 6-6-6z'></path></svg>");
background-position: 100% 50%;
background-repeat: no-repeat;
}
I'm using bootstrap that's why I used select.form-control
You can use select{
or select.your-custom-class{
instead.
HEAD~ specifies the first parent on a "branch"
HEAD^ allows you to select a specific parent of the commit
An Example:
If you want to follow a side branch, you have to specify something like
master~209^2~15
if still not resolved try adding this to your package.js
scripts
"scripts": { "gulp": "gulp" },
and run npm run gulp
it will runt gulp scripts from gulpfile.js
db.getCollection('orders').aggregate([
{$group: {
_id: {name: "$name"},
uniqueIds: {$addToSet: "$_id"},
count: {$sum: 1}
}
},
{$match: {
count: {"$gt": 1}
}
}
])
First Group Query the group according to the fields.
Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.
Just as a small addition, you can also do an apply if you have a complex function that you apply to a single column:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html
df[b] = df[a].apply(lambda col: do stuff with col here)
pg_dump -d <databasename> -h <hostname> -p <port> -n <schemaname> -f <location of the dump file>
Please notice that you have sufficient privilege to access that schema.
If you want take backup as specific user add user name in that command preceded by -U
There are two separate concepts here:
Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:
void f() {
int i;
i = 1; // OK: in scope
}
void g() {
i = 2; // Error: not in scope
}
Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:
int i;
void f() {
i = 1; // OK: in scope
}
void g() {
i = 2; // OK: still in scope
}
(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)
Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.
for (int i = 0; i < 5; ++i) {
int n = 0;
printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}
Static variables (pedantically, variables with static storage duration) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.
for (int i = 0; i < 5; ++i) {
static int n = 0;
printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}
Note that the static
keyword has various meanings apart from static storage duration. On a global variable or function, it gives it internal linkage so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto
keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
I was facing similar issue and found out that this error was due to incorrect rules set for read/write operations for real time database. By default google firebase nowadays loads cloud store not real time database. We need to switch to real time and apply the correct rules.
As we can see it says cloud Firestore not real time database, once switched to correct database apply below rules:
{
"rules": {
".read": true,
".write": true
}
}
important: in this kind of error you should look for simple mistakes in most cases
besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.
Switch back to the master branch using
$ git checkout master
and then run the git pull
operation
$ git pull origin/master
Afterwards, you can switch back to your my_branch
again.
It depends on your requirements. If IPet is simple enough, I would prefer to implement that. Otherwise, if PetBase implements a ton of functionality you don't want to duplicate, then have at it.
The downside to implementing a base class is the requirement to override
(or new
) existing methods. This makes them virtual methods which means you have to be careful about how you use the object instance.
Lastly, the single inheritance of .NET kills me. A naive example: Say you're making a user control, so you inherit UserControl
. But, now you're locked out of also inheriting PetBase
. This forces you to reorganize, such as to make a PetBase
class member, instead.
If you set the AllowsTransparency
property on the Window
(even without setting any transparency values) the border disappears and you can only resize via the grip.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
WindowStyle="None"
AllowsTransparency="True"
ResizeMode="CanResizeWithGrip">
<!-- Content -->
</Window>
Result looks like:
Giving us the whole error message would be much more useful. If it's for make install then you're probably trying to install something to a system directory and you're not root. If you have root access then you can run
sudo make install
or log in as root and do the whole process as root.
Simply you can follow the link. its very simple and very easy to use. I am using this. Its working fine.
use like this
//include the file
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {
//do some code
}
// Any tablet device.
if( $detect->isTablet() ){
//do some code
}
I have solved this Issue by this blog:http://android-developers.blogspot.com/2014/10/appcompat-v21-material-design-for-pre.html
The problem is you use the wrong theme,you can choose theme that like Theme.AppCompat.NoActionBar, in my project,it works.
I hope to help you?
If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.
I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11
Another way
num1 = (20*boolVar)+(num1*(not boolVar))
Here is the best solution for searching inside HTML table while covering all of the table, (all td, tr in the table), pure javascript and as short as possible:
<input id='myInput' onkeyup='searchTable()' type='text'>
<table id='myTable'>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
</table>
<script>
function searchTable() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
tr[i].style.display = "none";
}
}
}
</script>
A note about reliability:
Since the newline character is as valid as any in a file name, any solution that relies on lines like the head
/tail
based ones are flawed.
With GNU ls
, another option is to use the --quoting-style=shell-always
option and a bash
array:
eval "files=($(ls -t --quoting-style=shell-always))"
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"
(add the -A
option to ls
if you also want to consider hidden files).
If you want to limit to regular files (disregard directories, fifos, devices, symlinks, sockets...), you'd need to resort to GNU find
.
With bash 4.4 or newer (for readarray -d
) and GNU coreutils 8.25 or newer (for cut -z
):
readarray -t -d '' files < <(
LC_ALL=C find . -maxdepth 1 -type f ! -name '.*' -printf '%T@/%f\0' |
sort -rzn | cut -zd/ -f2)
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"
Or recursively:
readarray -t -d '' files < <(
LC_ALL=C find . -name . -o -name '.*' -prune -o -type f -printf '%T@%p\0' |
sort -rzn | cut -zd/ -f2-)
Best here would be to use zsh
and its glob qualifiers instead of bash
to avoid all this hassle:
Newest regular file in the current directory:
printf '%s\n' *(.om[1])
Including hidden ones:
printf '%s\n' *(D.om[1])
Second newest:
printf '%s\n' *(.om[2])
Check file age after symlink resolution:
printf '%s\n' *(-.om[1])
Recursively:
printf '%s\n' **/*(.om[1])
Also, with the completion system (compinit
and co) enabled, Ctrl+Xm becomes a completer that expands to the newest file.
So:
vi Ctrl+Xm
Would make you edit the newest file (you also get a chance to see which it before you press Return).
vi Alt+2Ctrl+Xm
For the second-newest file.
vi *.cCtrl+Xm
for the newest c
file.
vi *(.)Ctrl+Xm
for the newest regular file (not directory, nor fifo/device...), and so on.
.
character as a wildcard to match any single character.Example regex: a.c
abc // match
a c // match
azc // match
ac // no match
abbc // no match
[]
to match any characters in a set.\w
to match any single alphanumeric character: 0-9
, a-z
, A-Z
, and _
(underscore).\d
to match any single digit.\s
to match any single whitespace character.Example 1 regex: a[bcd]c
abc // match
acc // match
adc // match
ac // no match
abbc // no match
Example 2 regex: a[0-7]c
a0c // match
a3c // match
a7c // match
a8c // no match
ac // no match
a55c // no match
Use the hat in square brackets [^]
to match any single character except for any of the characters that come after the hat ^
.
Example regex: a[^abc]c
aac // no match
abc // no match
acc // no match
a c // match
azc // match
ac // no match
azzc // no match
(Don't confuse the ^
here in [^]
with its other usage as the start of line character: ^
= line start, $
= line end.)
Use the optional character ?
after any character to specify zero or one occurrence of that character. Thus, you would use .?
to match any single character optionally.
Example regex: a.?c
abc // match
a c // match
azc // match
ac // match
abbc // no match
In my case, I had generated DbContext from an existing database. I had my connection string set in appSettings.json
file; however, when I generated the class files by scaffolding the DbContext class it had incorrect connection string.
So make sure your connection string is proper in appSettings.json
file as well as in DbContext
file. This will solve your issue.
I was able to go around the whole thing by replacing the context reference from this
or Context.this
to getapplicationcontext
.
How about htis:
Private Sub ArrangeWindows(Order As Window())
For I As Integer = 1 To Order.Length -1
Order(I).Owner = Order(I - 1)
Next
End Sub
grid is not a global, it is local to the main function. Change this:
int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int row, int column)
to this:
int nonrecursivecountcells(color grid[ROW_SIZE][COL_SIZE], int row, int column)
Basically you forgot to give that first param a name, grid will do since it matches your code.
Contruct your url via click event handler:
string strUrl = "/some/url/path" + myvar;
Then:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + strUrl + "','_blank')", true);
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
The best option is to use SVG Images on different devices :)
<img src="your-svg-image.svg" alt="Your Logo Alt" onerror="this.src='your-alternative-image.png'">
My direct solution for this issue : right click the project --> Maven ---> Add Dependency == then choose the name or parent name of missing dependency
Inspired from code found above (credits), the simple blocking (aka not CPU consuming) macOS version I was looking for:
import termios
import sys
import fcntl
import os
def getKeyCode(blocking = True):
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
if not blocking:
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
return ord(sys.stdin.read(1))
except IOError:
return 0
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
if not blocking:
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
def getKeyStroke():
code = getKeyCode()
if code == 27:
code2 = getKeyCode(blocking = False)
if code2 == 0:
return "esc"
elif code2 == 91:
code3 = getKeyCode(blocking = False)
if code3 == 65:
return "up"
elif code3 == 66:
return "down"
elif code3 == 68:
return "left"
elif code3 == 67:
return "right"
else:
return "esc?"
elif code == 127:
return "backspace"
elif code == 9:
return "tab"
elif code == 10:
return "return"
elif code == 195 or code == 194:
code2 = getKeyCode(blocking = False)
return chr(code)+chr(code2) # utf-8 char
else:
return chr(code)
while True:
print getKeyStroke()
2017-11-09, EDITED: Not tested with Python 3
The given answer will throw an error if used in Microsoft Excel 14.0 Object Library. Object does not contain a definition for get_range. Instead use
int countRows = xlWorkSheetData.UsedRange.Rows.Count;
int countColumns = xlWorkSheetData.UsedRange.Columns.Count;
object[,] data = xlWorkSheetData.Range[xlWorkSheetData.Cells[1, 1], xlWorkSheetData.Cells[countRows, countColumns]].Cells.Value2;
Use the getTime
method to get the time in total milliseconds since 1970-01-01, and subtract those:
var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();
To solve this without jQuery .each()
you'd have to fix your code like this:
var listItems = $("#productList").find("li");
var ind, len, product;
for ( ind = 0, len = listItems.length; ind < len; ind++ ) {
product = $(listItems[ind]);
// ...
}
Bugs in your original code:
for ... in
will also loop through all inherited properties; i.e. you will also get a list of all functions that are defined by jQuery.
The loop variable li
is not the list item, but the index to the list item. In that case the index is a normal array index (i.e. an integer)
Basically you are save to use .each()
as it is more comfortable, but espacially when you are looping bigger arrays the code in this answer will be much faster.
For other alternatives to .each()
you can check out this performance comparison:
http://jsperf.com/browser-diet-jquery-each-vs-for-loop
Just to get the aliases even shorter than the standard git config way mentioned in other answers, I created an npm package mingit (npm install -g mingit
) so that most commands would become 2 characters instead of 2 words. Here's the examples:
g a . // git add .
g b other-branch // git branch other-branch
g c "made some changes" // git commit -m "made some changes"
g co master // git checkout master
g d // git diff
g f // git fetch
g i // git init
g m hotfix // git merge hotfix
g pll // git pull
g psh // git push
g s // git status
and other commands would be similarly short. This also keeps bash completions. The package adds a bash function to your dotfiles, works on osx, linux, and windows. Also, unlike the other aliases, it aliases git
-> g
as well as the second parameter.
The examples have very different outcomes.
Before looking at the differences, the following should be noted:
[[Prototype]]
property.myObj.method()
) then this within the method references the object. Where this is not set by the call or by the use of bind, it defaults to the global object (window in a browser) or in strict mode, remains undefined.So here are the snippets in question:
var A = function () {
this.x = function () {
//do something
};
};
In this case, variable A
is assigned a value that is a reference to a function. When that function is called using A()
, the function's this isn't set by the call so it defaults to the global object and the expression this.x
is effective window.x
. The result is that a reference to the function expression on the right-hand side is assigned to window.x
.
In the case of:
var A = function () { };
A.prototype.x = function () {
//do something
};
something very different occurs. In the first line, variable A
is assigned a reference to a function. In JavaScript, all functions objects have a prototype property by default so there is no separate code to create an A.prototype object.
In the second line, A.prototype.x is assigned a reference to a function. This will create an x property if it doesn't exist, or assign a new value if it does. So the difference with the first example in which object's x property is involved in the expression.
Another example is below. It's similar to the first one (and maybe what you meant to ask about):
var A = new function () {
this.x = function () {
//do something
};
};
In this example, the new
operator has been added before the function expression so that the function is called as a constructor. When called with new
, the function's this is set to reference a new Object whose private [[Prototype]]
property is set to reference the constructor's public prototype. So in the assignment statement, the x
property will be created on this new object. When called as a constructor, a function returns its this object by default, so there is no need for a separate return this;
statement.
To check that A has an x property:
console.log(A.x) // function () {
// //do something
// };
This is an uncommon use of new since the only way to reference the constructor is via A.constructor. It would be much more common to do:
var A = function () {
this.x = function () {
//do something
};
};
var a = new A();
Another way of achieving a similar result is to use an immediately invoked function expression:
var A = (function () {
this.x = function () {
//do something
};
}());
In this case, A
assigned the return value of calling the function on the right-hand side. Here again, since this is not set in the call, it will reference the global object and this.x
is effective window.x
. Since the function doesn't return anything, A
will have a value of undefined
.
These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods:
var A = function () {
this.objectsOwnProperties = "are serialized";
};
A.prototype.prototypeProperties = "are NOT serialized";
var instance = new A();
console.log(instance.prototypeProperties); // "are NOT serialized"
console.log(JSON.stringify(instance));
// {"objectsOwnProperties":"are serialized"}
Related questions:
Sidenote: There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy.
JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.
I'd recommend :Rename
from tpope's eunuch for this.
It also includes a bunch of other handy commands.
The Rename command is defined as follows therein currently (check the repo for any updates!):
command! -bar -nargs=1 -bang -complete=file Rename :
\ let s:file = expand('%:p') |
\ setlocal modified |
\ keepalt saveas<bang> <args> |
\ if s:file !=# expand('%:p') |
\ call delete(s:file) |
\ endif |
\ unlet s:file
String str = "1,2,3,4,5,6,7,8,9,0";
String items[] = str.split(",");
int ent[] = new int[items.length];
for(i=0;i<items.length;i++){
try{
ent[i] = Integer.parseInt(items[i]);
System.out.println("#"+i+": "+ent[i]);//Para probar
}catch(NumberFormatException e){
//Error
}
}
To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:
Add to your footer and header this CSS:
position: relative;
EDITED:
Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...
Remove From the #backstretch:
z-index: -999999;
Read a little bit about Z-Index here!
I must cautiously doubt the previously accepted answer that using a DialogFragment is the best option. The intended (primary) purpose of the DialogFragment seems to be to display fragments that are dialogs themselves, not to display fragments that have dialogs to display.
I believe that using the fragment's activity to mediate between the dialog and the fragment is the preferable option.
You can do this in very simple way using size property of angular modal.
var modal = $modal.open({
templateUrl: "/partials/welcome",
controller: "welcomeCtrl",
backdrop: "static",
scope: $scope,
size:'lg' // you can try different width like 'sm', 'md'
});
You can find if the textbox is disabled using is
method by passing :disabled
selector to it. Try this.
if($('textbox').is(':disabled')){
//textbox is disabled
}
For files encoding...
public class FRomUtf8ToIso {
static File input = new File("C:/Users/admin/Desktop/pippo.txt");
static File output = new File("C:/Users/admin/Desktop/ciccio.txt");
public static void main(String[] args) throws IOException {
BufferedReader br = null;
FileWriter fileWriter = new FileWriter(output);
try {
String sCurrentLine;
br = new BufferedReader(new FileReader( input ));
int i= 0;
while ((sCurrentLine = br.readLine()) != null) {
byte[] isoB = encode( sCurrentLine.getBytes() );
fileWriter.write(new String(isoB, Charset.forName("ISO-8859-15") ) );
fileWriter.write("\n");
System.out.println( i++ );
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
static byte[] encode(byte[] arr){
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-15");
ByteBuffer inputBuffer = ByteBuffer.wrap( arr );
// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);
// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();
return outputData;
}
}
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT
There are several problems here:
DateTime.Now
instead of Start
DateTime.Now
is a value of type DateTime
, not Integer
, so the assignment wouldn't work anywayStart
variable anyway; it's doing no goodtotal.Text
is a property of type String
- not DateTime
or Integer
(Some of these would only show up at execution time unless you have Option Strict
on, which you really should.)
You should use:
total.Text = DateTime.Now.ToString()
... possibly specifying a culture and/or format specifier if you want the result in a particular format.
Here is a fully worked example based on the top voted answer, which is:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
// task completed within timeout
} else {
// timeout logic
}
The main advantage of the implementation in this answer is that generics have been added, so the function (or task) can return a value. This means that any existing function can be wrapped in a timeout function, e.g.:
Before:
int x = MyFunc();
After:
// Throws a TimeoutException if MyFunc takes more than 1 second
int x = TimeoutAfter(MyFunc, TimeSpan.FromSeconds(1));
This code requires .NET 4.5.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskTimeout
{
public static class Program
{
/// <summary>
/// Demo of how to wrap any function in a timeout.
/// </summary>
private static void Main(string[] args)
{
// Version without timeout.
int a = MyFunc();
Console.Write("Result: {0}\n", a);
// Version with timeout.
int b = TimeoutAfter(() => { return MyFunc(); },TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", b);
// Version with timeout (short version that uses method groups).
int c = TimeoutAfter(MyFunc, TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", c);
// Version that lets you see what happens when a timeout occurs.
try
{
int d = TimeoutAfter(
() =>
{
Thread.Sleep(TimeSpan.FromSeconds(123));
return 42;
},
TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", d);
}
catch (TimeoutException e)
{
Console.Write("Exception: {0}\n", e.Message);
}
// Version that works on tasks.
var task = Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(1));
return 42;
});
// To use async/await, add "await" and remove "GetAwaiter().GetResult()".
var result = task.TimeoutAfterAsync(TimeSpan.FromSeconds(2)).
GetAwaiter().GetResult();
Console.Write("Result: {0}\n", result);
Console.Write("[any key to exit]");
Console.ReadKey();
}
public static int MyFunc()
{
return 42;
}
public static TResult TimeoutAfter<TResult>(
this Func<TResult> func, TimeSpan timeout)
{
var task = Task.Run(func);
return TimeoutAfterAsync(task, timeout).GetAwaiter().GetResult();
}
private static async Task<TResult> TimeoutAfterAsync<TResult>(
this Task<TResult> task, TimeSpan timeout)
{
var result = await Task.WhenAny(task, Task.Delay(timeout));
if (result == task)
{
// Task completed within timeout.
return task.GetAwaiter().GetResult();
}
else
{
// Task timed out.
throw new TimeoutException();
}
}
}
}
Caveats
Having given this answer, its generally not a good practice to have exceptions thrown in your code during normal operation, unless you absolutely have to:
Only use this code if you absolutely cannot alter the function you are calling so it times out after a specific TimeSpan
.
This answer is really only applicable when dealing with 3rd party library libraries that you simply cannot refactor to include a timeout parameter.
How to write robust code
If you want to write robust code, the general rule is this:
Every single operation that could potentially block indefinitely, must have a timeout.
If you do not observe this rule, your code will eventually hit an operation that fails for some reason, then it will block indefinitely, and your app has just permanently hung.
If there was a reasonable timeout after some time, then your app would hang for some extreme amount of time (e.g. 30 seconds) then it would either display an error and continue on its merry way, or retry.
A _ttoi
function can convert CString
to integer, both wide char and ansi char can work. Below is the details:
CString str = _T("123");
int i = _ttoi(str);
Defining a specific version to upgrade helped me instead of only the upgrade command.
pip3 install larapy-installer==0.4.01 -U
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
Pycharm 2020.3.3 CE ZorinOS(Linux) File>Settings > Project Structure > {select the folder} > Mark as Source(blue folder icon) > Apply
To verify:
import sys
print(sys.path)
Selected path should be listed here.
I just catch this "EmptyResultDataAccessException"
public Myclass findOne(String id){
try {
Myclass m = this.jdbcTemplate.queryForObject(
"SELECT * FROM tb_t WHERE id = ?",
new Object[]{id},
new RowMapper<Myclass>() {
public Myclass mapRow(ResultSet rs, int rowNum) throws SQLException {
Myclass m = new Myclass();
m.setName(rs.getString("name"));
return m;
}
});
return m;
} catch (EmptyResultDataAccessException e) { // result.size() == 0;
return null;
}
}
then you can check:
if(m == null){
// insert operation.
}else{
// update operation.
}
Most browsers have a native JSON
object these days, which includes parse
and stringify
methods. So just try JSON.stringify({})
and see if you get "{}"
. You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2)
puts a newline and 2 spaces in front of each key.
JSON.stringify({a:1,b:2}, null, 2)
gives
"{\n \"a\": 1,\n \"b\": 2\n}"
which prints as
{
"a": 1,
"b": 2
}
As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :
The replacer parameter can either be a function or an array of String/Numbers. It steps through each member within the JSON object to let you decide what value each member should be changed to. As a function it can return:
- A number, string, or Boolean, which replaces the property's original value with the returned one.
- An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
- Null, which causes the property to be removed.
As an array, the values defined inside it corresponds to the names of the properties inside the JSON object that should be retained when converted into a JSON object.
Separate function to make adding event handlers much easier.
function addListener(event, obj, fn) {
if (obj.addEventListener) {
obj.addEventListener(event, fn, false); // modern browsers
} else {
obj.attachEvent("on"+event, fn); // older versions of IE
}
}
element = document.getElementsByClassName('drill_cursor')[0];
addListener('click', element, function () {
// Do stuff
});
There are different open source libraries, which you can use for parsing json.
org.json :- If you want to read or write json then you can use this library. First create JsonObject :-
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values :-
String id = jsonObj.getString("id");
You can see complete example here
Jackson databind :- If you want to bind and parse your json to particular POJO class, then you can use jackson-databind library, this will bind your json to POJO class :-
ObjectMapper mapper = new ObjectMapper();
post= mapper.readValue(json, Post.class);
You can see complete example here
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
to Vilx-:
var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
table = table.parentNode;
and what if row.parentNode
is TBODY
?
You should check it out first, and after that
do while
by .tBodies
, probably
You can go to your /var/lib/pgsql/data/pg_hba.conf file and add trust in place of Ident It worked for me.
local all all trust
host all 127.0.0.1/32 trust
For further details refer to this issue Ident authentication failed for user
You can easily use .replace()
as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change.
Let me explain by;
>>stuff = "bin and small"
>>stuff.replace('and', ',')
>>print(stuff)
"big and small" #no change
To observe the change you want to apply, you can assign same or another variable;
>>stuff = "big and small"
>>stuff = stuff.replace("and", ",")
>>print(stuff)
'big, small'
The other answers were incorrect, at least in my case. request.path
does not provide the full url, only the relative url, e.g. /paper/53
. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path
.
df.groupby('Company Name').agg({'Organisation name':'count','Amount':'sum'})\
.apply(lambda x: x.sort_values(['count','sum'], ascending=False))
Using str(e)
or repr(e)
to represent the exception, you won't get the actual stack trace, so it is not helpful to find where the exception is.
After reading other answers and the logging package doc, the following two ways works great to print the actual stack trace for easier debugging:
logger.debug()
with parameter exc_info
try:
# my code
except SomeError as e:
logger.debug(e, exc_info=True)
logger.exception()
or we can directly use logger.exception()
to print the exception.
try:
# my code
except SomeError as e:
logger.exception(e)
Did you put void while calling your function?
For example:
void something(int x){
logic..
}
int main() {
**void** something();
return 0;
}
If so, you should delete the last void.
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
The regular representation that is used by print
can be get using the str()
function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42))
gives you '2008-11-22 19:53:42'
.
The alternative representation that is used to represent the object nature (as a data). It can be get using the repr()
function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42))
gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'
.
What happened is that when you have printed the date using print
, it used str()
so you could see a nice date string. But when you have printed mylist
, you have printed a list of objects and Python tried to represent the set of data, using repr()
.
Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.
When you want to display them, just use str()
. In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date)
.
One last thing. When you tried to print the dates, you printed mylist
. If you want to print a date, you must print the date objects, not their container (the list).
E.G, you want to print all the date in a list :
for date in mylist :
print str(date)
Note that in that specific case, you can even omit str()
because print will use it for you. But it should not become a habit :-)
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22
Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime()
method.
strftime()
expects a string pattern explaining how you want to format your date.
E.G :
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
All the letter after a "%"
represent a format for something:
%d
is the day number (2 digits, prefixed with leading zero's if necessary)%m
is the month number (2 digits, prefixed with leading zero's if necessary)%b
is the month abbreviation (3 letters)%B
is the month name in full (letters)%y
is the year number abbreviated (last 2 digits)%Y
is the year number full (4 digits)etc.
Have a look at the official documentation, or McCutchen's quick reference you can't know them all.
Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)
border-bottom-color: #b3b3b3;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-bottom-style: solid;
border-bottom-width: 1px;
border-left-color: #b3b3b3;
border-left-style: solid;
border-left-width: 1px;
border-right-color: #b3b3b3;
border-right-style: solid;
border-right-width: 1px;
border-top-color: #b3b3b3;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
border-top-style: solid;
border-top-width: 1px;
...Who cares IE6 we are in 2011 upgrade and wake up please!
It wont work like this.
When you try to insert the row using a query all values should be there in query.
With the above problem you want to insert
magazine_subscription_id, subscription_name, magazine_id, status
in select query you have
magazine_subscription_id, subscription_name, magazine_id, status
1 it is not possible.
If you want to insert either you need to insert using query of direct values
Just use Array.from(iterable, [mapFn])
.
var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);
var newArr = Array.from(myMap.values(), value => value + 1);
You're looking for this on the command line (for a class called MyClass):
On Unix/Linux:
javap -verbose MyClass | grep "major"
On Windows:
javap -verbose MyClass | findstr "major"
You want the major version from the results. Here are some example values:
There is no algorithm which can find all the cycles in a directed graph in polynomial time. Suppose, the directed graph has n nodes and every pair of the nodes has connections to each other which means you have a complete graph. So any non-empty subset of these n nodes indicates a cycle and there are 2^n-1 number of such subsets. So no polynomial time algorithm exists. So suppose you have an efficient (non-stupid) algorithm which can tell you the number of directed cycles in a graph, you can first find the strong connected components, then applying your algorithm on these connected components. Since cycles only exist within the components and not between them.
Also, consider to use a repository manager such as Nexus and configure all your repositories there.
From reading the source code, if a java.sql.Date
does actually have time information, calling getTime()
will return a value that includes the time information.
If that is not working, then the information is not in the java.sql.Date
object. I expect that the JDBC drivers or the database is (in effect) zeroing the time component ... or the information wasn't there in the first place.
I think you should be using java.sql.Timestamp
and the corresponding resultset methods, and the corresponding SQL type.
In my case, I had duplicate IDs in the source table, so none of the proposals worked. I don't care about performance, it's just done once. To solve this I took the records one by one with a cursor to ignore the duplicates.
So here's the code example:
DECLARE @c1 AS VARCHAR(12);
DECLARE @c2 AS VARCHAR(250);
DECLARE @c3 AS VARCHAR(250);
DECLARE MY_cursor CURSOR STATIC FOR
Select
c1,
c2,
c3
from T2
where ....;
OPEN MY_cursor
FETCH NEXT FROM MY_cursor INTO @c1, @c2, @c3
WHILE @@FETCH_STATUS = 0
BEGIN
if (select count(1)
from T1
where a1 = @c1
and a2 = @c2
) = 0
INSERT INTO T1
values (@c1, @c2, @c3)
FETCH NEXT FROM MY_cursor INTO @c1, @c2, @c3
END
CLOSE MY_cursor
DEALLOCATE MY_cursor
In case you just need to remove the duplicates using only ArrayList, no other Collection classes, then:-
//list is the original arraylist containing the duplicates as well
List<String> uniqueList = new ArrayList<String>();
for(int i=0;i<list.size();i++) {
if(!uniqueList.contains(list.get(i)))
uniqueList.add(list.get(i));
}
Hope this helps!
If you'd like to initialize the array to values other than 0, with gcc
you can do:
int array[1024] = { [ 0 ... 1023 ] = -1 };
This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99
to compile your code.
Now abortBroadcast();
method can be used for restricting the incoming message to go to inbox.
Better late than never. Here's a method that I devised (after reading this post) for returning a list of dates that includes: (a) day 1 of of the current month through today, PLUS (b) all dates for the past two months:
select (sysdate +1 - rownum) dt
from dual
connect by rownum <= (sysdate - add_months(sysdate - extract(day from sysdate),-2));
The "-2" is the number of prior full months of dates to include. For example, on July 10th, this SQL returns a list of all dates from May 1 through July 10 - i.e. two full prior months plus the current partial month.
This worked for me:
in web.config file;
<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>
haha...I have the same question. When initViews() just do like this.The sequence is the key, listener is the last. Good Luck !
spinner.setAdapter(adapter);
spinner.setSelection(position);
spinner.setOnItemSelectedListener(listener);
In RunCommand
write "MSINFO32"
and hit enter
It will show All information related to system
For Eclipse, modify project.properties
like this: (your path please)
android.library.reference.1=../../../../workspace/appcompat_v7_22
And remove android-support-v4.jar
file in your project's libs
folder.
Eran Hammer-Lahav has done an excellent job in explaining the majority of the differences in his article Introducing OAuth 2.0. To summarize, here are the key differences:
More OAuth Flows to allow better support for non-browser based applications. This is a main criticism against OAuth from client applications that were not browser based. For example, in OAuth 1.0, desktop applications or mobile phone applications had to direct the user to open their browser to the desired service, authenticate with the service, and copy the token from the service back to the application. The main criticism here is against the user experience. With OAuth 2.0, there are now new ways for an application to get authorization for a user.
OAuth 2.0 no longer requires client applications to have cryptography. This hearkens back to the old Twitter Auth API, which didn't require the application to HMAC hash tokens and request strings. With OAuth 2.0, the application can make a request using only the issued token over HTTPS.
OAuth 2.0 signatures are much less complicated. No more special parsing, sorting, or encoding.
OAuth 2.0 Access tokens are "short-lived". Typically, OAuth 1.0 Access tokens could be stored for a year or more (Twitter never let them expire). OAuth 2.0 has the notion of refresh tokens. While I'm not entirely sure what these are, my guess is that your access tokens can be short lived (i.e. session based) while your refresh tokens can be "life time". You'd use a refresh token to acquire a new access token rather than have the user re-authorize your application.
Finally, OAuth 2.0 is meant to have a clean separation of roles between the server responsible for handling OAuth requests and the server handling user authorization. More information about that is detailed in the aforementioned article.
You can update your Bitbucket credentials from the OSX Keychain.
Updating your cached credentials via the command line:
$ git credential-osxkeychain erase
host=bitbucket.org
protocol=https
[press return]
If it's successful, nothing will print out. To test that it works, try and clone a repository from Bitbucket. If you are prompted for a password, the keychain entry was deleted.
Say you had some URL that gave you JSON data like:
{'field': 'value'}
...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g. http://example.com/dataSource?callback=myCallback
). Then it would return:
myCallback({'field':'value'})
...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called myFunction
and execute this script, it will be called with the data from the URL.
The cool thing about this is: you can create a script tag and use your URL (complete with callback
parameter) as the src
attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).
This is what jQuery does when you make an ajax request (using .ajax
with 'jsonp' as the value for the dataType
property). E.g.
$.ajax({
url: 'http://example.com/datasource',
dataType: 'jsonp',
success: function(data) {
// your code to handle data here
}
});
Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.
If you are able to copy the actual SQLite database file to your desktop, you can use this tools to browse the data.
You can use _.mapValues(users, function(o) { return o.age; });
in Lodash and _.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });
in Underscore.
Check out the cross-documentation here: http://jonathanpchen.com/underdash-api/#mapvalues-object-iteratee-identity
Use split and join method
$("#idBut").click(function() {
$("body").children().each(function() {
$(this).html($(this).html().split('@').join("$"));
});
});
here is solution
I want to select the distinct values from one column 'GrondOfLucht' but they should be sorted in the order as given in the column 'sortering'. I cannot get the distinct values of just one column using
Select distinct GrondOfLucht,sortering
from CorWijzeVanAanleg
order by sortering
It will also give the column 'sortering' and because 'GrondOfLucht' AND 'sortering' is not unique, the result will be ALL rows.
use the GROUP to select the records of 'GrondOfLucht' in the order given by 'sortering
SELECT GrondOfLucht
FROM dbo.CorWijzeVanAanleg
GROUP BY GrondOfLucht, sortering
ORDER BY MIN(sortering)
Swift 4 & iOs 11+
@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .destructive, title: "Delete") { _, _, handler in
handler(true)
// handle deletion here
}
let more = UIContextualAction(style: .normal, title: "More") { _, _, handler in
handler(true)
// handle more here
}
return UISwipeActionsConfiguration(actions: [delete, more])
}
You can use this to merge date and time into the same column of dataframe.
import pandas as pd
data_file = 'data.csv' #path of your file
Reading .csv file with merged columns Date_Time:
data = pd.read_csv(data_file, parse_dates=[['Date', 'Time']])
You can use this line to keep both other columns also.
data.set_index(['Date', 'Time'], drop=False)
According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO
option or a certificate directory can be specified with the CURLOPT_CAPATH
option.
Also look at CURLOPT_SSL_VERIFYHOST:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
Since everything did not work, found that errors don't show when opening the project as solution (.sln), while the error shows when opening the project as a project.
You can also use animationListener, something like this:
fadeIn.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
this.startAnimation(fadeout);
}
});
I did another attempt to simplify this and achieve it without the necessity of a container.
HTML
.box1 {
background-color: #ff0000;
width: 200px;
float: left;
}
.box2 {
background-color: #00ff00;
width: 200px;
float: right;
}
.box3 {
background-color: #0fffff;
width: 200px;
margin: 0 auto;
}
CSS
.box1 {
background-color: #ff0000;
width: 200px;
float: left;
}
.box2 {
background-color: #00ff00;
width: 200px;
float: right;
}
.box3 {
background-color: #0fffff;
width: 200px;
margin: 0 auto;
}
You can see it live at JSFiddle
DataTable dt = new DataTable("EMPLOYEE_LIST");
DataColumn eeCode = dt.Columns.Add("EMPLOYEE_CODE", typeof(String));
DataColumn taxYear = dt.Columns.Add("TAX_YEAR", typeof(String));
DataColumn intData = dt.Columns.Add("INT_DATA", typeof(int));
DataColumn textData = dt.Columns.Add("TEXT_DATA", typeof(String));
dt.PrimaryKey = new DataColumn[] { eeCode, taxYear };
It filters data table with eecode and taxyear combinedly considered as unique
Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0
Yes it is possible. You need one ON for each join table.
LEFT JOIN ab
ON ab.sht = cd.sht
LEFT JOIN aa
ON aa.sht = cd.sht
Incidentally my personal formatting preference for complex SQL is described in http://bentilly.blogspot.com/2011/02/sql-formatting-style.html. If you're going to be writing a lot of this, it likely will help.
You can create your own custom auth schemas that use the Authorization:
header - for example, this is how OAuth works.
As a general rule, if servers or proxies don't understand the values of standard headers, they will leave them alone and ignore them. It is creating your own header keys that can often produce unexpected results - many proxies will strip headers with names they don't recognise.
Having said that, it is possibly a better idea to use cookies to transmit the token, rather than the Authorization:
header, for the simple reason that cookies were explicitly designed to carry custom values, whereas the specification for HTTP's built in auth methods does not really say either way - if you want to see exactly what it does say, have a look here.
The other point about this is that many HTTP client libraries have built-in support for Digest and Basic auth but may make life more difficult when trying to set a raw value in the header field, whereas they will all provide easy support for cookies and will allow more or less any value within them.
Elastic search Get all record where condition not empty.
const searchQuery = {
body: {
query: {
query_string: {
default_field: '*.*',
query: 'feildName: ?*',
},
},
},
index: 'IndexName'
};
For new linux users this could be a daunting task. Let me update this with mysql 8(the latest version available right now is 8.0.12 as on 12-Sep-2018)
That's it.
As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: Client
executes Proxy.method()
.
(I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: www.noelvaes.eu)
something like this is close: (untested code)
byte[] data; // data goes here.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = userNetworkCredentials;
request.Method = "PUT";
request.ContentType = "application/octet-stream";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data,0,data.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
temp = reader.ReadToEnd();
reader.Close();
Check if a modal is open
$('.modal:visible').length && $('body').hasClass('modal-open')
To attach an event listener
$(document).on('show.bs.modal', '.modal', function () {
// run your validation... ( or shown.bs.modal )
});
There is another solution. The next code is bad (although I think pandas needs this feature):
import pandas as pd
# empty dataframe
a = pd.DataFrame()
a.loc[0] = {'first': 111, 'second': 222}
But the next code runs fine:
import pandas as pd
# empty dataframe
a = pd.DataFrame()
a = a.append(pd.Series({'first': 111, 'second': 222}, name=0))
Here's a snippet I used - with plain SimpleDateFormat
. Hope somebody else may benefit from it:
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") {
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos) {
StringBuffer toFix = super.format(date, toAppendTo, pos);
return toFix.insert(toFix.length()-2, ':');
};
};
// Usage:
System.out.println(dateFormat.format(new Date()));
}
Output:
- Usual Output.........: 2013-06-14T10:54:07-0200
- This snippet's Output: 2013-06-14T10:54:07-02:00
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
// Usage:
System.out.println(dateFormat2.format(new Date()));
Output:
- This pattern's output: 2013-06-14T10:54:07-02:00
See the docs for that.
Sometimes you just don't have a choice about having to store numbers mixed with text. In one of our applications, the web site host we use for our e-commerce site makes filters dynamically out of lists. There is no option to sort by any field but the displayed text. When we wanted filters built off a list that said things like 2" to 8" 9" to 12" 13" to 15" etc, we needed it to sort 2-9-13, not 13-2-9 as it will when reading the numeric values. So I used the SQL Server Replicate function along with the length of the longest number to pad any shorter numbers with a leading space. Now 20 is sorted after 3, and so on.
I was working with a view that gave me the minimum and maximum lengths, widths, etc for the item type and class, and here is an example of how I did the text. (LBnLow and LBnHigh are the Low and High end of the 5 length brackets.)
REPLICATE(' ', LEN(LB5Low) - LEN(LB1High)) + CONVERT(NVARCHAR(4), LB1High) + '" and Under' AS L1Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB2Low)) + CONVERT(NVARCHAR(4), LB2Low) + '" to ' + CONVERT(NVARCHAR(4), LB2High) + '"' AS L2Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB3Low)) + CONVERT(NVARCHAR(4), LB3Low) + '" to ' + CONVERT(NVARCHAR(4), LB3High) + '"' AS L3Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB4Low)) + CONVERT(NVARCHAR(4), LB4Low) + '" to ' + CONVERT(NVARCHAR(4), LB4High) + '"' AS L4Text,
CONVERT(NVARCHAR(4), LB5Low) + '" and Over' AS L5Text
Using Request.Url.Host
is appropriate - it's how you retrieve the value of the HTTP Host:
header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858
is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority
.
Furthermore, it is not valid to get somedomain.com
from www.somedomain.com
because a webserver could be configured to serve a different site for www.somedomain.com
compared to somedomain.com
, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.')
works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config
) is a red-herring.
Here is your solution for the problem,
$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
if(ord($i) % 2 != 0)
$letter[] .= $i;
}
print_r($letter);
You need to get the ASCII value for that character which will solve your problem.
Here is ord doc and working code.
For your requirement, you can do like this,
for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
$letter[] .= $i;
}
print_r($letter);
Here set $x as per your requirement.
Outter joins don't work "as expected" in that case because you have explicitly told Oracle you only want data if that criteria on that table matches. In that scenario, the outter join is rendered useless.
A work-around
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
(SELECT account_type_standard_seq.nextval FROM DUAL),
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
[Edit] If you expect multiple rows from a sub-select, you can add ROWNUM=1 to each where clause OR use an aggregate such as MAX or MIN. This of course may not be the best solution for all cases.
[Edit] Per comment,
(SELECT account_type_standard_seq.nextval FROM DUAL),
can be just
account_type_standard_seq.nextval,
If you create an Audio element using:
var a = new Audio("my_audio_file.wav");
And add a suspend
event listener via:
a.addEventListener("suspend", function () {console.log('suspended')}, false);
And then load the file into mobile Safari (iPad or iPhone), you'll see the 'suspended' get logged in the developer console. According to the HTML5 spec, this means, "The user agent is intentionally not currently fetching media data, but does not have the entire media resource downloaded."
Calling a subsequent a.load(), testing for the "canplay" event and then using a.play() seems like a suitable method for auto triggering the sound.
Use like blow
$(function (a) {
. . . . .then in your function you can using msie property like
if (a.browser.msie)
{
}
else
{
$(settings.current).after(Uploadelement);
}
goodluck
Check the User-Agent and in case it's Mobile Safari, open a myprotocol:// URL to (attempt) to open the iPhone app and have it open Mobile iTunes to the download of the app in case the attempt fails
This sounds a reasonable approach to me, but I don't think you'll be able to get it to open mobile itunes as a second resort. I think you'll have to pick one or the other - either redirect to your app or to itunes.
i.e. if you redirect to myprotocol://, and the app isn't on the phone, you won't get a second chance to redirect to itunes.
You could perhaps first redirect to an (iphone optimised) landing page and give the user the option to click through to your app, or to itunes to get the app if they don't have it? But, you'll be relying on the user to do the right thing there. (Edit: though you could set a cookie so that is a first-time thing only?)
This is somewhat ago but it still might be useful.
My experience shows that resizing the image in-memory before passing it to tesseract sometimes helps.
Try different modes of interpolation. The post https://stackoverflow.com/a/4756906/146003 helped me a lot.
There are some existing implementations of tail on pypi which you can install using pip:
Depending on your situation, there may be advantages to using one of these existing tools.
You can try this one
img{
max-height:500px;
max-width:500px;
height:auto;
width:auto;
}
This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px
You can check this post
Here is a fast implementation using numba (mind the types). Note it does contain nans where shifted.
import numpy as np
import numba as nb
@nb.jit(nb.float64[:](nb.float64[:],nb.int64),
fastmath=True,nopython=True)
def moving_average( array, window ):
ret = np.cumsum(array)
ret[window:] = ret[window:] - ret[:-window]
ma = ret[window - 1:] / window
n = np.empty(window-1); n.fill(np.nan)
return np.concatenate((n.ravel(), ma.ravel()))
I try lots of ways and finally try this:
def db_persist(func):
def persist(*args, **kwargs):
func(*args, **kwargs)
try:
session.commit()
logger.info("success calling db func: " + func.__name__)
return True
except SQLAlchemyError as e:
logger.error(e.args)
session.rollback()
return False
return persist
and :
@db_persist
def insert_or_update(table_object):
return session.merge(table_object)
Same functionality i recently achieved using below function.
I wanted to enable SAVE button on edit.
Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.
Hope it helps you.
function checkAnyFormFieldEdited() {
/*
* If any field is edited,then only it will enable Save button
*/
$(':text').keypress(function(e) { // text written
enableSaveBtn();
});
$(':text').keyup(function(e) {
if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
enableSaveBtn();
} else { // rest ignore
e.preventDefault();
}
});
$(':text').bind('paste', function(e) { // text pasted
enableSaveBtn();
});
$('select').change(function(e) { // select element changed
enableSaveBtn();
});
$(':radio').change(function(e) { // radio changed
enableSaveBtn();
});
$(':password').keypress(function(e) { // password written
enableSaveBtn();
});
$(':password').bind('paste', function(e) { // password pasted
enableSaveBtn();
});
}
These are the methods of system.console
(There are more system.console methods like write() and writeline() as well which are used to write in command line, behaving similarly as read() and readline() methods)
This was clearly described with examples in the MSDN documentation (links are included above).
this might be a dirty code but i think it can suffice
<div v-for="(counter in counters">
{{ counter }}) {{ userlist[counter-1].name }}
</div>
on your script add this one
data(){return {userlist: [],user_id: '',counters: 0,edit: false,}},
Here's what's usually sufficient for me:
I create a serialization mixin which I use with my models. The serialization function basically fetches whatever attributes the SQLAlchemy inspector exposes and puts it in a dict.
from sqlalchemy.inspection import inspect
class Serializer(object):
def serialize(self):
return {c: getattr(self, c) for c in inspect(self).attrs.keys()}
@staticmethod
def serialize_list(l):
return [m.serialize() for m in l]
All that's needed now is to extend the SQLAlchemy model with the Serializer
mixin class.
If there are fields you do not wish to expose, or that need special formatting, simply override the serialize()
function in the model subclass.
class User(db.Model, Serializer):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String)
password = db.Column(db.String)
# ...
def serialize(self):
d = Serializer.serialize(self)
del d['password']
return d
In your controllers, all you have to do is to call the serialize()
function (or serialize_list(l)
if the query results in a list) on the results:
def get_user(id):
user = User.query.get(id)
return json.dumps(user.serialize())
def get_users():
users = User.query.all()
return json.dumps(User.serialize_list(users))