to detect when the iframe has loaded and its document is ready?
It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).
If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:
<img id="x" ... />
<script type="text/javascript">
document.getElementById('x').onload= function() {
...
};
</script>
there is no guarantee that the item won't already have loaded by the time the script executes.
The ways out of load-races are:
on IE, you can use the ‘readyState’ property to see if something's already loaded;
if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;
the old-school way of including it in the markup:
<img onload="callback(this)" ... />
Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.
From Wikipedia Media type,
A media type is composed of a type, a subtype, and optional parameters. As an example, an HTML file might be designated text/html; charset=UTF-8.
Media type consists of top-level type name and sub-type name, which is further structured into so-called "trees".
top-level type name / subtype name [ ; parameters ]
top-level type name / [ tree. ] subtype name [ +suffix ] [ ; parameters ]
All media types should be registered using the IANA registration procedures. Currently the following trees are created: standard
, vendor
, personal
or vanity
, unregistered x.
Standard:
Media types in the standards tree do not use any tree facet (prefix).
type / media type name [+suffix]
Examples: "application/xhtml+xml", "image/png"
Vendor:
Vendor tree is used for media types associated with publicly available products. It uses
vnd.
facet.
type / vnd. media type name [+suffix] - used in the case of well-known producer
type / vnd. producer's name followed by media type name [+suffix] - producer's name must be approved by IANA
type / vnd. producer's name followed by product's name [+suffix] - producer's name must be approved by IANA
Personal or Vanity tree:
Personal or Vanity tree includes media types created experimentally or as part of products that are not distributed commercially. It uses
prs.
facet.
type / prs. media type name [+suffix]
Unregistered x. tree:
The "x." tree may be used for media types intended exclusively for use in private, local environments and only with the active agreement of the parties exchanging them. Types in this tree cannot be registered.
According to the previous version of RFC 6838 - obsoleted RFC 2048 (published in November 1996) it should rarely, if ever, be necessary to use unregistered experimental types, and as such use of both "x-" and "x." forms is discouraged. Previous versions of that RFC - RFC 1590 and RFC 1521 stated that the use of "x-" notation for the sub-type name may be used for unregistered and private sub-types, but this recommendation was obsoleted in November 1996.
type / x. media type name [+suffix]
So its clear that the standard type MIME type application/pdf
is the appropriate one to use while you should avoid using the obsolete and unregistered x-
media type as stated in RFC 2048 and RFC 6838.
In my case the problem was the 32/64 bit driver which I solved by configuring the properties of the sql server job:
I dont think python has a catch :)
try:
connection = manager.connect("I2Cx")
except Exception, e:
print e
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
You could try to debug the problem using valgrind:
The Valgrind distribution currently includes six production-quality tools: a memory error detector, two thread error detectors, a cache and branch-prediction profiler, a call-graph generating cache profiler, and a heap profiler. It also includes two experimental tools: a heap/stack/global array overrun detector, and a SimPoint basic block vector generator. It runs on the following platforms: X86/Linux, AMD64/Linux, PPC32/Linux, PPC64/Linux, and X86/Darwin (Mac OS X).
I think problem is in
3 + ', ' + 4
change it to
'3' + ', ' + '4'
DECLARE @ExcludedList VARCHAR(MAX)
SET @ExcludedList = '3' + ', ' + '4' + ' ,' + '22'
SELECT * FROM A WHERE Id NOT IN (@ExcludedList)
SET @ExcludedListe such that your query should become
either
SELECT * FROM A WHERE Id NOT IN ('3', '4', '22')
or
SELECT * FROM A WHERE Id NOT IN (3, 4, 22)
Use the following location where you can find all ~AutoRecover.~vs*.sql
(autorecovery files):
C:\Users\<YourUserName>\Documents\SQL Server Management Studio\Backup Files\Solution1
Might be you forgotten to place the Main class and Test Case class in /src/test/java. Check it Once.
You can do something like that
<div style="background-image: url(http://your-image.jpg); position:relative;">
<img src="http://your-image.jpg" style="opacity: 0;" />
<div style="position: absolute;top: 0;width: 100%;height: 100%;">my content goes here</div>
</div>
A solution would be to force the key files to be kept permanently, by adding them in your ~/.ssh/config
file:
IdentityFile ~/.ssh/gitHubKey
IdentityFile ~/.ssh/id_rsa_buhlServer
If you do not have a 'config' file in the ~/.ssh directory, then you should create one. It does not need root rights, so simply:
nano ~/.ssh/config
...and enter the lines above as per your requirements.
For this to work the file needs to have chmod 600. You can use the command chmod 600 ~/.ssh/config
.
If you want all users on the computer to use the key put these lines into /etc/ssh/ssh_config
and the key in a folder accessible to all.
Additionally if you want to set the key specific to one host, you can do the following in your ~/.ssh/config :
Host github.com
User git
IdentityFile ~/.ssh/githubKey
This has the advantage when you have many identities that a server doesn't reject you because you tried the wrong identities first. Only the specific identity will be tried.
TIMESTAMP is 4 bytes Vs 8 bytes for DATETIME.
http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
But like scronide said it does have a lower limit of the year 1970. It's great for anything that might happen in the future though ;)
A cleaner approach would be to create a Person
object that contains contactName
, contactPhone
, etc. Then, use an ArrayList
rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:
while (!done) {
Person person = new Person();
String name = input.nextLine();
person.setContactName(name);
...
myPersonList.add(person);
}
Using the list will remove the need for array bounds checking.
Gradle nicely combines both Ant and Maven, taking the best from both frameworks. Flexibility from Ant and convention over configuration, dependency management and plugins from Maven.
So if you want to have a standard java build, like in maven, but test task has to do some custom step it could look like below.
build.gradle:
apply plugin:'java'
task test{
doFirst{
ant.copy(toDir:'build/test-classes'){fileset dir:'src/test/extra-resources'}
}
doLast{
...
}
}
On top of that it uses groovy syntax which gives much more expression power then ant/maven's xml.
It is a superset of Ant - you can use all Ant tasks in gradle with nicer, groovy-like syntax, ie.
ant.copy(file:'a.txt', toDir:"xyz")
or
ant.with{
delete "x.txt"
mkdir "abc"
copy file:"a.txt", toDir: "abc"
}
While editing the file, make marks where you want the start and end to be using
ma
- sets the a
mark
mb
- sets the b
mark
Then, to copy that into another file, just use the w
command:
:'a,'bw /name/of/output/file.txt
Use a library.
Just created this:
https://gist.github.com/3854049
//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");
//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');
Service references are another example where partial classes are useful to separate generated code from user-created code.
You can "extend" the service classes without having them overwritten when you update the service reference.
Prior answers focused on nominal data (e.g. unordered). If there is a reason to impose order for an ordinal variable, then one would use:
# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')
# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']
# Setup the ordering
df.zipcode_ordered.cat.set_categories(
new_categories = [90211, 90210], ordered = True, inplace = True
)
# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
# zipcode_category zipcode_ordered zipcode_ordered_id
# 90210 90210 1
# 90211 90211 0
More details on setting ordered categories can be found at the pandas website:
https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order
Since using the @Value("new Long("myconfig")") with cast could throw error on startup if the config is not found or if not in the same expected number format
We used the following approach and is working as expected with fail safe check.
@Configuration()
public class MyConfiguration {
Long DEFAULT_MAX_IDLE_TIMEOUT = 5l;
@Value("db.timeoutInString")
private String timeout;
public Long getTimout() {
final Long timoutVal = StringUtil.parseLong(timeout);
if (null == timoutVal) {
return DEFAULT_MAX_IDLE_TIMEOUT;
}
return timoutVal;
}
}
Check this blog Don't use code to remove headers. It is unstable according Microsoft
My take on this:
<system.webServer>
<httpProtocol>
<!-- Security Hardening of HTTP response headers -->
<customHeaders>
<!--Sending the new X-Content-Type-Options response header with the value 'nosniff' will prevent
Internet Explorer from MIME-sniffing a response away from the declared content-type. -->
<add name="X-Content-Type-Options" value="nosniff" />
<!-- X-Frame-Options tells the browser whether you want to allow your site to be framed or not.
By preventing a browser from framing your site you can defend against attacks like clickjacking.
Recommended value "x-frame-options: SAMEORIGIN" -->
<add name="X-Frame-Options" value="SAMEORIGIN" />
<!-- Setting X-Permitted-Cross-Domain-Policies header to “master-only” will instruct Flash and PDF files that
they should only read the master crossdomain.xml file from the root of the website.
https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
<add name="X-Permitted-Cross-Domain-Policies" value="master-only" />
<!-- X-XSS-Protection sets the configuration for the cross-site scripting filter built into most browsers.
Recommended value "X-XSS-Protection: 1; mode=block". -->
<add name="X-Xss-Protection" value="1; mode=block" />
<!-- Referrer-Policy allows a site to control how much information the browser includes with navigations away from a document and should be set by all sites.
If you have sensitive information in your URLs, you don't want to forward to other domains
https://scotthelme.co.uk/a-new-security-header-referrer-policy/ -->
<add name="Referrer-Policy" value="no-referrer-when-downgrade" />
<!-- Remove x-powered-by in the response header, required by OWASP A5:2017 - Do not disclose web server configuration -->
<remove name="X-Powered-By" />
<!-- Ensure the cache-control is public, some browser won't set expiration without that -->
<add name="Cache-Control" value="public" />
</customHeaders>
</httpProtocol>
<!-- Prerequisite for the <rewrite> section
Install the URL Rewrite Module on the Web Server https://www.iis.net/downloads/microsoft/url-rewrite -->
<rewrite>
<!-- Remove Server response headers (OWASP Security Measure) -->
<outboundRules rewriteBeforeCache="true">
<rule name="Remove Server header">
<match serverVariable="RESPONSE_Server" pattern=".+" />
<!-- Use custom value for the Server info -->
<action type="Rewrite" value="Your Custom Value Here." />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
I'd like to clarify a few things:
pandas.Series.tolist()
. I'm not sure why the top voted answer
leads off with using pandas.Series.values.tolist()
since as far as I can tell, it adds syntax/confusion with no added benefit.tst[lookupValue][['SomeCol']]
is a dataframe (as stated in the
question), not a series (as stated in a comment to the question). This is because tst[lookupValue]
is a dataframe, and slicing it with [['SomeCol']]
asks for
a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you
remove the extra set of brackets, as in
tst[lookupValue]['SomeCol']
, then you are asking for just that one
column rather than a list of columns, and thus you get a series back.pandas.Series.tolist()
, so you should
definitely skip the second set of brackets in this case. FYI, if you
ever end up with a one-column dataframe that isn't easily avoidable
like this, you can use pandas.DataFrame.squeeze()
to convert it to
a series.tst[lookupValue]['SomeCol']
is getting a subset of a particular column via
chained slicing. It slices once to get a dataframe with only certain rows
left, and then it slices again to get a certain column. You can get
away with it here since you are just reading, not writing, but
the proper way to do it is tst.loc[lookupValue, 'SomeCol']
(which returns a series).ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()
Demo Code:
import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
'colB':[4,5,6]})
filter_value = 1
print "df"
print df
print type(df)
rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)
result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)
result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)
result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)
result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)
result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)
ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)
ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)
Result:
df
colA colB
0 1 4
1 2 5
2 1 6
<class 'pandas.core.frame.DataFrame'>
df['colA'] == filter_value
0 True
1 False
2 True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>
df[rows_to_keep]['colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df[rows_to_keep][['colB']]
colB
0 4
2 6
<class 'pandas.core.frame.DataFrame'>
df[rows_to_keep][['colB']].squeeze()
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[df['colA'] == filter_value, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>
df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>
The working code
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
if(jsonData.hasOwnProperty(obj)){_x000D_
for(var prop in jsonData[obj]){_x000D_
if(jsonData[obj].hasOwnProperty(prop)){_x000D_
alert(prop + ':' + jsonData[obj][prop]);_x000D_
}_x000D_
}_x000D_
}_x000D_
}
_x000D_
You say it works once you install the VB6 IDE so the problem is likely to be that the components you are trying to use depend on the VB6 runtime being installed.
The VB6 runtime isn't installed on Windows by default.
Installing the IDE is one way to get the runtime. For non-developer machines, a "redistributable" installer package from Microsoft should be used instead.
Here is one VB6 runtime installer from Microsoft. I'm not sure if it will be the right version for your components:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7b9ba261-7a9c-43e7-9117-f673077ffb3c
There are several ways to create a dataframe from multiple lists.
list1=[1,2,3,4]
list2=[5,6,7,8]
list3=[9,10,11,12]
pd.DataFrame({'list1':list1, 'list2':list2, 'list3'=list3})
pd.DataFrame(data=zip(list1,list2,list3),columns=['list1','list2','list3'])
Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.
The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.
CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx
Try the steps described here: http://avaminzhang.wordpress.com/2011/11/24/python-version-2-7-required-which-was-not-found-in-the-registry/
You have multiple Google Chrome browser tabs open for the same URL and developer toolbar.
In some other tab, you have set breakpoints which are showing up when you are debugging in the current tab.
Solution: Close the developer toolbar in the other tab or the tab itself.
If emails is the pandas dataframe and emails.message the column for email text
## Helper functions
def get_text_from_email(msg):
'''To get the content from email objects'''
parts = []
for part in msg.walk():
if part.get_content_type() == 'text/plain':
parts.append( part.get_payload() )
return ''.join(parts)
def split_email_addresses(line):
'''To separate multiple email addresses'''
if line:
addrs = line.split(',')
addrs = frozenset(map(lambda x: x.strip(), addrs))
else:
addrs = None
return addrs
import email
# Parse the emails into a list email objects
messages = list(map(email.message_from_string, emails['message']))
emails.drop('message', axis=1, inplace=True)
# Get fields from parsed email objects
keys = messages[0].keys()
for key in keys:
emails[key] = [doc[key] for doc in messages]
# Parse content from emails
emails['content'] = list(map(get_text_from_email, messages))
# Split multiple email addresses
emails['From'] = emails['From'].map(split_email_addresses)
emails['To'] = emails['To'].map(split_email_addresses)
# Extract the root of 'file' as 'user'
emails['user'] = emails['file'].map(lambda x:x.split('/')[0])
del messages
emails.head()
composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist
And then you probably need to install all of vendor packages, so
composer install
Your code won't work because you haven't assigned anything to n
before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break
:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input
in Python 2.x reads a line of input and then evaluates it. You want to use raw_input
.
Note: In Python 3.x, raw_input
has been renamed to input
and the old input
method no longer exists.
There is no full proof way.
But here is some strategy that can be employed to hide source code using "window.history.pushState()" and adding oncontextmenu="return false"
in body tag as attribute
like <body oncontextmenu="return false">
to disable right click too along with modifying view-source content using "history.pushState()".
Detail here - http://freelancer.usercv.com/blog/28/hide-website-source-code-in-view-source-using-stupid-one-line-chinese-hack-code
With Javascript you can get full size profile images like this
pass your accessToken
to the getface()
function from your FB.init
call
function getface(accessToken){
FB.api('/me/friends', function (response) {
for (id in response.data) {
var homie=response.data[id].id
FB.api(homie+'/albums?access_token='+accessToken, function (aresponse) {
for (album in aresponse.data) {
if (aresponse.data[album].name == "Profile Pictures") {
FB.api(aresponse.data[album].id + "/photos", function(aresponse) {
console.log(aresponse.data[0].images[0].source);
});
}
}
});
}
});
}
Usually Vu (or VU for uppercase) is enough to turn the whole line into lowercase as V already selects the whole line to apply the action against.
Tilda (~) changes the case of the individual letter, resulting in camel case or the similar.
It is really great how Vim has many many different modes to deal with various occasions and how those modes are neatly organized.
For instance, v - the true visual mode, and the related V - visual line, and Ctrl+Q - visual block modes (what allows you to select blocks, a great feature some other advanced editors also offer usually by holding the Alt key and selecting the text).
You can restart the database on RDS Admin.
too many ) parenthesis remove one of them.
Sure you can:
Option Explicit
'***** User defined type
Public Type MyType
MyInt As Integer
MyString As String
MyDoubleArr(2) As Double
End Type
'***** Testing MyType as single variable
Public Sub MyFirstSub()
Dim MyVar As MyType
MyVar.MyInt = 2
MyVar.MyString = "cool"
MyVar.MyDoubleArr(0) = 1
MyVar.MyDoubleArr(1) = 2
MyVar.MyDoubleArr(2) = 3
Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub
'***** Testing MyType as an array
Public Sub MySecondSub()
Dim MyArr(2) As MyType
Dim i As Integer
MyArr(0).MyInt = 31
MyArr(0).MyString = "VBA"
MyArr(0).MyDoubleArr(0) = 1
MyArr(0).MyDoubleArr(1) = 2
MyArr(0).MyDoubleArr(2) = 3
MyArr(1).MyInt = 32
MyArr(1).MyString = "is"
MyArr(1).MyDoubleArr(0) = 11
MyArr(1).MyDoubleArr(1) = 22
MyArr(1).MyDoubleArr(2) = 33
MyArr(2).MyInt = 33
MyArr(2).MyString = "cool"
MyArr(2).MyDoubleArr(0) = 111
MyArr(2).MyDoubleArr(1) = 222
MyArr(2).MyDoubleArr(2) = 333
For i = LBound(MyArr) To UBound(MyArr)
Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
Next
End Sub
You should really use a set based solution involving two queries (basic insert):
INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT id, column1, column2 FROM TableA
UPDATE TableA SET column1 = column2 * column3
And for your transform:
INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT
id,
column1 * column4 * 100,
(column2 / column12)
FROM TableA
UPDATE TableA SET column1 = column2 * column3
Now if your transform is more complicated than that and involved multiple tables, post another question with the details.
For what it is worth I came to this page because I had the same problem. I never got anywhere except some IMAP stuff that I don't understand. Then I remembered I had uninstalled privoxy on my ubuntu (because of some weird runtime error that mentioned 127.0.0.1:8118 when I used Daniel Kehoe's Rails template, https://github.com/RailsApps/rails3-application-templates [never discovered what it was]) and I hadn't changed my terminal to the state of no system wide proxy, under network proxy.
I know this may not be on-point but if I wound up here maybe other privoxy users can benefit too.
you can do it only in one line as below:
$cnt = mysql_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;
Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.
I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')
I'm basing this on somewhat reading between the lines of: Selecting a Credential Type
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?
The click event is not bound to your new element, use a jQuery.on
to handle the click.
I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.
When using your script from the console or as an application, the functions hereunder will deliver you the "execution path", not the "actual file path":
print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))
Source:
http://cx-freeze.readthedocs.org/en/latest/faq.html
Your old line (initial question):
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
Substitute your line of code with the following snippet.
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
With the above code you could add your application to the path of your os, you could execute it anywhere without the problem that your app is unable to find it's data/configuration files.
Tested with python:
If you have view Collection (Multiple View) do this
func setGradientBackground() {
let v:UIView
for v in viewgradian
//here viewgradian is your view Collection Outlet name
{
let layer:CALayer
var arr = [AnyObject]()
for layer in v.layer.sublayers!
{
arr.append(layer)
}
let colorTop = UIColor(red: 216.0/255.0, green: 240.0/255.0, blue: 244.0/255.0, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [ colorBottom, colorTop]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.frame = v.bounds
v.layer.insertSublayer(gradientLayer, at: 0)
}
}
Faced similar issue, and here is the solution
Example :
In elasticsearch.yml add the below properties
cluster.name: production
node.name: node1
network.bind_host: 10.0.1.22
network.host: 0.0.0.0
transport.tcp.port: 9300
Add the following in Java Elastic API for Bulk Push (just a code snippet). For IP Address add public IP address of elastic search machine
Client client;
BulkRequestBuilder requestBuilder;
try {
client = TransportClient.builder().settings(Settings.builder().put("cluster.name", "production").put("node.name","node1")).build().addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName(""), 9300));
requestBuilder = (client).prepareBulk();
}
catch (Exception e) {
}
Open the Firewall ports for 9200,9300
I've been using some simple CSS and it seems to remove them and work fine.
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
This tutorial from CSS Tricks explains in detail & also shows how to style them
Try using WGET
:
WGET 'http://localhost/index.php?a=1&b=2&c=3'
Open Command Prompt inside your Application's source. Run the Command
npm run eject
Open your scripts/build.js file and add this at the beginning of the file after 'use strict' line
'use strict';
....
process.env.PUBLIC_URL = './'
// Provide the current path
.....
Open your config/paths.js and modify the buildApp property in the exports object to your destination folder. (Here, I provide 'react-app-scss' as the destination folder)
module.exports = {
.....
appBuild: resolveApp('build/react-app-scss'),
.....
}
Run
npm run build
Note: Running Platform dependent scripts are not advisable
If DF
is your data frame of numeric columns:
library(zoo)
na.aggregate(DF)
ADDED:
Using only the base of R define a function which does it for one column and then lapply to every column:
NA2mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
replace(DF, TRUE, lapply(DF, NA2mean))
The last line could be replaced with the following if it's OK to overwrite the input:
DF[] <- lapply(DF, NA2mean)
I think that the best solution for drawing text in OpenGL is texture fonts, I work with them for a long time. They are flexible, fast and nice looking (with some rear exceptions). I use special program for converting font files (.ttf for example) to texture, which is saved to file of some internal "font" format (I've developed format and program based on http://content.gpwiki.org/index.php/OpenGL:Tutorials:Font_System though my version went rather far from the original supporting Unicode and so on). When starting the main app, fonts are loaded from this "internal" format. Look link above for more information.
With such approach the main app doesn't use any special libraries like FreeType, which is undesirable for me also. Text is being drawn using standard OpenGL functions.
You can always use multiple
or multiple = "true"
option with a select tag, but there is one jquery plugin which makes it more beautiful. It is called chosen and can be found here.
This fiddle-example might help you to get started
Thank you.
The easiest way is to CAST the value as FLOAT and then to a string data type.
CAST(CAST(123.456000 AS FLOAT) AS VARCHAR(100))
It works for me:
if (isset($_POST['MyTextAreaName'])){
$array=explode( "\r\n", $_POST['MyTextAreaName'] );
now, my $array will have all the lines I need
for ($i = 0; $i <= count($array); $i++)
{
echo (trim($array[$i]) . "<br/>");
}
(make sure to close the if
block with another curly brace)
}
Perhaps bool is a tad "lighter" than Boolean; Interestingly, changing this:
namespace DuckbillServerWebAPI.Models
{
public class Expense
{
. . .
public bool CanUseOnItems { get; set; }
}
}
...to this:
namespace DuckbillServerWebAPI.Models
{
public class Expense
{
. . .
public Boolean CanUseOnItems { get; set; }
}
}
...caused my cs file to sprout a "using System;" Changing the type back to "bool" caused the using clause's hair to turn grey.
(Visual Studio 2010, WebAPI project)
These two settings worked for me to upload 1GB mp4 videos.
<system.web>
<httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
SELECT count(*) -- or count(myCol)
FROM <table name> -- replace <table name> with your table
WHERE myCol = true;
Here's a way with Windowing Function:
SELECT DISTINCT *, count(*) over(partition by myCol)
FROM <table name>;
-- Outputs:
-- --------------
-- myCol | count
-- ------+-------
-- f | 2
-- t | 3
-- | 1
You can create files in browser using Blob
and URL.createObjectURL
. All recent browsers support this.
You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download
attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea
.
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
I should mention here that we now have a means of triggering a new build on the web. See https://blog.travis-ci.com/2017-08-24-trigger-custom-build for details.
TL;DR Click on "More options", and choose "Trigger build".
This should do the work on any Javascript environment (NodeJS included).
const text = `
<html lang="en">
<head>
<style type="text/css">*{color:red}</style>
<script>alert('hello')</script>
</head>
<body><b>This is some text</b><br/><body>
</html>`;
// Remove style tags and content
text.replace(/<style[^>]*>.*<\/style>/gm, '')
// Remove script tags and content
.replace(/<script[^>]*>.*<\/script>/gm, '')
// Remove all opening, closing and orphan HTML tags
.replace(/<[^>]+>/gm, '')
// Remove leading spaces and repeated CR/LF
.replace(/([\r\n]+ +)+/gm, '');
Simply restarting Visual Studio worked for me.
In my case, I was careless while merging the application.yml file, and I've unnecessary indented my properties to the right.
I've indented it like this:
spring:
application:
name: applicationName
............................
myProperties:
property1: property1value
While the code expected it to be like this:
spring:
application:
name: applicationName
.............................
myProperties:
property1: property1value
Solved, this is how your parse their html results:
table = soup.find("table", { "class" : "lineItemsTable" })
for row in table.findAll("tr"):
cells = row.findAll("td")
if len(cells) == 9:
summons = cells[1].find(text=True)
plateType = cells[2].find(text=True)
vDate = cells[3].find(text=True)
location = cells[4].find(text=True)
borough = cells[5].find(text=True)
vCode = cells[6].find(text=True)
amount = cells[7].find(text=True)
print amount
I had a similar problem.
I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.
Let's say for example this one.
$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');
// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));
// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut
// down the process one by one like this.
$data1 = array_keys($data);
$lastkey = array_pop($data1);
echo $lastkey;
There you go!
You could have simply used Range("x1").value(11)
something like below:
Sheets("Output").Range("$A$1:$A$500").value(11) = Sheets(sheet_).Range("$A$1:$A$500").value(11)
range has default property "Value" plus value can have 3 optional orguments 10,11,12. 11 is what you need to tansfer both value and formats. It doesn't use clipboard so it is faster.- Durgesh
Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:
select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc
you just have to change the name of your input filed because same name is required in parameter and input field name just replace this line Your code working fine
<input type="file" name="file" />
I have used
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
Use jQuery. You need to capture the click
event and then go on to the website.
$("#myHref").on('click', function() {_x000D_
alert("inside onclick");_x000D_
window.location = "http://www.google.com";_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="myHref">Click me</a>
_x000D_
Using the Excel Text import wizard to import it if it is a text file, like a CSV file, is another option and can be done based on which row number to which row numbers you specify. See: This link
So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.
Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.
The reason for this apparent performance discrepancy between categorical & binary cross entropy is what user xtof54 has already reported in his answer below, i.e.:
the accuracy computed with the Keras method
evaluate
is just plain wrong when using binary_crossentropy with more than 2 labels
I would like to elaborate more on this, demonstrate the actual underlying issue, explain it, and offer a remedy.
This behavior is not a bug; the underlying reason is a rather subtle & undocumented issue at how Keras actually guesses which accuracy to use, depending on the loss function you have selected, when you include simply metrics=['accuracy']
in your model compilation. In other words, while your first compilation option
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
is valid, your second one:
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
will not produce what you expect, but the reason is not the use of binary cross entropy (which, at least in principle, is an absolutely valid loss function).
Why is that? If you check the metrics source code, Keras does not define a single accuracy metric, but several different ones, among them binary_accuracy
and categorical_accuracy
. What happens under the hood is that, since you have selected binary cross entropy as your loss function and have not specified a particular accuracy metric, Keras (wrongly...) infers that you are interested in the binary_accuracy
, and this is what it returns - while in fact you are interested in the categorical_accuracy
.
Let's verify that this is the case, using the MNIST CNN example in Keras, with the following modification:
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # WRONG way
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=2, # only 2 epochs, for demonstration purposes
verbose=1,
validation_data=(x_test, y_test))
# Keras reported accuracy:
score = model.evaluate(x_test, y_test, verbose=0)
score[1]
# 0.9975801164627075
# Actual accuracy calculated manually:
import numpy as np
y_pred = model.predict(x_test)
acc = sum([np.argmax(y_test[i])==np.argmax(y_pred[i]) for i in range(10000)])/10000
acc
# 0.98780000000000001
score[1]==acc
# False
To remedy this, i.e. to use indeed binary cross entropy as your loss function (as I said, nothing wrong with this, at least in principle) while still getting the categorical accuracy required by the problem at hand, you should ask explicitly for categorical_accuracy
in the model compilation as follows:
from keras.metrics import categorical_accuracy
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[categorical_accuracy])
In the MNIST example, after training, scoring, and predicting the test set as I show above, the two metrics now are the same, as they should be:
# Keras reported accuracy:
score = model.evaluate(x_test, y_test, verbose=0)
score[1]
# 0.98580000000000001
# Actual accuracy calculated manually:
y_pred = model.predict(x_test)
acc = sum([np.argmax(y_test[i])==np.argmax(y_pred[i]) for i in range(10000)])/10000
acc
# 0.98580000000000001
score[1]==acc
# True
System setup:
Python version 3.5.3
Tensorflow version 1.2.1
Keras version 2.0.4
UPDATE: After my post, I discovered that this issue had already been identified in this answer.
Not an answer per se, but a guideline. Most of the time there is not much sense in declaring local T&&
variable (as you did with std::vector<int>&& rval_ref
). You will still have to std::move()
them to use in foo(T&&)
type methods. There is also the problem that was already mentioned that when you try to return such rval_ref
from function you will get the standard reference-to-destroyed-temporary-fiasco.
Most of the time I would go with following pattern:
// Declarations
A a(B&&, C&&);
B b();
C c();
auto ret = a(b(), c());
You don't hold any refs to returned temporary objects, thus you avoid (inexperienced) programmer's error who wish to use a moved object.
auto bRet = b();
auto cRet = c();
auto aRet = a(std::move(b), std::move(c));
// Either these just fail (assert/exception), or you won't get
// your expected results due to their clean state.
bRet.foo();
cRet.bar();
Obviously there are (although rather rare) cases where a function truly returns a T&&
which is a reference to a non-temporary object that you can move into your object.
Regarding RVO: these mechanisms generally work and compiler can nicely avoid copying, but in cases where the return path is not obvious (exceptions, if
conditionals determining the named object you will return, and probably couple others) rrefs are your saviors (even if potentially more expensive).
You can get the example of css implemented html to pdf conversion using jspdf on following link: JSFiddle Link
This is sample code for the jspdf html to pdf download.
$('#print-btn').click(() => {
var pdf = new jsPDF('p','pt','a4');
pdf.addHTML(document.body,function() {
pdf.save('web.pdf');
});
})
Template driven method
#receiverInput="ngModel" (blur)="receiverInput.control.setValue('')"
In Python2, input
is evaluated, input()
is equivalent to eval(raw_input())
. When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.
Use raw_input
to get a string from the user in Python2.
Demo 1: klj
is not defined:
>>> input()
klj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
Demo 2: klj
is defined:
>>> klj = 'hi'
>>> input()
klj
'hi'
Demo 3: getting a string with raw_input
:
>>> raw_input()
klj
'klj'
Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
atof and strtod do what you want but are very forgiving. If you don't want to accept strings like "32asd" as valid you need to wrap strtod in a function such as this:
#include <stdlib.h>
double strict_str2double(char* str)
{
char* endptr;
double value = strtod(str, &endptr);
if (*endptr) return 0;
return value;
}
the default encoding of a HTTP POST is ISO-8859-1.
else you have to look at the Content-Type header that will then look like
Content-Type: application/x-www-form-urlencoded ; charset=UTF-8
You can maybe declare your form with
<form enctype="application/x-www-form-urlencoded;charset=UTF-8">
or
<form accept-charset="UTF-8">
to force the encoding.
Some references :
Refresh the page containing the script whilst the developer tools are open on the scripts tab. This will add a (program) entry in the file list which shows the html of the page including the script. From here you can add breakpoints.
You can also concat df1
, df2
:
x = pd.concat([df1, df2])
and then remove all duplicates:
y = x.drop_duplicates(keep=False, inplace=False)
I had similar issue, my problem was with the side padding, and the solution was with, text-indent, I wasn't realize that text indent effect the placeholder side position.
input{
text-indent: 10px;
}
VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.
Dim val1 As Integer, val2 As Integer, i As Integer
For i = 1 To 333
Sheets("Feuil2").Activate
ActiveSheet.Cells(i, 1).Select
val1 = Cells(i, 1).Value
val2 = Cells(i, 2).Value
Sheets("Classeur2.csv").Select
Cells(val1, val2).Select
ActiveCell.FormulaR1C1 = "1"
Next i
The trim() method removes whitespace from both sides of a string.
You can use a Javascript replace method to remove white space like
"hello world".replace(/\s/g, "");
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
I've met same problem and fixed it changing connection string like below. Write
'DRIVER={ODBC Driver 13 for SQL Server}'
instead of
'DRIVER={SQL Server}'
No there's not and developers still don't know why google doesn't pay attention to this request!
As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!
You can use wireshark or tcpdump to look on any network traffic (http too).
Not the answer to the original question but when trying to resolve a similar issue, I found that the Mac OS X update to Maverics screwed up the java install (the cacert actually). Remove sudo rm -rf /Library/Java/JavaVirtualMachines/*.jdk
and reinstall from http://www.oracle.com/technetwork/java/javase/downloads/index.html
To find the AWS_SECRET_ACCESS_KEY Its better to create new create "IAM" user Here is the steps https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html 1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.
A simple example that will clear both during executing script or inside script while calling a function.
#!/bin/bash
echo "parameterized function example"
function print_param_value(){
value1="${1}" # $1 represent first argument
value2="${2}" # $2 represent second argument
echo "param 1 is ${value1}" # As string
echo "param 2 is ${value2}"
sum=$(($value1+$value2)) # Process them as number
echo "The sum of two value is ${sum}"
}
print_param_value "6" "4" # Space-separated value
# You can also pass parameters during executing the script
print_param_value "$1" "$2" # Parameter $1 and $2 during execution
# Suppose our script name is "param_example".
# Call it like this:
#
# ./param_example 5 5
#
# Now the parameters will be $1=5 and $2=5
We should always go for equals() method for comparison for two integers.Its the recommended practice.
If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.
Please see examples:
Case 1:
Integer a = 100; Integer b = 100;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.
Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.
Integer a = 220; Integer b = 220;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
Proper way:
Integer a = 200;
Integer b = 200;
System.out.println("a == b? " + a.equals(b)); // true
I hope this helps.
import java.io.IOException
import java.net.URL
fun main(vararg args: String) {
val response = try {
URL("http://seznam.cz")
.openStream()
.bufferedReader()
.use { it.readText() }
} catch (e: IOException) {
"Error with ${e.message}."
}
println(response)
}
The following your code:
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
is superfluous.
Why not to write:
public static boolean logicalXOR(boolean x, boolean y) {
return x != y;
}
?
Also, as javashlook said, there already is ^
operator.
!=
and ^
work identically* for boolean operands (your case), but differently for integer operands.
* Notes:
1. They work identically for boolean
(primitive type), but not Boolean
(object type) operands. As Boolean
(object type) values can have value null
. And !=
will return false
or true
when one or both of its operands are null
, while ^
will throw NullPointerException
in this case.
2. Although they work identically, they have different precedence, e.g. when used with &
: a & b != c & d
will be treated as a & (b != c) & d
, while a & b ^ c & d
will be treated as (a & b) ^ (c & d)
(offtopic: ouch, C-style precedence table sucks).
This works in my case for getting table name and column name in the corresponding table for indexed fields.
SELECT TABLE_NAME , COLUMN_NAME, COMMENT
FROM information_schema.statistics
WHERE table_schema = 'database_name';
The exception is threw here (In FragmentActivity):
@Override
public void onBackPressed() {
if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) {
super.onBackPressed();
}
}
In FragmentManager.popBackStatckImmediate()
,FragmentManager.checkStateLoss()
is called firstly. That's the cause of IllegalStateException
. See the implementation below:
private void checkStateLoss() {
if (mStateSaved) { // Boom!
throw new IllegalStateException(
"Can not perform this action after onSaveInstanceState");
}
if (mNoTransactionsBecause != null) {
throw new IllegalStateException(
"Can not perform this action inside of " + mNoTransactionsBecause);
}
}
I solve this problem simply by using a flag to mark Activity's current status. Here's my solution:
public class MainActivity extends AppCompatActivity {
/**
* A flag that marks whether current Activity has saved its instance state
*/
private boolean mHasSaveInstanceState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
mHasSaveInstanceState = true;
super.onSaveInstanceState(outState);
}
@Override
protected void onResume() {
super.onResume();
mHasSaveInstanceState = false;
}
@Override
public void onBackPressed() {
if (!mHasSaveInstanceState) {
// avoid FragmentManager.checkStateLoss()'s throwing IllegalStateException
super.onBackPressed();
}
}
}
I ran into a similar problem while creating a library to handle authentication. I want the app owner using my library to be able to register a callback with the library for checking authorization against LDAP groups the authenticated person is in. The configuration is getting passed in as a config.py file that gets imported and contains a dict with all the config parameters.
I got this to work:
>>> class MyClass(object):
... def target_func(self):
... print "made it!"
...
... def __init__(self,config):
... self.config = config
... self.config['funcname'] = getattr(self,self.config['funcname'])
... self.config['funcname']()
...
>>> instance = MyClass({'funcname':'target_func'})
made it!
Is there a pythonic-er way to do this?
You can also use another built-in template default_if_none
{{ profile.user.first_name|default_if_none:"--" }}
SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
Here what I DO on MY PC I install all software that i usually used in G: partian not C: if my operating system is fall (win 10) , Do not need to reinstall them again and lost time , Then How windows work it update PATH automatic if you install any new programe or pice of softwore ,
SO
I must update PATH like these HERE! all my software i usually used 1- I created folder called Programe Files 2- I install all my programe data in these folder 3-and then going to PATH and add it Dont forget ;
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;G:\HashiCorp\Vagrant\bin;G:\xampp\php;G:\xampp\mysql\bin;G:\Program Files (x86)\heroku\bin;G:\Program Files (x86)\Git\bin;G:\Program Files (x86)\composer;G:\Program Files (x86)\nodejs;G:\Program Files (x86)\Sublime Text 3;G:\Program Files (x86)\Microsoft VS Code\bin;G:\Program Files (x86)\cygwin64\bin
You can use ASP.NET to generate your HTML outside the context of web pages. Here's an article that shows how it can be done.
Since python 3.7 dict always ordered(insert order),
since python 3.8 keys(), values() and items() of dict returns: view that can be reversed:
to get last key:
next(reversed(my_dict.keys()))
the same apply for values() and items()
PS, to get first key use: next(iter(my_dict.keys()))
You can use the IsDbNull function:
If IsDbNull(myItem("sID")) = False AndAlso myItem("sID")==sID Then
// Do something
End If
I'm not very happy with any of the options so I ended up requesting the file in Excel 97 formate. The POI works great for that. Thanks everyone for the help.
I recently struggled with this issue for 3 days. How the client is sending the request might not be the cause, the server might not be configured to handle multipart requests. This is what I had to do to get it working:
pom.xml - Added commons-fileupload dependency (download and add the jar to your project if you are not using dependency management such as maven)
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-version}</version>
</dependency>
web.xml - Add multipart filter and mapping
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/springrest/*</url-pattern>
</filter-mapping>
app-context.xml - Add multipart resolver
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize">
<beans:value>10000000</beans:value>
</beans:property>
</beans:bean>
Your Controller
@RequestMapping(value=Constants.REQUEST_MAPPING_ADD_IMAGE, method = RequestMethod.POST, produces = { "application/json"})
public @ResponseBody boolean saveStationImage(
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_FILE) MultipartFile file,
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_URI) String imageUri,
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_TYPE) String imageType,
@RequestParam(value = Constants.MONGO_FIELD_STATION_ID) String stationId) {
// Do something with file
// Return results
}
Your client
public static Boolean updateStationImage(StationImage stationImage) {
if(stationImage == null) {
Log.w(TAG + ":updateStationImage", "Station Image object is null, returning.");
return null;
}
Log.d(TAG, "Uploading: " + stationImage.getImageUri());
try {
RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName("UTF8"));
restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add(Constants.STATION_PROFILE_IMAGE_FILE, new FileSystemResource(stationImage.getImageFile()));
parts.add(Constants.STATION_PROFILE_IMAGE_URI, stationImage.getImageUri());
parts.add(Constants.STATION_PROFILE_IMAGE_TYPE, stationImage.getImageType());
parts.add(Constants.FIELD_STATION_ID, stationImage.getStationId());
return restTemplate.postForObject(Constants.REST_CLIENT_URL_ADD_IMAGE, parts, Boolean.class);
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
Log.e(TAG + ":addStationImage", sw.toString());
}
return false;
}
That should do the trick. I added as much information as possible because I spent days, piecing together bits and pieces of the full issue, I hope this will help.
Cutting to the bottom line, you want a query like SELECT x FROM y to be passed into a function that returns the values as a comma separated string.
As has already been explained you can do this by creating a table type and passing a UDT into the function, but this needs a multi-line statement.
You can pass XML around without declaring a typed table, but this seems to need a xml variable which is still a multi-line statement i.e.
DECLARE @MyXML XML = (SELECT x FROM y FOR XML RAW);
SELECT Dbo.CreateCSV(@MyXml);
The "FOR XML RAW" makes the SQL give you it's result set as some xml.
But you can bypass the variable using Cast(... AS XML). Then it's just a matter of some XQuery and a little concatenation trick:
CREATE FUNCTION CreateCSV (@MyXML XML)
RETURNS VARCHAR(MAX)
BEGIN
DECLARE @listStr VARCHAR(MAX);
SELECT
@listStr =
COALESCE(@listStr+',' ,'') +
c.value('@Value[1]','nvarchar(max)')
FROM @myxml.nodes('/row') as T(c)
RETURN @listStr
END
GO
-- And you call it like this:
SELECT Dbo.CreateCSV(CAST(( SELECT x FROM y FOR XML RAW) AS XML));
-- Or a working example
SELECT Dbo.CreateCSV(CAST((
SELECT DISTINCT number AS Value
FROM master..spt_values
WHERE type = 'P'
AND number <= 20
FOR XML RAW) AS XML));
As long as you use FOR XML RAW all you need do is alias the column you want as Value, as this is hard coded in the function.
I'm using jquery with yql for feed. You can retrieve twitter,rss,buzz with yql. I read from http://tutorialzine.com/2010/02/feed-widget-jquery-css-yql/ . It's very useful for me.
Amortized Big-O for hashtables:
Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
If you wish to force a "," separator regardless of culture (for example in a trace or log message), the following code will work and has the added benefit of telling the next guy who stumbles across it exactly what you are doing.
int integerValue = 19400320;
string formatted = string.Format(CultureInfo.InvariantCulture, "{0:N0}", integerValue);
sets formatted to "19,400,320"
Much simpler:
position: relative;
left: 50%;
transform: translateX(-50%);
You are now centered in your parent element. You can do that vertically too.
I was struggling with the docker push, both using the Fabric8 Maven plugin (on Windows 10), and directly calling docker push
from the command line.
Finally I solved both issues the same way.
My repo is called vgrazi/playpen. In my pom, I changed the docker image name to vgrazi/playpen, as below:
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.31.0</version>
<configuration>
<dockerHost>npipe:////./pipe/docker_engine</dockerHost>
<verbose>true</verbose>
<images>
<image>
<name>vgrazi/playpen</name>
<build>
<dockerFileDir>${project.basedir}/src/main/docker/</dockerFileDir>
...
That let me do a mvn clean package docker:build docker:push
from the command line, and at last, the image appeared in my repo, which was the problem I was trying to solve.
As an aside, to answer the OP and get this to work directly from the command line, without Maven, I did the following (PS is the PowerShell prompt, don't type that):
PS docker images
vgrazi/docker-test/docker-play playpen 0722e876ebd7 40 minutes ago 536MB
rabbitmq 3-management 68055d63a993 10 days ago 180MB
PS docker tag 0722e876ebd7 vgrazi:playpen
PS docker push vgrazi/playpen
and again, the image appeared in my docker.io: repo vgrazi/playpen
tony's approach does work for me but when do a console.log, the function getTableHeight get called too many time(sort, menu click...)
I modify it so the height is recalculated only when i add/remove rows. Note: tableData is the array of rows
$scope.getTableHeight = function() {
var rowHeight = 30; // your row height
var headerHeight = 30; // your header height
return {
height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"
};
};
$scope.$watchCollection('tableData', function (newValue, oldValue) {
angular.element(element[0].querySelector('.grid')).css($scope.getTableHeight());
});
Html
<div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize"></div>
Consider a=10
, b=15
:
Using Addition and Subtraction
a = a + b //a=25
b = a - b //b=10
a = a - b //a=15
Using Division and multiplication
a = a * b //a=150
b = a / b //b=10
a = a / b //a=15
Try lodash sortBy
import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
console.log("application")
)
)
Read more : lodash.sortBy
Use the .IndexOf()
method of the list. Specs for the method can be found on MSDN.
You are looking for -H
option in gnu grep.
find . -name '*bills*' -exec grep -H "put" {} \;
-H, --with-filename
Print the filename for each match.
It's been some time since I used node.js, but I think I might be able to help.
Firstly, in node, you only have a single thread and are supposed to use callbacks. What will happen with your code, is that base.getID
query will get queued up by for execution, but the while
loop will continusouly run as a busy loop pointlessly.
You should be able to solve your issue with a callback as follows:
function generate(count, k) {
var _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
var str = '';
for(var i = 0; i < count; i++) {
str += _sym[parseInt(Math.random() * (_sym.length))];
}
base.getID(str, function(err, res) {
if(!res.length) {
k(str) // use the continuation
} else generate(count, k) // otherwise, recurse on generate
});
}
And use it as such
generate(10, function(uniqueId){
// have a uniqueId
})
I haven't coded any node/js in around 2 years and haven't tested this, but the basic idea should hold – don't use a busy loop, and use callbacks. You might want to have a look at the node async package.
A small update to this one:
if you use the following it will update on the fly rather than on mouse release.
"change mousemove", function"
<script>
$('input[type="range"]').on("change mousemove", function () {
var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));
$(this).css('background-image',
'-webkit-gradient(linear, left top, right top, '
+ 'color-stop(' + val + ', #2f466b), '
+ 'color-stop(' + val + ', #d3d3db)'
+ ')'
);
});</script>
It doesn't work because name
is a reserved word in JavaScript. Change the function name to something else.
See http://www.quackit.com/javascript/javascript_reserved_words.cfm
<form id="form" onsubmit="return false;">
<input style="position:absolute; top:80%; left:5%; width:40%;" type="text" id="userInput" />
<input style="position:absolute; top:50%; left:5%; width:40%;" type="submit" onclick="othername();" />
</form>
function othername() {
var input = document.getElementById("userInput").value;
alert(input);
}
If you happen to have cxf-core on the classpath and you know you have no repeated query params, you may want to use UrlUtils.parseQueryString.
The easiest solution I found for this:
git commit -m "fixing merge conflicts"
git push
You are supposed to be able to specify a domain that is safe for scripting. the api document mentions "As an extra security measure, you should also include the origin parameter to the URL" http://code.google.com/apis/youtube/iframe_api_reference.html src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com" would be the src of your iframe.
however it is not very well documented. I am trying something similar right now.
Your Delivery
class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery
class. You need to either make Delivery
public, or restrict the visibility of the thelivery
property.
The number of binary trees can be calculated using the catalan number.
The number of binary search trees can be seen as a recursive solution. i.e., Number of binary search trees = (Number of Left binary search sub-trees) * (Number of Right binary search sub-trees) * (Ways to choose the root)
In a BST, only the relative ordering between the elements matter. So, without any loss on generality, we can assume the distinct elements in the tree are 1, 2, 3, 4, ...., n. Also, let the number of BST be represented by f(n) for n elements.
Now we have the multiple cases for choosing the root.
...... Similarly, for i-th element as the root, i-1 elements can be on the left and n-i on the right.
These sub-trees are itself BST, thus, we can summarize the formula as:
f(n) = f(0)f(n-1) + f(1)f(n-2) + .......... + f(n-1)f(0)
Base cases, f(0) = 1, as there is exactly 1 way to make a BST with 0 nodes. f(1) = 1, as there is exactly 1 way to make a BST with 1 node.
$(function() {
$('.phrase .items').each(function(i, items_list){
var myText = "";
$(items_list).find('li').each(function(j, li){
alert(li.text());
})
alert(myText);
});
};
There is no native version of Visual Studio for Mac OS X.
Almost all versions of Visual Studio have a Garbage rating on Wine's application database, so Wine isn't an option either, sadly.
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
From a purely "make it fit in the div" perspective, add the following to your table class (jsfiddle):
table-layout: fixed;
width: 100%;
Set your column widths as desired; otherwise, the fixed layout algorithm will distribute the table width evenly across your columns.
For quick reference, here are the table layout algorithms, emphasis mine:
With this (fast) algorithm, the horizontal layout of the table does not depend on the contents of the cells; it only depends on the table's width, the width of the columns, and borders or cell spacing.
In this algorithm (which generally requires no more than two passes), the table's width is given by the width of its columns [, as determined by content] (and intervening borders).
[...] This algorithm may be inefficient since it requires the user agent to have access to all the content in the table before determining the final layout and may demand more than one pass.
Click through to the source documentation to see the specifics for each algorithm.
You have to use v-html directive for displaying html content inside a vue component
<div v-html="html content data property"></div>
# Define the types of logger and level of logging
log4j.rootLogger = DEBUG,console, FILE
# Define the File appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Define Console Appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
# Define the layout for console appender. If you do not
# define it, you will get an error
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# Set the name of the file
log4j.appender.FILE.File=log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
On Ubuntu after installing lxc-docker you need to add your user to the docker user group:
sudo usermod -a -G docker myusername
This is because of the socket file permissions:
srw-rw---- 1 root docker 0 Mar 20 07:43 /var/run/docker.sock
DO NOT RUN usermod WITHOUT "-a" as suggested in one of the other comments or it will wipe your additional groups setting and will just leave the "docker" group
This is what will happen:
? ~ id pawel
uid=1000(pawel) gid=1000(pawel) groups=1000(pawel),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),108(lpadmin),124(sambashare),998(docker)
? ~ usermod -G docker pawel
? ~ id pawel
uid=1000(pawel) gid=1000(pawel) groups=1000(pawel),998(docker)
<script>
function sum()
{
var value1= parseInt(document.getElementById("txtfirst").value);
var value2=parseInt(document.getElementById("txtsecond").value);
var sum=value1+value2;
document.getElementById("result").value=sum;
}
</script>
You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:
public class ProgramViwer : Form{
public ProgramViwer()
{
InitializeComponent();
Load += new EventHandler(ProgramViwer_Load);
}
private void ProgramViwer_Load(object sender, System.EventArgs e)
{
formPanel.Controls.Clear();
formPanel.Controls.Add(wel);
}
}
Using MySQLi
transaction I sometimes wasn't able to get mysqli::$insert_id
, because it returned 0. Especially if I was using stored procedures, that executing INSERT
s. So there is another way within transaction:
<?php
function getInsertId(mysqli &$instance, $enforceQuery = false){
if(!$enforceQuery)return $instance->insert_id;
$result = $instance->query('SELECT LAST_INSERT_ID();');
if($instance->errno)return false;
list($buffer) = $result->fetch_row();
$result->free();
unset($result);
return $buffer;
}
?>
Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
The best way to fix it I have looked for the code or trick how to center nav menu and found the real solutions it works for all browsers and for my friends ;)
Here is how I have done:
body {
margin: 0;
padding: 0;
}
div maincontainer {
margin: 0 auto;
width: ___px;
text-align: center;
}
ul {
margin: 0;
padding: 0;
}
ul li {
margin-left: auto;
margin-right: auto;
}
and do not forget to set doctype html5
As per Angular2 final, you do not even have to import FORM_DIRECTIVES
as suggested above by many. However, the syntax has been changed as kebab-case was dropped for the betterment.
Just replace ng-model
with ngModel
and wrap it in a box of bananas. But you have spilt the code into two files now:
app.ts:
import { Component } from '@angular/core';
@Component({
selector: 'ng-app',
template: `
<input id="name" type="text" [(ngModel)]="name" />
{{ name }}
`
})
export class DataBindingComponent {
name: string;
constructor() {
this.name = 'Jose';
}
}
app.module.ts:
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DataBindingComponent } from './app'; //app.ts above
@NgModule({
declarations: [DataBindingComponent],
imports: [BrowserModule, FormsModule],
bootstrap: [DataBindingComponent]
})
export default class MyAppModule {}
platformBrowserDynamic().bootstrapModule(MyAppModule);
If we are very sure that List<Object>
will contain collection of String
, then probably try this.
List<Object> lst = new ArrayList<Object>();
lst.add("sample");
lst.add("simple");
String[] arr = lst.toArray(new String[] {});
System.out.println(Arrays.deepToString(arr));
You can also achieve this by using simple JavaScript.
const stringData = '?name=Nikhil&surname=Mahirrao&age=30';_x000D_
_x000D_
const newData= {};_x000D_
stringData.replace('?', '').split('&').map((value) => {_x000D_
const temp = value.split('=');_x000D_
newData[temp[0]] = temp[1];_x000D_
});_x000D_
_x000D_
console.log('stringData: '+stringData);_x000D_
console.log('newData: ');_x000D_
console.log(newData);
_x000D_
What is DATA ACCESS OBJECT (DAO) -
It is a object/interface, which is used to access data from database of data storage.
WHY WE USE DAO:
it abstracts the retrieval of data from a data resource such as a database. The concept is to "separate a data resource's client interface from its data access mechanism."
The problem with accessing data directly is that the source of the data can change. Consider, for example, that your application is deployed in an environment that accesses an Oracle database. Then it is subsequently deployed to an environment that uses Microsoft SQL Server. If your application uses stored procedures and database-specific code (such as generating a number sequence), how do you handle that in your application? You have two options:
Its in all referred as DAO Pattern, It consist of following:
Please check this example, This will clear things more clearly.
Example
I assume this things must have cleared your understanding of DAO up to certain extend.
implementation 'com.android.support:appcompat-v7:26.1.0'
after this line You have to add new Line in your gradle
implementation 'com.android.support:design:26.1.0'
An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view
Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'
The best way to do this:
ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);
This error means some other process or user is accessing your file. Use lsof
to check what other processes are using it. You can use kill
command to kill it if needed.
you can download bjam for OSX (or any other OS) here
I was able to accomplish this in swift this way:
let navBarAppearance = UINavigationBar.appearance()
let colorImage = UIImage.imageFromColor(UIColor.morselPink(), frame: CGRectMake(0, 0, 340, 64))
navBarAppearance.setBackgroundImage(colorImage, forBarMetrics: .Default)
where i created the following utility method in a UIColor
category:
imageFromColor(color: UIColor, frame: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
color.setFill()
UIRectFill(frame)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
Be careful with "/" and "\". Even on Windows the command should be in the form:
\i c:/1.sql
Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> **$dte = Get-Date**
PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
PS C:\Windows\system32> **$PastDueDate**
Sunday, March 1, 2020 12:00:00 AM
PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
PS C:\Windows\system32> **$NewDateFormat 03012020**
There're few additional methods available as well e.g.: $dte.AddDays(-45).Day
This is the method I used to disable.Hope it helps.
$("#ThisLink").attr("href","javascript:;");
You haven't posted the findvertex
method, but Access Reading Violation with an offset like 0x00000048
means that the Vertex* f;
in your getCost function is receiving null, and when trying to access the member adj
in the null
Vertex pointer (that is, in f
), it is offsetting to adj
(in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0
or null
memory address.
Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex
isn't returning null, or do a comparisong for null on f
before using it to keep yourself sane (or use an assert):
assert( f != null ); // A good sanity check
EDIT:
If you have a map
for doing something like a find, you can just use the map's find
method to make sure the vertex exists:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.find( s );
if ( itr == map1.end() )
{
return NULL;
}
return itr->second;
}
Just make sure you're still careful to handle the error case where it does return NULL
. Otherwise, you'll keep getting this access violation.
If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!
The code is,
set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;
And then call the function as it is:
DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;
You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.
When clicking Button1
on the UserControl, i'll fire Button1_Click
which triggers UserControl_ButtonClick
on the form:
User control:
[Browsable(true)] [Category("Action")]
[Description("Invoked when user clicks button")]
public event EventHandler ButtonClick;
protected void Button1_Click(object sender, EventArgs e)
{
//bubble the event up to the parent
if (this.ButtonClick!= null)
this.ButtonClick(this, e);
}
Form:
UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);
protected void UserControl_ButtonClick(object sender, EventArgs e)
{
//handle the event
}
Notes:
Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e);
you can use ButtonClick?.Invoke(this, e);
, which does essentially the same, but is shorter.
The Browsable
attribute makes the event visible in Visual Studio's designer (events view), Category
shows it in the "Action" category, and Description
provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.
Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:
NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy")
Answered my own question after reading your advice on the vertical-align CSS attribute. Thanks for the tip!
.pdf:before {
padding: 0 5px 0 0;
content: url(../img/icon/pdf_small.png);
vertical-align: -50%;
}
To add on to Andrea's solution, if you are passing an array of JSONs for instance
[
{"name":"value"},
{"name":"value2"}
]
Then you will need to set up the Spring Boot Controller like so:
@RequestMapping(
value = "/process",
method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object>[] payload)
throws Exception {
System.out.println(payload);
}
At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.
Just set all the selected time unit's displayFormat
to MMM DD
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MMM DD',
'second': 'MMM DD',
'minute': 'MMM DD',
'hour': 'MMM DD',
'day': 'MMM DD',
'week': 'MMM DD',
'month': 'MMM DD',
'quarter': 'MMM DD',
'year': 'MMM DD',
}
...
Notice that I've set all the unit's display format to MMM DD
. A better way, if you have control over the range of your data and the chart size, would be force a unit, like so
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'MMM DD'
}
...
Fiddle - http://jsfiddle.net/prfd1m8q/
The magic method __getitem__
is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.
Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__
method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.
import copy
# Constants that can be used to index date of birth's Date-Month-Year
D = 0; M = 1; Y = -1
class Person(object):
def __init__(self, name, age, dob):
self.name = name
self.age = age
self.dob = dob
def __getitem__(self, indx):
print ("Calling __getitem__")
p = copy.copy(self)
p.name = p.name.split(" ")[indx]
p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
return p
Suppose one user input is as follows:
p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))
With the help of __getitem__
method, the user can access the indexed attributes. e.g.,
print p[0].name # print first (or last) name
print p[Y].dob # print (Date or Month or ) Year of the 'date of birth'
IIS will create it again AFAIK.
I did not find the accepted answer helpful in resolving the exception encountered in my code. And while not technically incorrect, I was also not satisfied with others' suggestions to introduce redundancy:
configuration.addAnnotatedClass(...)
hbm.xml
file and resource mapping in hibernate_test.cfg.xml
that were redundant to the existing annotationsHowever, I found 2 possible solutions that I wanted to share, both of which independently resolved the exception I encountered in my own code.
I was having the same MappingException
as @ron (using a very nearly identical HibernateUtil
class):
public final class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static ServiceRegistry serviceRegistry = null;
private HibernateUtil() {}
public static synchronized SessionFactory getSessionFactory() {
if ( sessionFactory == null ) {
Configuration configuration = new Configuration().configure("hibernate_test.cfg.xml");
serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
sessionFactory = configuration.buildSessionFactory( serviceRegistry );
}
return sessionFactory;
}
// exception handling and closeSessionFactory() omitted for brevity
}
Within my hibernate_test.cfg.xml
configuration file, I have the required class mapping:
<mapping class="myPackage.Device"/>
And my Device
class is properly annotated with the javax.persistence.Entity
annotation:
package myPackage.core;
import javax.persistence.*;
@Entity
@Table( name = "devices" )
public class Device {
//body omitted for brevity
}
Two Possible Solutions:
First, I am using Hibernate 5.2, and for those using Hibernate 5 this solution using a Metadata
object to build a SessionFactory
should work. It also appears to be the currently recommended native bootstrap mechanism in the Hibernate Getting Started Guide :
public static synchronized SessionFactory getSessionFactory() {
if ( sessionFactory == null ) {
// exception handling omitted for brevity
serviceRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate_test.cfg.xml")
.build();
sessionFactory = new MetadataSources( serviceRegistry )
.buildMetadata()
.buildSessionFactory();
}
return sessionFactory;
}
Second, while Configuration
is semi-deprecated in Hibernate 5, @ron didn't say which version of Hibernate he was using, so this solution could also be of value to some.
I found a very subtle change in the order of operations when instantiating and configuring Configuration
and ServiceRegistry
objects to make all the difference in my own code.
Original order (Configuration
created and configured prior to ServiceRegistry
):
public static synchronized SessionFactory getSessionFactory() {
if ( sessionFactory == null ) {
// exception handling omitted for brevity
Configuration configuration = new Configuration().configure("hibernate_test.cfg.xml");
serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings( configuration.getProperties() )
.build();
sessionFactory = configuration.buildSessionFactory( serviceRegistry );
}
return sessionFactory;
}
New order (ServiceRegistry
created and configured prior to Configuration
):
public static synchronized SessionFactory getSessionFactory() {
if ( sessionFactory == null ) {
// exception handling omitted for brevity
serviceRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate_test.cfg.xml")
.build();
sessionFactory = new Configuration().buildSessionFactory( serviceRegistry );
}
return sessionFactory;
}
At the risk of TLDR, I will also point out that with respect to hibernate_test.cfg.xml
my testing suggests that the configuration.getProperties()
method only returns <property />
elements, and <mapping />
elements are excluded. This appears consistent with the specific use of the terms 'property' and 'mapping' within the API documentation for Configuration
. I will concede that this behaviour may have something to do with the failure of applySettings()
to yield the mapping data to the StandardServiceRegistryBuilder
. However, this mapping data should already have been parsed during configuration of the Configuration
object and available to it when buildSessionFactory()
is called. Therefore, I suspect this may be due to implementation-specific details regarding resource precedence when a ServiceRegistry
is passed to a Configuration
object's buildSessionFactory()
method.
I know this question is several years old now, but I hope this answer saves somebody the hours of research I spent in deriving it. Cheers!
Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
They could then be used like so:
[MyClass aClassMethod];
MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];
Some real world examples of class methods are the convenience methods on many Foundation classes like NSString
's +stringWithFormat:
or NSArray
's +arrayWithArray:
. An instance method would be NSArray
's -count
method.
you could use fopen() function.
some example:
$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
$newfname = $destination_folder .'myfile.mp4'; //set your file ext
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "a"); // to overwrite existing file
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
If start
can't find what it's looking for, it does what you describe.
Since what you're doing should work, it's very likely you're leaving out some quotes (or putting extras in).
$http_name_of_the_header_key
i.e if you have origin = domain.com
in header, you can use $http_origin
to get "domain.com"
In nginx does support arbitrary request header field. In the above example last part of a variable name is the field name converted to lower case with dashes replaced by underscores
Reference doc here: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_
For your example the variable would be $http_my_custom_header
.
Thread.interrupt()
sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted()
can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html
In command line prompt:
set __COMPAT_LAYER=RUNASINVOKER
SystemPropertiesAdvanced.exe
Now you can set user environment variables.
my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine
I had this error message with boot2docker on windows with the docker-oracle-xe-11g image (https://registry.hub.docker.com/u/wnameless/oracle-xe-11g/).
The reason was that the virtual box disk was full (check with boot2docker.exe ssh df
). Deleting old images and restarting the container solved the problem.
You may need to do a combination of the above to resolve this problem. I normally get this error when I do
mvn clean install
and see a compile error preventing the my tests from fully compiling.
Assuming the issues resolved by the above have been dealt with, try clicking Project, Clean, and clean the project which contains the test you want to run. Also make sure Build Automatically is checked.
git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d
where grep -E -v
is equivalent of egrep -v
Use -d
to remove already merged branches or
-D
to remove unmerged branches
In Windows it worked for me only after trying the following: 1. Open cmd inside the folder where "requests" is unpacked. (CTRL+SHIFT+right mouse click, choose the appropriate popup menu item) 2. (Here is the path to your pip3.exe)\pip3.exe install requests Done
I realize this is an older post but I had the same error on IIS 8.5. Hopefully this can help another experiencing the same issue (I didn't see my issue outlined in other questions with a similar title).
Everything seemed set up correctly with the Application Pool Identity, but I continued to receive the error. After much digging, there is a setting for the anonymous user to use the credentials of the application pool identity or a specific user. For whatever reason, mine was defaulted to a specific user. Altering the setting to the App Pool Identity fixed the issue for me.
Hopefully this saves someone else some time!
short answer, partial
gives default values to the parameters of a function that would otherwise not have default values.
from functools import partial
def foo(a,b):
return a+b
bar = partial(foo, a=1) # equivalent to: foo(a=1, b)
bar(b=10)
#11 = 1+10
bar(a=101, b=10)
#111=101+10
If you want to fire the event only on changes of your input use:
$('.s').bind('input', function(){
console.log("search!");
doSearch();
});
I tried in the following way
aws s3 ls s3://Bucket1/folder1/2019/ --recursive |grep filename.csv
This outputs the actual path where the file exists
2019-04-05 01:18:35 111111 folder1/2019/03/20/filename.csv
Use Map interface and an implementation like HashMap
You can also edit 'hosts' file and create local variation of your domain.
Example
If your real facebook application address is "example.com" you can create "localhost.example.com" (accessible only from your pc) domain in your "hosts" file pointing to "localhost" and run your local website under this domain. You can trick Facebook this way.
And if you neither want to use @Autowire nor injecting @Value you can simply do (with fallback included):
System.getProperty("spring.profiles.active", "unknown");
This will return any active profile (or fallback to 'unknown').
Prepare: 1. HostA is SMTP virtual server with default port 25 2. HostB is a workstation on which I send mail with SmtpClient and simulate unstable network I use clumsy
Case 1 Given If HostB is 2008R2 When I send email. Then This issue occurs.
Case 2 Given If HostB is 2012 or higher version When I send email. Then The mail was sent out.
Conclusion: This root cause is related with Windows Server 2008R2.
This usually happens when you have edited a file from Windows and now trying to execute that from some unix based machine.
The solution presented on Linux Forum worked for me (many times):
perl -i -pe's/\r$//;' <file name here>
Hope this helps.
PS: you need to have perl installed on your unix/linux machine.
I belive this is the easiest way:
org.apache.commons.io.FileUtils.readFileToByteArray(file);
You have several options for iterating over a dictionary.
If you iterate over the dictionary itself (for team in league
), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league
) itself, or league.keys()
:
for team in league.keys():
runs_scored, runs_allowed = map(float, league[team])
You can also iterate over both the keys and the values at once by iterating over league.items()
:
for team, runs in league.items():
runs_scored, runs_allowed = map(float, runs)
You can even perform your tuple unpacking while iterating:
for team, (runs_scored, runs_allowed) in league.items():
runs_scored = float(runs_scored)
runs_allowed = float(runs_allowed)
Open Sublime Text console ? paste in opened field:
sublime.packages_path()
? Enter. You get result in console output.
This answer is relevant for April 2018. In the future, the data of this answer may be obsolete.
I'm not recommended @osiris answer. Arguments:
Packages
folder.Apart from fixing the imports, do a fresh maven clean compile -U
. Note the -U
option, that brings in new dependencies which sometimes the editor has hard time with. Let the compilation fail due to un-imported classes, but at least you have an option to import them after the maven command.
Just doing Maven->Reimport from Intellij did not work for me.
There are numerous ways to store credentials while still using boto3.resource(). I'm using the AWS CLI method myself. It works perfectly.
Use:
IF Var IS NULL THEN
var := 5;
END IF;
Oracle 9i+:
var = COALESCE(Var, 5)
Other alternatives:
var = NVL(var, 5)
Reference:
Assuming you know the size of your footer, you can do this:
footer {
position: sticky;
height: 100px;
top: calc( 100vh - 100px );
}
Use:
*.dll #Exclude all dlls
!foo.dll #Except for foo.dll
From gitignore:
An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
This question is about bootstrap date picker. But all of the above answers are for the jquery date picker. For Bootstrap datepicker, you just need to provide the defaut date in the value of the input element. Like this.
<input class="form-control datepicker" value=" <?= date("Y-m-d") ?>">
Here's an efficient way of achieving the result with two caveats.
See sample test cases here.
123.12345678 ==> 123.123
1.230000 ==> 1.23
1.1 ==> 1.1
1 ==> 1.0
0.000 ==> 0.0
0.00 ==> 0.0
0.4 ==> 0.4
0 ==> 0.0
1.4999 ==> 1.499
1.4995 ==> 1.499
1.4994 ==> 1.499
Here's the code. The two caveats I mentioned above can be addressed pretty easily, however, speed mattered more to me than accuracy, so i left it here.
String manipulations like System.out.printf("%.2f",123.234);
are computationally costly compared to mathematical operations. In my tests, the below code (without the sysout) took 1/30th the time compared to String manipulations.
public double limitPrecision(String dblAsString, int maxDigitsAfterDecimal) {
int multiplier = (int) Math.pow(10, maxDigitsAfterDecimal);
double truncated = (double) ((long) ((Double.parseDouble(dblAsString)) * multiplier)) / multiplier;
System.out.println(dblAsString + " ==> " + truncated);
return truncated;
}
You can also specify a commit hash
(often also called commit ID
) with the git show
command.
git show <commitHash>:/path/to/file
git log /path/to/file
commit hash
such as commit 06c98...
(06c98... being the commit hash)commit hash
git show <commitHash>:/path/to/file
using the commit hash
of step 3 & the path/to/file
of step 1.Note: adding the ./
when specifying a relative path seems important, i.e. git show b2f8be577166577c59b55e11cfff1404baf63a84:./flight-simulation/src/main/components/nav-horiz.html
.
Here's the exact definition of UsedRange
(MSDN reference) :
Every Worksheet object has a UsedRange property that returns a Range object representing the area of a worksheet that is being used. The UsedRange property represents the area described by the farthest upper-left and farthest lower-right nonempty cells in a worksheet and includes all cells in between.
So basically, what that line does is :
.UsedRange
-> "Draws" a box around the outer-most cells with content inside..Columns
-> Selects the entire columns of those cells.Count
-> Returns an integer corresponding to how many columns there are (in this selection)- 8
-> Subtracts 8 from the previous integer.I assume VBA calculates the UsedRange by finding the non-empty cells with lowest and highest index values.
Most likely, you're getting an error because the number of lines in your range is smaller than 3, and therefore the number returned is negative.
You need to click Log Navigator icon (far right in left sidebar). Then choose your Debug/Run session in left sidebar, and you will have console in editor area.
These all do {1..8}
and should all be POSIX. They also will not break if you
put a conditional continue
in the loop. The canonical way:
f=
while [ $((f+=1)) -le 8 ]
do
echo $f
done
Another way:
g=
while
g=${g}1
[ ${#g} -le 8 ]
do
echo ${#g}
done
and another:
set --
while
set $* .
[ ${#} -le 8 ]
do
echo ${#}
done
I know this is a fairly old question, but I was searching for a solution to generically deserialize nested JSON to a Map<String, Object>
, and found nothing.
The way my yaml deserializer works, it defaults JSON objects to Map<String, Object>
when you don't specify a type, but gson doesn't seem to do this. Luckily you can accomplish it with a custom deserializer.
I used the following deserializer to naturally deserialize anything, defaulting JsonObject
s to Map<String, Object>
and JsonArray
s to Object[]
s, where all the children are similarly deserialized.
private static class NaturalDeserializer implements JsonDeserializer<Object> {
public Object deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) {
if(json.isJsonNull()) return null;
else if(json.isJsonPrimitive()) return handlePrimitive(json.getAsJsonPrimitive());
else if(json.isJsonArray()) return handleArray(json.getAsJsonArray(), context);
else return handleObject(json.getAsJsonObject(), context);
}
private Object handlePrimitive(JsonPrimitive json) {
if(json.isBoolean())
return json.getAsBoolean();
else if(json.isString())
return json.getAsString();
else {
BigDecimal bigDec = json.getAsBigDecimal();
// Find out if it is an int type
try {
bigDec.toBigIntegerExact();
try { return bigDec.intValueExact(); }
catch(ArithmeticException e) {}
return bigDec.longValue();
} catch(ArithmeticException e) {}
// Just return it as a double
return bigDec.doubleValue();
}
}
private Object handleArray(JsonArray json, JsonDeserializationContext context) {
Object[] array = new Object[json.size()];
for(int i = 0; i < array.length; i++)
array[i] = context.deserialize(json.get(i), Object.class);
return array;
}
private Object handleObject(JsonObject json, JsonDeserializationContext context) {
Map<String, Object> map = new HashMap<String, Object>();
for(Map.Entry<String, JsonElement> entry : json.entrySet())
map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class));
return map;
}
}
The messiness inside the handlePrimitive
method is for making sure you only ever get a Double or an Integer or a Long, and probably could be better, or at least simplified if you're okay with getting BigDecimals, which I believe is the default.
You can register this adapter like:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();
And then call it like:
Object natural = gson.fromJson(source, Object.class);
I'm not sure why this is not the default behavior in gson, since it is in most other semi-structured serialization libraries...
try overflow hidden on the thing you don't want to scroll while touch event is happening. e.g set overflow hidden on Start and set it back to auto on end.
Did you try it ? I'd be interested to know if this would work.
document.addEventListener('ontouchstart', function(e) {
document.body.style.overflow = "hidden";
}, false);
document.addEventListener('ontouchmove', function(e) {
document.body.style.overflow = "auto";
}, false);
<!-- Server port-->
server.port=8080
<!--Context Path of the Application-->
server.servlet.context-path=/ems
In child component:
this.$emit('eventname', this.variable)
In parent component:
<component @eventname="updateparent"></component>
methods: {
updateparent(variable) {
this.parentvariable = variable
}
}
This is my version of check ping function. May be if well be usefull for someone:
def check_ping(host):
if platform.system().lower() == "windows":
response = os.system("ping -n 1 -w 500 " + host + " > nul")
if response == 0:
return "alive"
else:
return "not alive"
else:
response = os.system("ping -c 1 -W 0.5" + host + "> /dev/null")
if response == 1:
return "alive"
else:
return "not alive"
var results = list.GroupBy(x => x.Category)
.Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());
For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.
Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.