For showing Forbidden error then include these lines in your .htaccess file:
Options -Indexes
If we want to index our files and showing them with some information, then use:
IndexOptions -FancyIndexing
If we want for some particular extension not to show, then:
IndexIgnore *.zip *.css
set list = a1-2019 a3-2018 a4-2017
setlocal enabledelayedexpansion
set backup=
set bb1=
for /d %%d in (%list%) do (
set td=%%d
set x=!td!
set y=!td!
set y=!y:~-4!
if !y! gtr !bb1! (
set bb1=!y!
set backup=!x!
)
)
rem: backup will be 2019
echo %backup%
There are a number of approaches here- and though the position is that typically users should not be restricted when it comes to zooming for accessibility purposes, there may be incidences where is it required:
Render the page at the width of the device, dont scale:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Prevent scaling- and prevent the user from being able to zoom:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
Removing all zooming, all scaling
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
For a UWP app:
XAML
<ListBox x:Name="List" DisplayMemberPath="Source" ItemsSource="{x:Bind Results}"/>
C#
public ObservableCollection<Type> Results
Please follow those steps.
Bundle your js:
if you have index.android.js in project root then run
react-native bundle --dev false --platform android --entry-file index.android.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug
if you have index.js in project root then run
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Create debug apk:
cd android/
./gradlew assembleDebug
Then You can find your apk here:
cd app/build/outputs/apk/
The @Url.Action()
method is proccess on the server-side
, so you cannot pass a client-side
value to this function as a parameter. You can concat the client-side
variables with the server-side
url generated by this method, which is a string on the output. Try something like this:
var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;
The @Url.Action("Display", "Customer")
is processed on the server-side
and the rest of the string is processed on the client-side
, concatenating the result of the server-side
method with the client-side
.
This plugin is documented rather good in https://polylang.wordpress.com/documentation.
The developers documentation states the following logic as a means to generate URL's for different translations of the same post
<?php while ( have_posts() ) : the_post(); ?>
<ul class='translations'><?php pll_the_languages(array('post_id' =>; $post->ID)); ?></ul>
<?php the_content(); ?>
<?php endwhile; ?>
If you want more influence on what is rendered, inspet pll_the_languages
function and copy it's behaviour to your own output implementation
As you want buttons to switch language, this page: https://polylang.wordpress.com/documentation/frequently-asked-questions/the-language-switcher/ will give you the required info.
An implementation example:
<ul><?php pll_the_languages();?></ul>
Then style with CSS to create buttons, flags or whatever you want. It is also possible to use a widget for this, provided by te plugin
All plugins functions are explained here: https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/
In this case use:
pll_current_language();
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.
Dim s1 As String
Dim i As Integer
s1 = "Hello"
i = 1
String.Format("{0} {1}", s1, i)
It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?
SEVERE: Error listenerStart
This boils down to that a ServletContextListener
which is registered by either @WebListener
annotation on the class, or by a <listener>
declaration in web.xml
, has thrown an unhandled exception inside the contextInitialized()
method. This is usually caused by a developer's mistake (a bug) and needs to be fixed. For example, a NullPointerException
.
The full exception should be visible in webapp-specific startup log as well as the IDE console, before the particular line which you've copypasted. If there is none and you still can't figure the cause of the exception by just looking at the code, put the entire contextInitialized()
code in a try-catch
wherein you log the exception to a reliable output and then interpret and fix it accordingly.
OPTION 1: Add this line to ~/.zshrc:
export "PATH=$HOME/pear/bin:$PATH"
After that you need to run source ~/.zshrc
in order your changes to take affect OR close this window and open a new one
OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.
The problem is your query returned false
meaning there was an error in your query. After your query you could do the following:
if (!$result) {
die(mysqli_error($link));
}
Or you could combine it with your query:
$results = mysqli_query($link, $query) or die(mysqli_error($link));
That will print out your error.
Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:
$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist
Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.
You can go with POSTMAN, an application who makes APIs easy. Fill request fields and then it will generate code for you in different languages. Just click code on the right side and select your prefered language.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.
Here are the options in question :
-T seconds
--timeout=seconds
Set the network timeout to seconds seconds. This is equivalent to specifying
--dns-timeout
,--connect-timeout
, and--read-timeout
, all at the same time.
And for those three options :
--dns-timeout=seconds
Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.
--connect-timeout=seconds
Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.
--read-timeout=seconds
Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.
I suppose using something like
wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run
should make sure there is no timeout before longer than the duration of your script.
(Yeah, that's probably the most brutal solution possible ^^ )
I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.
This is the method for rotating the Matrix:
this.matrix.reset();
this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY());
(this.getCenterX()
is basically the bitmaps X position + the bitmaps width / 2)
And the method for Drawing the bitmap (called via a RenderManager
Class):
canvas.drawBitmap(this.bitmap, this.matrix, null);
So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate
followed by postTranslate
. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/
Anyways, thanks for your help!
Using EntrySet() and for each loop
for(Map.Entry<String, String> entry: hashMap.entrySet()) {
System.out.println("Key Of map = "+ entry.getKey() +
" , value of map = " + entry.getValue() );
}
Using keyset() and for each loop
for(String key : hashMap.keySet()) {
System.out.println("Key Of map = "+ key + " ,
value of map = " + hashMap.get(key) );
}
Using EntrySet() and java Iterator
for(String key : hashMap.keySet()) {
System.out.println("Key Of map = "+ key + " ,
value of map = " + hashMap.get(key) );
}
Using keyset() and java Iterator
Iterator<String> keysIterator = keySet.iterator();
while (keysIterator.hasNext()) {
String key = keysIterator.next();
System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
}
Reference : How to iterate over Map or HashMap in java
Unfortunately I couldn't comment on the Sean Rose post due to insufficient reputation, however I had to amend the "public" role portion of the script as it didn't show SCHEMA-scoped permissions due to the (INNER) JOIN against sys.objects. After that was changed to a LEFT JOIN I further had to amend the WHERE-clause logic to omit system objects. My amended query for the public perms is below.
--3) List all access provisioned to the public role, which everyone gets by default
SELECT
@@servername ServerName
, db_name() DatabaseName
, [UserType] = '{All Users}',
[DatabaseUserName] = '{All Users}',
[LoginName] = '{All Users}',
[Role] = roleprinc.[name],
[PermissionType] = perm.[permission_name],
[PermissionState] = perm.[state_desc],
[ObjectType] = CASE perm.[class]
WHEN 1 THEN obj.[type_desc] -- Schema-contained objects
ELSE perm.[class_desc] -- Higher-level objects
END,
[Schema] = objschem.[name],
[ObjectName] = CASE perm.[class]
WHEN 3 THEN permschem.[name] -- Schemas
WHEN 4 THEN imp.[name] -- Impersonations
ELSE OBJECT_NAME(perm.[major_id]) -- General objects
END,
[ColumnName] = col.[name]
FROM
--Roles
sys.database_principals AS roleprinc
--Role permissions
LEFT JOIN sys.database_permissions AS perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN sys.schemas AS permschem ON permschem.[schema_id] = perm.[major_id]
--All objects
LEFT JOIN sys.objects AS obj ON obj.[object_id] = perm.[major_id]
LEFT JOIN sys.schemas AS objschem ON objschem.[schema_id] = obj.[schema_id]
--Table columns
LEFT JOIN sys.columns AS col ON col.[object_id] = perm.[major_id]
AND col.[column_id] = perm.[minor_id]
--Impersonations
LEFT JOIN sys.database_principals AS imp ON imp.[principal_id] = perm.[major_id]
WHERE
roleprinc.[type] = 'R'
AND roleprinc.[name] = 'public'
AND isnull(obj.[is_ms_shipped], 0) = 0
AND isnull(object_schema_name(perm.[major_id]), '') <> 'sys'
ORDER BY
[UserType],
[DatabaseUserName],
[LoginName],
[Role],
[Schema],
[ObjectName],
[ColumnName],
[PermissionType],
[PermissionState],
[ObjectType]
tr -d "\r" < file
take a look here for examples using sed
:
# IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format.
sed 's/.$//' # assumes that all lines end with CR/LF
sed 's/^M$//' # in bash/tcsh, press Ctrl-V then Ctrl-M
sed 's/\x0D$//' # works on ssed, gsed 3.02.80 or higher
# IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format.
sed "s/$/`echo -e \\\r`/" # command line under ksh
sed 's/$'"/`echo \\\r`/" # command line under bash
sed "s/$/`echo \\\r`/" # command line under zsh
sed 's/$/\r/' # gsed 3.02.80 or higher
Use sed -i
for in-place conversion e.g. sed -i 's/..../' file
.
The Saxon documentation, though a little unclear, seems to suggest that the JAXP XPath API will return false
when evaluating an XPath expression if no matching nodes are found.
This IBM article mentions a return value of null
when no nodes are matched.
You might need to play around with the return types a bit based on this API, but the basic idea is that you just run a normal XPath and check whether the result is a node / false
/ null
/ etc.
XPathFactory xpathFactory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile("/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml");
Object result = expr.evaluate(doc, XPathConstants.NODE);
if ( result == null ) {
// do something
}
It would be easier to recreate the data frame. This would also interpret the columns types from scratch.
headers = df.iloc[0]
new_df = pd.DataFrame(df.values[1:], columns=headers)
go to information_schema database there you will find 'tables' table then select it;
Mysql>use information_schema; Mysql> select table_name,engine from tables;
Try this-
driver.findElement(By.name("period")).sendKeys("Last 52 Weeks");
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
In addition to @Bruno's answer, you need to supply the -name
for alias, otherwise Tomcat will throw Alias name tomcat does not identify a key entry
error
Sample Command:
openssl pkcs12 -export -in localhost.crt -inkey localhost.key -out localhost.p12 -name localhost
first,use git pull
to merge repository save your change.then retype git commit -m "your commit"
.
Much more convenient way if you are sure you need a default timezone :
Date d = java.sql.Timestamp.valueOf( myLocalDateTime );
Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.
I like indent
as mentioned above, but most often I want to format only a small section of the file that I'm working on. Since indent
can take code from stdin, its really simple:
:!indent
.astyle
takes stdin too, so you can use the same trick there.
Like other answers pointed out, you might find it easier to work with an array.
If not:
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
// Get the current size of the object
size = Object.keys(alerts).length
//add a new alert
alerts[size + 1] = {app:'Your new app', message:'your new message'}
//Result:
console.log(alerts)
{
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
3: {app: "Another hello",message: "Another message"}
}
try it:
jsFunction is not in good closure. change to:
jsFunction = function(value)
{
alert(value);
}
and don't use global variables and functions, change it into module
Instead of navigating to blank, you can do
webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();
No need to wait for events or anything else. You can check the MSDN for OpenNew, while I have tested the initial DocumentText assignment in one of my projects and it works.
The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.
"koan" == "koan" # Output: => true
The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.
"koan" != "discursive thought" # Output: => true
Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.
When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.
2 == 2.0 # Output: => true
Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.
Example: a = "zen" b = "zen"
a.object_id # Output: => 20139460
b.object_id # Output :=> 19972120
a.equal? b # Output: => false
In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.
Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.
a = "zen"
b = a
a.object_id # Output: => 18637360
b.object_id # Output: => 18637360
a.equal? b # Output: => true
In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.
Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).
"meditation".hash # Output: => 1396080688894079547
"meditation".hash # Output: => 1396080688894079547
"meditation".hash # Output: => 1396080688894079547
The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.
Symbol.instance_method(:hash).owner # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel
String.instance_method(:hash).owner # Output: => String
Hash.instance_method(:hash).owner # Output: => Hash
In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.
"zen".eql? "zen" # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true
In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.
2 == 2.0 # Output: => true
2.eql? 2.0 # Output: => false
2.hash == 2.0.hash # Output: => false
Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).
String === "zen" # Output: => true
Range === (1..2) # Output: => true
Array === [1,2,3] # Output: => true
Integer === 2 # Output: => true
The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.
2.is_a? Integer # Output: => true
2.kind_of? Integer # Output: => true
2.instance_of? Integer # Output: => false
Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.
The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:
Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true
When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.
(1..4) === 3 # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6 # Output: => false
("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false
Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.
Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/
This operator is also used under the hood on case/when statements. That is its most common use.
minutes = 15
case minutes
when 10..20
puts "match"
else
puts "no match"
end
# Output: match
In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:
if (10..20) === minutes
puts "match"
else
puts "no match"
end
The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.
The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.
"practice zazen" =~ /zen/ # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil
:zazen =~ /zen/ # Output: => 2
:zazen =~ /discursive thought/ # Output: => nil
The implementation in the Regexp class expects a string or a symbol as an argument.
/zen/ =~ "practice zazen" # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil
In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.
puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes
Pattern-matching operators are also useful for writing shorter if statements. Example:
if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
true
end
The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.
More info is available at this blog post.
# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
iptables -A FORWARD -p all -d $ip -j REJECT
done
The error tells you that there is an error but you don´t catch it. This is how you can catch it:
getAllPosts().then(response => {
console.log(response);
}).catch(e => {
console.log(e);
});
You can also just put a console.log(reponse)
at the beginning of your API callback function, there is definitely an error message from the Graph API in it.
More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Or with async/await:
//some async function
try {
let response = await getAllPosts();
} catch(e) {
console.log(e);
}
One small point of emphasis I'll add to all the excellent answers given previously:
Probably the biggest thing you can do to avoid using Select is to as much as possible, use named ranges (combined with meaningful variable names) in your VBA code. This point was mentioned above, but it was glossed over a bit; however, it deserves special attention.
Here are a couple of additional reasons to make liberal use of named ranges, though I am sure I could think of more.
Example:
Dim Months As Range
Dim MonthlySales As Range
Set Months = Range("Months")
' E.g, "Months" might be a named range referring to A1:A12
Set MonthlySales = Range("MonthlySales")
' E.g, "Monthly Sales" might be a named range referring to B1:B12
Dim Month As Range
For Each Month in Months
Debug.Print MonthlySales(Month.Row)
Next Month
It is pretty obvious what the named ranges Months
and MonthlySales
contain, and what the procedure is doing.
Why is this important? Partially because it is easier for other people to understand it, but even if you are the only person who will ever see or use your code, you should still use named ranges and good variable names because you will forget what you meant to do with it a year later, and you will waste 30 minutes just figuring out what your code is doing.
Consider, if the above example had been written like this:
Dim rng1 As Range
Dim rng2 As Range
Set rng1 = Range("A1:A12")
Set rng2 = Range("B1:B12")
Dim rng3 As Range
For Each rng3 in rng1
Debug.Print rng2(rng3.Row)
Next rng3
This code will work just fine at first - that is until you or a future user decides "gee wiz, I think I'm going to add a new column with the year in Column A
!", or put an expenses column between the months and sales columns, or add a header to each column. Now, your code is broken. And because you used terrible variable names, it will take you a lot more time to figure out how to fix it than it should take.
If you had used named ranges to begin with, the Months
and Sales
columns could be moved around all you like, and your code would continue working just fine.
I had the same problem. I fixed it by removing/commenting proxy settings in gradle.properties. Check your gradle.properties, if you have some like this
systemProp.https.proxyPort=8080
systemProp.http.proxyHost=192.168.1.1
systemProp.https.proxyHost=192.168.1.1
systemProp.http.proxyPort=8080
comment it with #. Which will look like this
#systemProp.https.proxyPort=8080
#systemProp.http.proxyHost=192.168.1.1
#systemProp.https.proxyHost=192.168.1.1
#systemProp.http.proxyPort=8080
If you are prepending an array to the front of another array, it is more efficient to just use concat
. So:
var newArray = values.concat(oldArray);
But this will still be O(N) in the size of oldArray. Still, it is more efficient than manually iterating over oldArray. Also, depending on the details, it may help you, because if you are going to prepend many values, it's better to put them into an array first and then concat oldArray on the end, rather than prepending each one individually.
There's no way to do better than O(N) in the size of oldArray, because arrays are stored in contiguous memory with the first element in a fixed position. If you want to insert before the first element, you need to move all the other elements. If you need a way around this, do what @GWW said and use a linked list, or a different data structure.
If you want to cut out the last or the first do this:
list = ["This", "is", "a", "list"]
listnolast = list[:-1]
listnofirst = list[1:]
If you change 1 to 2 the first 2 characters will be removed not the second. Hope this still helps!
Just to elucidate a bit on @emsr's comment in @unwind's answer, if one is not fortunate enough to have a C++11 compiler (say GCC 4.2.1), and one wants to embed the newlines in the string (either char * or class string), one can write something like this:
const char *text =
"This text is pretty long, but will be\n"
"concatenated into just a single string.\n"
"The disadvantage is that you have to quote\n"
"each part, and newlines must be literal as\n"
"usual.";
Very obvious, true, but @emsr's short comment didn't jump out at me when I read this the first time, so I had to discover this for myself. Hopefully, I've saved someone else a few minutes.
PL/SQL: numeric or value error: character string buffer too small
is due to the fact that you declare a string to be of a fixed length (say 20), and at some point in your code you assign it a value whose length exceeds what you declared.
for example:
myString VARCHAR2(20);
myString :='abcdefghijklmnopqrstuvwxyz'; --length 26
will fire such an error
I'll use a common example in biology; reconstructing a genome by making DNA samples.
De-novo assembly
To construct a genome from short reads, it's necessary to construct a graph of those reads. We do it by breaking the reads into k-mers and assemble them into a graph.
We can reconstruct the genome by visiting each node once as in the diagram. This is known as Hamiltonian path.
Unfortunately, constructing such path is NP-hard. It's not possible to derive an efficient algorithm for solving it. Instead, in bioinformatics we construct a Eulerian cycle where an edge represents an overlap.
Use jQTouch instead - its jQuery's mobile version
So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:
r" |(?<![0-9])[.,](?![0-9])"
In addition to using keyup
and keydown
listeners to track when is key goes down and back up, there are actually some properties that tell you if certain keys are down.
window.onmousemove = function (e) {
if (!e) e = window.event;
if (e.shiftKey) {/*shift is down*/}
if (e.altKey) {/*alt is down*/}
if (e.ctrlKey) {/*ctrl is down*/}
if (e.metaKey) {/*cmd is down*/}
}
This are available on all browser generated event objects, such as those from keydown
, keyup
, and keypress
, so you don't have to use mousemove.
I tried generating my own event objects with document.createEvent('KeyboardEvent')
and document.createEvent('KeyboardEvent')
and looking for e.shiftKey
and such, but I had no luck.
I'm using Chrome 17 on Mac
If you have enough space on your hard-disk in your OS-X of Apple, then you could install virtualbox for Mac-OS-X after download at http://virtualbox.org
Then you would need "only" 100 GB to create with this virtualbox as virtual harddisk. Then install for intentions of tests simply for 1 month-free-testtime a Windows of your choice - Vista or 7 or 8 - together with internet explorer ...
You dont need to buy Windows for this as long as you dont test longer than one month - when testing time is expired it is not tragic at all, you simply can repeat a new testing-time ...
This looks trivial but with virtualbox you have a real-time-testing-area in this case with IE - no matter which version of IE !
To solve this you must ensure the following is true on the machine hosting SQL Server...
Use the .Select()
after grouping:
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyContractID, // required by your view model. should be omited
// in most cases because group by primary key
// makes no sense.
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyContractID = ac.Key.AgencyContractID,
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Amount = ac.Sum(acs => acs.Amount),
Fee = ac.Sum(acs => acs.Fee)
});
You could do this with an INSTEAD OF INSERT
trigger on the table, that checks for the existance of the row and then updates/inserts depending on whether it exists already. There is an example of how to do this for SQL Server 2000+ on MSDN here:
CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
FROM Person P, inserted I
WHERE P.SSN = I.SSN))
INSERT INTO Person
SELECT SSN,Name,Address,Birthdate
FROM inserted
ELSE
-- Log attempt to insert duplicate Person row in PersonDuplicates table.
INSERT INTO PersonDuplicates
SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
FROM inserted
-- Check for duplicate Employee. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT E.SSN
FROM EmployeeTable E, inserted
WHERE E.SSN = inserted.SSN))
INSERT INTO EmployeeTable
SELECT EmployeeID,SSN, Department, Salary
FROM inserted
ELSE
--If duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
UPDATE EmployeeTable
SET EmployeeID = I.EmployeeID,
Department = I.Department,
Salary = I.Salary
FROM EmployeeTable E, inserted I
WHERE E.SSN = I.SSN
END
After following the instructions in the other answers, I needed to strip the version from the map file for this to work for me.
Example: Rename
jquery-1.9.1.min.map
to
jquery.min.map
http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css
Line 11:
.postItem img {
height: auto;
width: 450px;
}
You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:
<img src="theSource" style="width:30px;" />
Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.
For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:
If destination is a file: echo f | [batch file path]
If folder: echo d | [batch file path]
It will essentially just pipe the letter after "echo" to the input of the batch file.
The '\r'
character (carriage return) resets the cursor to the beginning of the line and allows you to write over what was previously on the line.
from time import sleep
import sys
for i in range(21):
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
sys.stdout.flush()
sleep(0.25)
I'm not 100% sure if this is completely portable across all systems, but it works on Linux and OSX at the least.
All your problems derive from this
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;
Which are enclosed in a try, catch block, the problem is that in case the program found an exception you are not returning anything. Put it like this (modify it as your program logic stands):
public static byte[] encrypt(String toEncrypt) throws Exception{
try{
String plaintext = toEncrypt;
String key = "01234567890abcde";
String iv = "fedcba9876543210";
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;
} catch(Exception e){
return null; // Always must return something
}
}
For the second one you must catch the Exception from the encrypt method call, like this (also modify it as your program logic stands):
public void actionPerformed(ActionEvent e)
.
.
.
try {
byte[] encrypted = encrypt(concatURL);
String encryptedString = bytesToHex(encrypted);
content.removeAll();
content.add(new JLabel("Concatenated User Input -->" + concatURL));
content.add(encryptedTextField);
setContentPane(content);
} catch (Exception exc) {
// TODO: handle exception
}
}
The lessons you must learn from this:
After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,
client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
Although btnMybutton.getBackground().setAlpha(45);
is nice idea, it just apply alpha to background and not the whole view.
If you want apply alpha to view use btnMybutton.setAlpha(0.30f);
instead. This apply opacity to View. It accepts a value between 0 and 1.
Doc says:
Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque. If this view overrides onSetAlpha(int) to return true, then this view is responsible for applying the opacity itself. Otherwise, calling this method is equivalent to calling setLayerType(int, android.graphics.Paint) and setting a hardware layer. Note that setting alpha to a translucent value (0 < alpha < 1) may have performance implications. It is generally best to use the alpha property sparingly and transiently, as in the case of fading animations.
In my case, this error happened because my HTML had a trailing linebreak.
var myHtml = '<p>\
This should work.\
But does not.\
</p>\
';
jQuery('.something').append(myHtml); // this causes the error
To avoid the error, you just need to trim the HTML.
jQuery('.something').append(jQuery.trim(myHtml)); // this works
You can use type
or isinstance
.
In Python 2:
>>> type(u'abc') # Python 2 unicode string literal
<type 'unicode'>
>>> type('abc') # Python 2 byte string literal
<type 'str'>
In Python 2, str
is just a sequence of bytes. Python doesn't know what
its encoding is. The unicode
type is the safer way to store text.
If you want to understand this more, I recommend http://farmdev.com/talks/unicode/.
In Python 3:
>>> type('abc') # Python 3 unicode string literal
<class 'str'>
>>> type(b'abc') # Python 3 byte string literal
<class 'bytes'>
In Python 3, str
is like Python 2's unicode
, and is used to
store text. What was called str
in Python 2 is called bytes
in Python 3.
You can call decode
. If it raises a UnicodeDecodeError exception, it wasn't valid.
>>> u_umlaut = b'\xc3\x9c' # UTF-8 representation of the letter 'Ü'
>>> u_umlaut.decode('utf-8')
u'\xdc'
>>> u_umlaut.decode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
The UnsupportedClassVersionError
means that you are probably using (installed) an older version of Java as used to create the JAR.
Go to java.sun.com page, download and install a newer JRE (Java Runtime Environment).
if you want/need to develop with Java, you will need the JDK which includes the JRE.
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
You could use mapvalues()
from the plyr package.
Initial data:
dat <- data.frame(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"))
> dat
HouseType
1 Semi
2 Single
3 Row
4 Single
5 Apartment
6 Apartment
7 Row
Lookup / crosswalk table:
lookup <- data.frame(type_text = c("Semi", "Single", "Row", "Apartment"), type_num = c(1, 2, 3, 4))
> lookup
type_text type_num
1 Semi 1
2 Single 2
3 Row 3
4 Apartment 4
Create the new variable:
dat$house_type_num <- plyr::mapvalues(dat$HouseType, from = lookup$type_text, to = lookup$type_num)
Or for simple replacements you can skip creating a long lookup table and do this directly in one step:
dat$house_type_num <- plyr::mapvalues(dat$HouseType,
from = c("Semi", "Single", "Row", "Apartment"),
to = c(1, 2, 3, 4))
Result:
> dat
HouseType house_type_num
1 Semi 1
2 Single 2
3 Row 3
4 Single 2
5 Apartment 4
6 Apartment 4
7 Row 3
You can try using Seaborn. It works for both 2.7 as well as 3.6. You can install it by running:
pip install seaborn
As others have suggested, a relational database could be more useful to you. You can use a in-memory sqlite3 database as a data structure to create tables and then query them.
import sqlite3
c = sqlite3.Connection(':memory:')
c.execute('CREATE TABLE jobs (state, county, title, count)')
c.executemany('insert into jobs values (?, ?, ?, ?)', [
('New Jersey', 'Mercer County', 'Programmers', 81),
('New Jersey', 'Mercer County', 'Plumbers', 3),
('New Jersey', 'Middlesex County', 'Programmers', 81),
('New Jersey', 'Middlesex County', 'Salesmen', 62),
('New York', 'Queens County', 'Salesmen', 36),
('New York', 'Queens County', 'Plumbers', 9),
])
# some example queries
print list(c.execute('SELECT * FROM jobs WHERE county = "Queens County"'))
print list(c.execute('SELECT SUM(count) FROM jobs WHERE title = "Programmers"'))
This is just a simple example. You could define separate tables for states, counties and job titles.
After show table, above the table ( +options ) Hyperlink is there.
Below command worked out pretty good:
javac -version
I also manually verified by navigating to the Java Folder on my Mac
/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk
You can add parameters to the request from a middleware by doing:
public function handle($request, Closure $next)
{
$request->route()->setParameter('foo', 'bar');
return $next($request);
}
check this
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
list[0:10]
Outputs:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/
I renamed your container
div to overlay
, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.
The resulting html is :
<div class="overlay">
<div id="loading-img"></div>
</div>
<div class="content">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
<button id="button">Submit</button>
</div>
The css of the overlay is the following
.overlay {
background: #e9e9e9; <- I left your 'gray' background
display: none; <- Not displayed by default
position: absolute; <- This and the following properties will
top: 0; make the overlay, the element will expand
right: 0; so as to cover the whole body of the page
bottom: 0;
left: 0;
opacity: 0.5;
}
I added some dummy text so as to have something to overlay.
Then, in the click
handler we just need to show the overlay :
$("#button").click(function () {
$(".overlay").show();
});
Extract unique words sorted ASC from a list of phrases:
List<String> phrases = Arrays.asList(
"sporadic perjury",
"confounded skimming",
"incumbent jailer",
"confounded jailer");
List<String> uniqueWords = phrases
.stream()
.flatMap(phrase -> Stream.of(phrase.split("\\s+")))
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println("Unique words: " + uniqueWords);
... and the output:
Unique words: [confounded, incumbent, jailer, perjury, skimming, sporadic]
This UtilException
helper class lets you use any checked exceptions in Java streams, like this:
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(rethrowFunction(Class::forName))
.collect(Collectors.toList());
Note Class::forName
throws ClassNotFoundException
, which is checked. The stream itself also throws ClassNotFoundException
, and NOT some wrapping unchecked exception.
public final class UtilException {
@FunctionalInterface
public interface Consumer_WithExceptions<T, E extends Exception> {
void accept(T t) throws E;
}
@FunctionalInterface
public interface BiConsumer_WithExceptions<T, U, E extends Exception> {
void accept(T t, U u) throws E;
}
@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Exception> {
R apply(T t) throws E;
}
@FunctionalInterface
public interface Supplier_WithExceptions<T, E extends Exception> {
T get() throws E;
}
@FunctionalInterface
public interface Runnable_WithExceptions<E extends Exception> {
void run() throws E;
}
/** .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name)))); or .forEach(rethrowConsumer(ClassNameUtil::println)); */
public static <T, E extends Exception> Consumer<T> rethrowConsumer(Consumer_WithExceptions<T, E> consumer) throws E {
return t -> {
try { consumer.accept(t); }
catch (Exception exception) { throwAsUnchecked(exception); }
};
}
public static <T, U, E extends Exception> BiConsumer<T, U> rethrowBiConsumer(BiConsumer_WithExceptions<T, U, E> biConsumer) throws E {
return (t, u) -> {
try { biConsumer.accept(t, u); }
catch (Exception exception) { throwAsUnchecked(exception); }
};
}
/** .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName)) */
public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E {
return t -> {
try { return function.apply(t); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
};
}
/** rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))), */
public static <T, E extends Exception> Supplier<T> rethrowSupplier(Supplier_WithExceptions<T, E> function) throws E {
return () -> {
try { return function.get(); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
};
}
/** uncheck(() -> Class.forName("xxx")); */
public static void uncheck(Runnable_WithExceptions t)
{
try { t.run(); }
catch (Exception exception) { throwAsUnchecked(exception); }
}
/** uncheck(() -> Class.forName("xxx")); */
public static <R, E extends Exception> R uncheck(Supplier_WithExceptions<R, E> supplier)
{
try { return supplier.get(); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
}
/** uncheck(Class::forName, "xxx"); */
public static <T, R, E extends Exception> R uncheck(Function_WithExceptions<T, R, E> function, T t) {
try { return function.apply(t); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
}
@SuppressWarnings ("unchecked")
private static <E extends Throwable> void throwAsUnchecked(Exception exception) throws E { throw (E)exception; }
}
Many other examples on how to use it (after statically importing UtilException
):
@Test
public void test_Consumer_with_checked_exceptions() throws IllegalAccessException {
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.forEach(rethrowConsumer(className -> System.out.println(Class.forName(className))));
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.forEach(rethrowConsumer(System.out::println));
}
@Test
public void test_Function_with_checked_exceptions() throws ClassNotFoundException {
List<Class> classes1
= Stream.of("Object", "Integer", "String")
.map(rethrowFunction(className -> Class.forName("java.lang." + className)))
.collect(Collectors.toList());
List<Class> classes2
= Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(rethrowFunction(Class::forName))
.collect(Collectors.toList());
}
@Test
public void test_Supplier_with_checked_exceptions() throws ClassNotFoundException {
Collector.of(
rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))),
StringJoiner::add, StringJoiner::merge, StringJoiner::toString);
}
@Test
public void test_uncheck_exception_thrown_by_method() {
Class clazz1 = uncheck(() -> Class.forName("java.lang.String"));
Class clazz2 = uncheck(Class::forName, "java.lang.String");
}
@Test (expected = ClassNotFoundException.class)
public void test_if_correct_exception_is_still_thrown_by_method() {
Class clazz3 = uncheck(Class::forName, "INVALID");
}
But don't use it before understanding the following advantages, disadvantages, and limitations:
• If the calling-code is to handle the checked exception you MUST add it to the throws clause of the method that contains the stream. The compiler will not force you to add it anymore, so it's easier to forget it.
• If the calling-code already handles the checked exception, the compiler WILL remind you to add the throws clause to the method declaration that contains the stream (if you don't it will say: Exception is never thrown in body of corresponding try statement).
• In any case, you won't be able to surround the stream itself to catch the checked exception INSIDE the method that contains the stream (if you try, the compiler will say: Exception is never thrown in body of corresponding try statement).
• If you are calling a method which literally can never throw the exception that it declares, then you should not include the throws clause. For example: new String(byteArr, "UTF-8") throws UnsupportedEncodingException, but UTF-8 is guaranteed by the Java spec to always be present. Here, the throws declaration is a nuisance and any solution to silence it with minimal boilerplate is welcome.
• If you hate checked exceptions and feel they should never be added to the Java language to begin with (a growing number of people think this way, and I am NOT one of them), then just don't add the checked exception to the throws clause of the method that contains the stream. The checked exception will, then, behave just like an UNchecked exception.
• If you are implementing a strict interface where you don't have the option for adding a throws declaration, and yet throwing an exception is entirely appropriate, then wrapping an exception just to gain the privilege of throwing it results in a stacktrace with spurious exceptions which contribute no information about what actually went wrong. A good example is Runnable.run(), which does not throw any checked exceptions. In this case, you may decide not to add the checked exception to the throws clause of the method that contains the stream.
• In any case, if you decide NOT to add (or forget to add) the checked exception to the throws clause of the method that contains the stream, be aware of these 2 consequences of throwing CHECKED exceptions:
1) The calling-code won't be able to catch it by name (if you try, the compiler will say: Exception is never thrown in body of corresponding try statement). It will bubble and probably be catched in the main program loop by some "catch Exception" or "catch Throwable", which may be what you want anyway.
2) It violates the principle of least surprise: it will no longer be enough to catch RuntimeException to be able to guarantee catching all possible exceptions. For this reason, I believe this should not be done in framework code, but only in business code that you completely control.
In conclusion: I believe the limitations here are not serious, and the UtilException
class may be used without fear. However, it's up to you!
The obvious question being "why do you want to read in the entire file?" This is obviously not a scalable solution if your files get very large. The scala.io.Source
gives you back an Iterator[String]
from the getLines
method, which is very useful and concise.
It's not much of a job to come up with an implicit conversion using the underlying java IO utilities to convert a File
, a Reader
or an InputStream
to a String
. I think that the lack of scalability means that they are correct not to add this to the standard API.
When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p
flag to mkdir
... Please update your Dockerfile with
RUN mkdir -p ...
I tested this and it's correct.
JSP is s presentation framework, and is generally not supposed to contain any program logic in it. As skaffman suggested, use pure servlets, or any MVC web framework in order to achieve what you want.
componentWillReceiveProps
is being deprecated because using it "often leads to bugs and inconsistencies".
If something changes from the outside, consider resetting the child component entirely with key
.
Providing a key
prop to the child component makes sure that whenever the value of key
changes from the outside, this component is re-rendered. E.g.,
<EmailInput
defaultEmail={this.props.user.email}
key={this.props.user.id}
/>
On its performance:
While this may sound slow, the performance difference is usually insignificant. Using a key can even be faster if the components have heavy logic that runs on updates since diffing gets bypassed for that subtree.
That's happening, because switch
statement is a statement
, but here javascript expects an expression.
Although, it's not recommended to use switch statement in a render
method, you can use self-invoking function to achieve this:
render() {
// Don't forget to return a value in a switch statement
return (
<div>
{(() => {
switch(...) {}
})()}
</div>
);
}
That's not how to add an item to a string. This:
newinv=inventory+str(add)
Means you're trying to concatenate a list and a string. To add an item to a list, use the list.append()
method.
inventory.append(add) #adds a new item to inventory
print(inventory) #prints the new inventory
Hope this helps!
You need to send customerKey and customerSecret to Zend_Service_Twitter
$twitter = new Zend_Service_Twitter(array(
'consumerKey' => $this->consumer_key,
'consumerSecret' => $this->consumer_secret,
'username' => $user->screenName,
'accessToken' => unserialize($user->token)
));
I was trying to find the meaning of GRANT USAGE on *.* TO
and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password
will be granted when you create the user with the following command (CREATE
):
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
When you grant privilege with GRANT
, new privilege s will be added on top of it.
Replace this:
StreamWriter file2 = new StreamWriter("c:/file.txt");
with this:
StreamWriter file2 = new StreamWriter("c:/file.txt", true);
true
indicates that it appends text.
em... Keep pressing Shift and then click the right mouse button
On my IntelliJ U on Mac I need to point with cursor on some method, variable etc. and press [cntrl] or [cmd] key. Then click on the link inside popup window which appeared to see JavaDocs
bash will not give you correct result of 3/2 since it doesn't do floating pt maths. you can use tools like awk
$ awk 'BEGIN { rounded = sprintf("%.0f", 3/2); print rounded }'
2
or bc
$ printf "%.0f" $(echo "scale=2;3/2" | bc)
2
EDIT: I was wrong, and you should see Marks answer above.
I cannot speak from experience with SQL Server, but for most databases the answer would be no. The only potential benefit that you get, performance wise, from using a view is that it could potentially create some access paths based on the query. But the main reason to use a view is to simplify a query or to standardize a way of accessing some data in a table. Generally speaking, you won't get a performance benefit. I may be wrong, though.
I would come up with a moderately more complicated example and time it yourself to see.
I don't know if it's a stupid answer, but resolved this problem by storing a flag in shared preferences every time I entered onCreate() of any activity, then I used the value from shered preferences to find out what it's the foreground activity.
REST is an style of software architecture for distributed software
Conforming to the REST constraints is referred to as being ‘RESTful’.
Very used today to build web services as an alternative to SOAP.
Here you have some links to check
http://en.wikipedia.org/wiki/Representational_State_Transfer
http://www.computerworld.com/s/article/297424/Representational_State_Transfer_REST_
http://www.ibm.com/developerworks/webservices/library/ws-restful/
An expansion and useful addition to egmackenzie's "arp -a" solution for Windows -
Windows Example searching for my iPhone on the WiFi network
(pre: iPhone WiFi disabled)
See below for example:
Here is a nice writeup on the use of 'arp -d' here if interested -
You can use the groupby command, if you already have some labels for your data.
out_list = [group[1] for group in in_series.groupby(label_series.values)]
Here's a detailed example:
Let's say we want to partition a pd series using some labels into a list of chunks
For example, in_series
is:
2019-07-01 08:00:00 -0.10
2019-07-01 08:02:00 1.16
2019-07-01 08:04:00 0.69
2019-07-01 08:06:00 -0.81
2019-07-01 08:08:00 -0.64
Length: 5, dtype: float64
And its corresponding label_series
is:
2019-07-01 08:00:00 1
2019-07-01 08:02:00 1
2019-07-01 08:04:00 2
2019-07-01 08:06:00 2
2019-07-01 08:08:00 2
Length: 5, dtype: float64
Run
out_list = [group[1] for group in in_series.groupby(label_series.values)]
which returns out_list
a list
of two pd.Series
:
[2019-07-01 08:00:00 -0.10
2019-07-01 08:02:00 1.16
Length: 2, dtype: float64,
2019-07-01 08:04:00 0.69
2019-07-01 08:06:00 -0.81
2019-07-01 08:08:00 -0.64
Length: 3, dtype: float64]
Note that you can use some parameters from in_series
itself to group the series, e.g., in_series.index.day
SQL> SELECT version FROM v$instance;
VERSION
-----------------
11.2.0.3.0
Ctrl + MouseWheel on active editor.
I'll look at my docs; there's a way of specifying a configuration to change the path of the root web application away from ROOT (or ROOT.war), but it seems to have changed between Tomcat 5 and 6.
Found this:
http://www.nabble.com/Re:-Tomcat-6-and-ROOT-application...-td20017401.html
So, it seems that changing the root path (in ROOT.xml) is possible, but a bit broken -- you need to move your WAR outside of the auto-deployment directory. Mind if I ask why just renaming your file to ROOT.war isn't a workable solution?
Have a look at java.io.File.list()
and FilenameFilter
.
Just collected all people's answers:(m new to git plz use it for reference only)
git log
-first check from which commit you want to rebase
git rebase -i HEAD~1
-Here i want to rebase on the second last commit- commit count starts from '1')
-this will open the command line editor (called vim editor i guess)
Then the screen will look something like this:
pick 0c2236d Added new line.
Rebase 2a1cd65..0c2236d onto 2a1cd65 (1 command)
#
Commands:
p, pick = use commit
r, reword = use commit, but edit the commit message
e, edit = use commit, but stop for amending
s, squash = use commit, but meld into previous commit
f, fixup = like "squash", but discard this commit's log message
x, exec = run command (the rest of the line) using shell
d, drop = remove commit
#
These lines can be re-ordered; they are executed from top to bottom.
#
If you remove a line here THAT COMMIT WILL BE LOST.
#
However, if you remove everything, the rebase will be aborted.
#
Note that empty commits are commented out ~ ~
~
~
~
~
~
~
~
~
~
Here change the first line as per your need (using the commands listed above i.e. 'drop' to remove commit etc.) Once done the editing press ':x' to save and exit editor(this is for vim editor only)
And then
git push
If its showing problem then you need to forcefully push the changes to remote(ITS VERY CRITICAL : dont force push if you are working in team)
git push -f origin
There is a known problem with Java and glibc >= 2.10 (includes Ubuntu >= 10.04, RHEL >= 6).
The cure is to set this env. variable:
export MALLOC_ARENA_MAX=4
If you are running Tomcat, you can add this to TOMCAT_HOME/bin/setenv.sh
file.
For Docker, add this to Dockerfile
ENV MALLOC_ARENA_MAX=4
There is an IBM article about setting MALLOC_ARENA_MAX https://www.ibm.com/developerworks/community/blogs/kevgrig/entry/linux_glibc_2_10_rhel_6_malloc_may_show_excessive_virtual_memory_usage?lang=en
resident memory has been known to creep in a manner similar to a memory leak or memory fragmentation.
There is also an open JDK bug JDK-8193521 "glibc wastes memory with default configuration"
search for MALLOC_ARENA_MAX on Google or SO for more references.
You might want to tune also other malloc options to optimize for low fragmentation of allocated memory:
# tune glibc memory allocation, optimize for low fragmentation
# limit the number of arenas
export MALLOC_ARENA_MAX=2
# disable dynamic mmap threshold, see M_MMAP_THRESHOLD in "man mallopt"
export MALLOC_MMAP_THRESHOLD_=131072
export MALLOC_TRIM_THRESHOLD_=131072
export MALLOC_TOP_PAD_=131072
export MALLOC_MMAP_MAX_=65536
i was looking information about how to do a POST request. I need to specify that mi request is a POST request because, i'm working with RESTful web services that only uses POST methods, and if the request isn't post, when i try to do the request i receive an HTTP error 405. I assure that my code isn't wrong doing the next: I create a method in my web service that is called through GET request and i point my application to consume that web service method and it works. My code is the next:
URL server = null;
URLConnection conexion = null;
BufferedReader reader = null;
server = new URL("http://localhost:8089/myApp/resources/webService");
conexion = server.openConnection();
reader = new BufferedReader(new InputStreamReader(server.openStream()));
System.out.println(reader.readLine());
Bash has built in features to access the last command executed. But that's the last whole command (e.g. the whole case
command), not individual simple commands like you originally requested.
!:0
= the name of command executed.
!:1
= the first parameter of the previous command
!:*
= all of the parameters of the previous command
!:-1
= the final parameter of the previous command
!!
= the previous command line
etc.
So, the simplest answer to the question is, in fact:
echo !!
...alternatively:
echo "Last command run was ["!:0"] with arguments ["!:*"]"
Try it yourself!
echo this is a test
echo !!
In a script, history expansion is turned off by default, you need to enable it with
set -o history -o histexpand
The best article I found about it is this one: https://trilon.io/blog/how-to-delete-all-nodemodules-recursively
All from the console and easy to execute from any folder point.
But as a summary of the article, this command to find the size for each node_module
folder found in different projects.
find . -name "node_modules" -type d -prune -print | xargs du -chs
And to actually remove them:
find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;
The article contains also instructions for windows shell.
I use this function htmlentities($string):
$msg = "<script>alert("hello")</script> <h1> Hello World </h1>" $msg = htmlentities($msg); echo $msg;
You can draw the image on the canvas and let the user draw on top of that.
The drawImage()
function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images
If maven is not creating Local Repository i.e .m2/repository folder then try below step.
In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close
I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.
If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany
annotation with the 'mappedBy
' property, it also means that the other side holding the @ManyToOne
annotation with the @JoinColumn
is the 'owner' of this bi-directional relationship.
Also, mappedBy
takes in the instance name (mCustomer
in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).
BONUS :
Also, look into the orphanRemoval
property of @OneToMany
annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.
simple example to selecting character from string and appending to string variable
private static String findaccountnum(String holdername, String mobile) {
char n1=holdername.charAt(0);
char n2=holdername.charAt(1);
char n3=holdername.charAt(2);
char n4=mobile.charAt(0);
char n5=mobile.charAt(1);
char n6=mobile.charAt(2);
String number=new StringBuilder().append(n1).append(n2).append(n3).append(n4).append(n5).append(n6).toString();
return number;
}
Your fundamental problem is that grep
works one line at a time - so it cannot find a SELECT statement spread across lines.
Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.
I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.
In outline, for a single file:
$/ = "\n\n"; # Paragraphs
while (<>)
{
if ($_ =~ m/SELECT.*customerName.*FROM/mi)
{
printf file name
go to next file
}
}
That needs to be wrapped into a sub that is then invoked by the methods of File::Find.
Just use Double.compare() method to compare double values.
Double.compare((d1,d2) == 0)
double d1 = 0.0;
double d2 = 0.0;
System.out.println(Double.compare((d1,d2) == 0)) // true
You have to tell your SQLCommand objects to use the transaction:
cmd1.Transaction = transaction;
or in the constructor:
SqlCommand cmd1 = new SqlCommand("select...", connectionsql, transaction);
Make sure to have the connectionsql object open, too.
But all you are doing are SELECT statements. Transactions would benefit more when you use INSERT, UPDATE, etc type actions.
collection.find().sort('date':1).exec(function(err, doc) {});
this worked for me
referred https://docs.mongodb.org/getting-started/node/query/
The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values
the output is an numpy array
. So if the data has int
and float
in it then output will either have int
or float
and the columns will loose their original dtype.
Consider df
a b
0 1 4
1 2 5
2 3 6
a float64
b int64
So if you want to keep original dtype, you can do something like
row_list = df.to_csv(None, header=False, index=False).split('\n')
this will return each row as a string.
['1.0,4', '2.0,5', '3.0,6', '']
Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.
def f(row_str):
row_list = row_str.split(',')
return [float(row_list[0]), int(row_list[1])]
df_list_of_list = map(f, row_list[:-1])
[[1.0, 4], [2.0, 5], [3.0, 6]]
you should try this
g++-4.4 -std=c++0x or g++-4.7 -std=c++0x
I guess you already have the process object of the running process (e.g. by GetProcessesByName()). You can then get the executable file name by using
Process p;
string filename = p.MainModule.FileName;
You should really make a difference between:
There are many scenarios where those 2 values are mismatching such as:
In most cases you would want to use the interface orientation and you can get it via the window:
private var windowInterfaceOrientation: UIInterfaceOrientation? {
return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
}
In case you also want to support < iOS 13 (such as iOS 12) you would do the following:
private var windowInterfaceOrientation: UIInterfaceOrientation? {
if #available(iOS 13.0, *) {
return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
} else {
return UIApplication.shared.statusBarOrientation
}
}
Now you need to define where to react to the window interface orientation change. There are multiple ways to do that but the optimal solution is to do it within
willTransition(to newCollection: UITraitCollection
.
This inherited UIViewController method which can be overridden will be trigger every time the interface orientation will be change. Consequently you can do all your modifications in the latter.
Here is a solution example:
class ViewController: UIViewController {
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
guard let windowInterfaceOrientation = self.windowInterfaceOrientation else { return }
if windowInterfaceOrientation.isLandscape {
// activate landscape changes
} else {
// activate portrait changes
}
})
}
private var windowInterfaceOrientation: UIInterfaceOrientation? {
return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
}
}
By implementing this method you'll then be able to react to any change of orientation to your interface. But keep in mind that it won't be triggered at the opening of the app so you will also have to manually update your interface in viewWillAppear()
.
I've created a sample project which underlines the difference between device orientation and interface orientation. Additionally it will help you to understand the different behavior depending on which lifecycle step you decide to update your UI.
Feel free to clone and run the following repository: https://github.com/wjosset/ReactToOrientation
Try obuildfactory.
There is need to modify these scripts (contains error and don't exactly do the "thing" required), i will upload mine scripts forked from obuildfactory in next few days. and so i will also update my answer accordingly.
Until then enjoy, sir :)
You can't set a number in an arbitrary place in the array without telling the array how big it needs to be. For your example: int[] array = new int[4];
Case: using SO Windows, try:
set ANDROID_HOME=C:\\android-sdk-windows
set PATH=%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools
more in: http://spring.io/guides/gs/android/
Case: you don't have platform-tools:
cordova platforms list
cordova platforms add <Your_platform, example: Android>
Below is worked for me on macos mojave 10.14.6 version
I installed current jdk(https://www.oracle.com/java/technologies/javase-downloads.html)
Then do respectively;
it is done. And you can check the version with java -version command.
Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.
In order to match PyQt5's behavior, you have to create the started signal yourself.
Here is an easy solution:
# Use this class instead of QThread
class QThread2(QThread):
# Use this signal instead of "started"
started2 = Signal()
def __init__(self):
QThread.__init__(self)
self.started.connect(self.onStarted)
def onStarted(self):
self.started2.emit()
Actually ngAfterViewInit()
will initiate only once when the component initiate.
If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()
see tag input example :
<div class="input-group date" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input form-control-sm" data-target="#dt_expdate" id="dt_expdate" />
<div class="input-group-append" data-target="#dt_expdate" data-toggle="datetimepicker">
<div class="input-group-text form-control-sm"><i class="fa fa-calendar"></i></div>
</div>
</div>
acess to get & assign value from
id="dt_expdate"
get value:
var date= $("#dt_expdate").val();
assign value:
$("#dt_expdate").val('20/08/2020');
The error "client denied by server configuration" generally means that somewhere in your configuration are Allow from
and Deny from
directives that are preventing access. Read the mod_authz_host documentation for more details.
You should be able to solve this in your VirtualHost by adding something like:
<Location />
Allow from all
Order Deny,Allow
</Location>
Or alternatively with a Directory
directive:
<Directory "D:/Devel/matysart/matysart_dev1">
Allow from all
Order Deny,Allow
</Directory>
Some investigation of your Apache configuration files will probably turn up default restrictions on the default DocumentRoot.
Normally you need to have the same number of columns when you're using set based operators so Kangkan's answer is correct.
SAS SQL has specific operator to handle that scenario:
SAS(R) 9.3 SQL Procedure User's Guide
CORRESPONDING (CORR) Keyword
The CORRESPONDING keyword is used only when a set operator is specified. CORR causes PROC SQL to match the columns in table expressions by name and not by ordinal position. Columns that do not match by name are excluded from the result table, except for the OUTER UNION operator.
SELECT * FROM tabA
OUTER UNION CORR
SELECT * FROM tabB;
For:
+---+---+
| a | b |
+---+---+
| 1 | X |
| 2 | Y |
+---+---+
OUTER UNION CORR
+---+---+
| b | d |
+---+---+
| U | 1 |
+---+---+
<=>
+----+----+---+
| a | b | d |
+----+----+---+
| 1 | X | |
| 2 | Y | |
| | U | 1 |
+----+----+---+
U-SQL supports similar concept:
OUTER
requires the BY NAME clause and the ON list. As opposed to the other set expressions, the output schema of the OUTER UNION includes both the matching columns and the non-matching columns from both sides. This creates a situation where each row coming from one of the sides has "missing columns" that are present only on the other side. For such columns, default values are supplied for the "missing cells". The default values are null for nullable types and the .Net default value for the non-nullable types (e.g., 0 for int).
BY NAME
is required when used with OUTER. The clause indicates that the union is matching up values not based on position but by name of the columns. If the BY NAME clause is not specified, the matching is done positionally.
If the ON clause includes the “*” symbol (it may be specified as the last or the only member of the list), then extra name matches beyond those in the ON clause are allowed, and the result’s columns include all matching columns in the order they are present in the left argument.
And code:
@result =
SELECT * FROM @left
OUTER UNION BY NAME ON (*)
SELECT * FROM @right;
EDIT:
The concept of outer union is supported by KQL:
kind:
inner - The result has the subset of columns that are common to all of the input tables.
outer - The result has all the columns that occur in any of the inputs. Cells that were not defined by an input row are set to null.
Example:
let t1 = datatable(col1:long, col2:string)
[1, "a",
2, "b",
3, "c"];
let t2 = datatable(col3:long)
[1,3];
t1 | union kind=outer t2;
Output:
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| 1 | a | |
| 2 | b | |
| 3 | c | |
| | | 1 |
| | | 3 |
+------+------+------+
Could anyone help explain why
In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.
The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.
or give a solution for the code on windows? Thanks so much!
Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in the most sensible choice would probably be np.int64
You can perform this task using window.location.reload();
. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation
JavaScript window.location
object can be used
window
: in JavaScript represents an open window in a browser.
location
: in JavaScript holds information about current URL.
The location
object is like a fragment of the window
object and is called up through the window.location
property.
location
object has three methods:
assign()
: used to load a new documentreload()
: used to reload current documentreplace()
: used to replace current document with a new oneSo here we need to use reload()
, because it can help us in reloading the same document.
So use it like window.location.reload();
.
To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true
parameter to location.reload()
. This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.
It works like this:
h4 {
display:inline;
}
h4:after {
content:"\a";
white-space: pre;
}
Example: http://jsfiddle.net/Bb2d7/
The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)
My conclusion is that(Tested on 12c):
thus :
SELECT {T / t} FROM (SELECT 1 AS T FROM DUAL); -- Correct
SELECT "tEST" FROM (SELECT 1 AS "tEST" FROM DUAL); -- Correct
SELECT {"TEST" / tEST} FROM (SELECT 1 AS "tEST" FROM DUAL ); -- Incorrect
SELECT test_value AS "doggy" FROM test ORDER BY "doggy"; --Correct
SELECT test_value AS "doggy" FROM test WHERE "doggy" IS NOT NULL; --You can not do this, column alias not supported in WHERE & HAVING
SELECT * FROM test "doggy" WHERE "doggy".test_value IS NOT NULL; -- Do not use AS preceding table alias
So, the reason why USING AS AND "" causes problem is NOT AS
Note: "" double quotes are required if alias contains space OR if it contains lower-case characters and MUST show-up in Result set as lower-case chars. In all other scenarios its OPTIONAL and can be ignored.
The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever
). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever
.
Hide #categories
initially
#categories {
display: none;
}
and then, using JQuery UI, animate the Menu
slowly
var duration = 'slow';
$('#cat_icon').click(function () {
$('#cat_icon').hide(duration, function() {
$('#categories').show('slide', {direction: 'left'}, duration);});
});
$('.panel_title').click(function () {
$('#categories').hide('slide', {direction: 'left'}, duration, function() {
$('#cat_icon').show(duration);});
});
You can use any time in milliseconds as well
var duration = 2000;
If you want to hide on class='panel_item'
too, select both panel_title
and panel_item
$('.panel_title,.panel_item').click(function () {
$('#categories').hide('slide', {direction: 'left'}, duration, function() {
$('#cat_icon').show(duration);});
});
If you add to RelativeLayout, don't forget to set imageView's position. For instance:
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(200, 200);
lp.addRule(RelativeLayout.CENTER_IN_PARENT); // A position in layout.
ImageView imageView = new ImageView(this); // initialize ImageView
imageView.setLayoutParams(lp);
// imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(R.drawable.photo);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
layout.addView(imageView);
/var/lib/tomcat7/webapps/
find / -name 'tomcat_version' -type d
I know this is fairly old but I figured this was as good as any to put this. I found a post from yahoo with a good explanation:
Let's say you have two numbers, 40 and 30.
30/40*100 = 75.
So 30 is 75% of 40.
40/30*100 = 133.
So 40 is 133% of 30.
The percentage increase from 30 to 40 is:
(40-30)/30 * 100 = 33%
The percentage decrease from 40 to 30 is:
(40-30)/40 * 100 = 25%.
These calculations hold true whatever your two numbers.
Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:
$ date
If the date and/or time is incorrect, try to update using:
$ sudo ntpdate -u time.nist.gov
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseThrow(NullPointerException::new);
// .orElseThrow(CustomException::new);
If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:
npm install iconv
npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.
fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.
Here is All step with image. please follow it properly and i am sure you will not get any error.
From How to install CocoaPods and setup with your Xcode project.
First of all check you have to install command line
or not.
You can check this by opening Xcode, navigating the menu to
Xcode > Preferences > Downloads > Components, finding Command Line Tools and select install/update.
if you haven't find command line tool
then you need to write this command in terminal.
xcode-select --install
and click on install
if you have install command line tool. you need to select your Xcode directory (Sometimes this type of problems created due to different versions of Xcode available) follow this procedure.
Open terminal and run this command:
sudo gem install cocoapods
Enter admin password. This could take a while. After few minutes it will show green message is cocoa pods installed successfully in your mac machine.
If you are getting any error with Xcode 6 like developer path is missing. First run this command in terminal:
sudo xcode-select -switch /Applications/Xcode6.app (or your XCodeName.app)
Now you can setup Pod with your Xcode project.
and now you have to install pod. follow this procedure.
Open Terminal
Change directory to your Xcode project root directory (where your ProjectName.xcodeproj file is placed).
$ pod setup
: (Setting up CocoaPods master repo)If successful, it shows : Setup completed (read-only access). So, you setup everything. Now Lets do something which is more visible…Yes ! Lets install libraries in your Xcode project.
now you have to setup and update library related to pod in your project.
Steps to add-remove-update libraries in pod:
Open Terminal
Change directory to your Xcode project root directory. If your terminal is already running then no need to do this, as you are already at same path.
$ touch pod file
$ open -e podfile
(This should open a blank text file)Add your library names in that text file. You can add new names (lib name), remove any name or change the version e.g :
pod ’Facebook-iOS-SDK’ pod ’EGOTableViewPullRefresh’ pod ’JSONKit’ pod ‘MBProgressHUD
NOTE: Use ( control + ” ) button to add single quote at both end of library name. It should be shown as straight vertical line. Without control button it shall be added as curly single quote which will give error while installation of file.
Save and close this text file. Now libraries are setup and you have to install/update it
Go to your terminal again and run this command:
$ pod install
(to install/update these libraries in pod).You should see output similar to the following:
Updating spec repo `master’ Installing Facebook-iOS-SDK Generating support files
Setup completed.
Note:-
If you have followed this whole procedure correctly and step by step , then you can directly fire pod update
command after selecting Xcode
and then select your project path. and write your command pod update
EDIT :-
you can also check command line tool here.
In code level also, you could add your lib to the project using the compiler directives #pragma.
example:
#pragma comment( lib, "yourLibrary.lib" )
im using following module:
#!/usr/bin/python
# module for getting the lan ip address of the computer
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', bytes(ifname[:15], 'utf-8'))
# Python 2.7: remove the second argument for the bytes call
)[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break;
except IOError:
pass
return ip
Tested with windows and linux (and doesnt require additional modules for those) intended for use on systems which are in a single IPv4 based LAN.
The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by Alexander. In such cases, you need to manually replace the list with the interface names on your system, or use another solution like netifaces.
Write the following method using Java:
protected boolean isElementPresent(By by){
try{
driver.findElement(by);
return true;
}
catch(NoSuchElementException e){
return false;
}
}
Call the above method during assertion.
To complement ruslik's answer, in C++14 you can use this construction:
delete std::exchange(heapObject, nullptr);
Here is my solution:
public String HMAC_SHA256(String secret, String message)
{
String hash="";
try{
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
hash = Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), Base64.DEFAULT);
}catch (Exception e)
{
}
return hash.trim();
}
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
From the documentation:
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, soa.insert(0, x)
inserts at the front of the list, anda.insert(len(a),x)
is equivalent toa.append(x)
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
The checked answer does work but officially in MongooseJS latest, you should use pull.
doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed
https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull
I was just looking that up too.
See Daniel's answer for the correct answer. Much better.
In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.
So register the ChildComponent in Shared Module manually.
You can use the managed .Net cryptography library, then save the encrypted string into the database. When you want to verify the password you can compare the stored database string with the hashed value of the user input. See here for more info about SHA512Managed
using System.Security.Cryptography;
public static string EncryptSHA512Managed(string password)
{
UnicodeEncoding uEncode = new UnicodeEncoding();
byte[] bytPassword = uEncode.GetBytes(password);
SHA512Managed sha = new SHA512Managed();
byte[] hash = sha.ComputeHash(bytPassword);
return Convert.ToBase64String(hash);
}
I would recommend OAuth 2/3. You can find more information at http://oauth.net/2/
Use this link to convert your JSON into POJO with select options as selected in image below
You will get a POJO class for your response like this
public class Result {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("Username")
@Expose
private String username;
@SerializedName("Level")
@Expose
private String level;
/**
*
* @return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return
* The username
*/
public String getUsername() {
return username;
}
/**
*
* @param username
* The Username
*/
public void setUsername(String username) {
this.username = username;
}
/**
*
* @return
* The level
*/
public String getLevel() {
return level;
}
/**
*
* @param level
* The Level
*/
public void setLevel(String level) {
this.level = level;
}
}
and use interface like this:
@FormUrlEncoded
@POST("/api/level")
Call<Result> checkLevel(@Field("id") int id);
and call like this:
Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
if(response.isSuccessful()){
response.body(); // have your all data
int id =response.body().getId();
String userName = response.body().getUsername();
String level = response.body().getLevel();
}else Toast.makeText(context,response.errorBody().string(),Toast.LENGTH_SHORT).show(); // this will tell you why your api doesnt work most of time
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(context,t.toString(),Toast.LENGTH_SHORT).show(); // ALL NETWORK ERROR HERE
}
});
and use dependencies in Gradle
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'
NOTE: The error occurs because you changed your JSON into POJO (by use of addConverterFactory(GsonConverterFactory.create())
in retrofit). If you want response in JSON then remove the addConverterFactory(GsonConverterFactory.create())
from Retrofit. If not then use the above solution
You can use the built-in ast.literal_eval
:
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
This is safer than using eval
. As its own docs say:
>>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
For example:
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
An Enumerator
shows you the items in a list or collection.
Each instance of an Enumerator is at a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current
) or move to the next one (IEnumerator.MoveNext
). When you write a foreach
loop in C#, the compiler generates code that uses an Enumerator.
An Enumerable
is a class that can give you Enumerator
s. It has a method called GetEnumerator
which gives you an Enumerator
that looks at its items. When you write a foreach
loop in C#, the code that it generates calls GetEnumerator
to create the Enumerator
used by the loop.
I know this is old but neither an <svg>
group tag nor a <g>
fixed the issue I was facing. I needed to adjust the y position of a tag which also had animation on it.
The solution was to use both the and tag together:
<svg y="1190" x="235">
<g class="light-1">
<path />
</g>
</svg>
If you don't want to re-encode your video AND your player can handle rotation metadata you can just change the rotation in the metadata using ffmpeg:
ffmpeg -i input.m4v -map_metadata 0 -metadata:s:v rotate="90" -codec copy output.m4v
^[a-zA-Z]
means any a-z or A-Z at the start of a line
[^a-zA-Z]
means any character that IS NOT a-z OR A-Z
You can also write a hint in an anchor like this:
<a href="javascript:void('open popup image')" onclick="return f()">...</a>
so the user will know what this link does.
Alec's answer is great, but it doesn't work in the case where there are multiple levels of nesting. Here's a modified version that supports multiple levels of nesting. It also makes the header names a bit nicer if the nested object already specifies its own key (e.g. Firebase Analytics / BigTable / BigQuery data):
"""Converts JSON with nested fields into a flattened CSV file.
"""
import sys
import json
import csv
import os
import jsonlines
from orderedset import OrderedSet
# from https://stackoverflow.com/a/28246154/473201
def flattenjson( b, prefix='', delim='/', val=None ):
if val is None:
val = {}
if isinstance( b, dict ):
for j in b.keys():
flattenjson(b[j], prefix + delim + j, delim, val)
elif isinstance( b, list ):
get = b
for j in range(len(get)):
key = str(j)
# If the nested data contains its own key, use that as the header instead.
if isinstance( get[j], dict ):
if 'key' in get[j]:
key = get[j]['key']
flattenjson(get[j], prefix + delim + key, delim, val)
else:
val[prefix] = b
return val
def main(argv):
if len(argv) < 2:
raise Error('Please specify a JSON file to parse')
print "Loading and Flattening..."
filename = argv[1]
allRows = []
fieldnames = OrderedSet()
with jsonlines.open(filename) as reader:
for obj in reader:
# print 'orig:\n'
# print obj
flattened = flattenjson(obj)
#print 'keys: %s' % flattened.keys()
# print 'flattened:\n'
# print flattened
fieldnames.update(flattened.keys())
allRows.append(flattened)
print "Exporting to CSV..."
outfilename = filename + '.csv'
count = 0
with open(outfilename, 'w') as file:
csvwriter = csv.DictWriter(file, fieldnames=fieldnames)
csvwriter.writeheader()
for obj in allRows:
# print 'allRows:\n'
# print obj
csvwriter.writerow(obj)
count += 1
print "Wrote %d rows" % count
if __name__ == '__main__':
main(sys.argv)
numpy.where() is my favorite.
>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])
It's true that true
and false
don't represent any numerical values in Javascript.
In some languages (e.g. C, VB), the boolean values are defined as actual numerical values, so they are just different names for 1 and 0 (or -1 and 0).
In some other languages (e.g. Pascal, C#), there is a distinct boolean type that is not numerical. It's possible to convert between boolean values and numerical values, but it doesn't happen automatically.
Javascript falls in the category that has a distinct boolean type, but on the other hand Javascript is quite keen to convert values between different data types.
For example, eventhough a number is not a boolean, you can use a numeric value where a boolean value is expected. Using if (1) {...}
works just as well as if (true) {...}
.
When comparing values, like in your example, there is a difference between the ==
operator and the ===
operator. The ==
equality operator happily converts between types to find a match, so 1 == true
evaluates to true because true
is converted to 1
. The ===
type equality operator doesn't do type conversions, so 1 === true
evaluates to false because the values are of different types.
I could not change the code, so I needed command line for testing purpose and figured this could help someone:
Application specific caches are stored in ~/Library/Caches/<bundle-identifier-of-your-app>
, so simply remove as below and re-open your application
rm -rf ~/Library/Caches/com.mycompany.appname/
I've taken @meouw's answer, added in the clientLeft that allows for the border, and then created three versions:
getAbsoluteOffsetFromBody - similar to @meouw's, this gets the absolute position relative to the body or html element of the document (depending on quirks mode)
getAbsoluteOffsetFromGivenElement - returns the absolute position relative to the given element (relativeEl). Note that the given element must contain the element el, or this will behave the same as getAbsoluteOffsetFromBody. This is useful if you have two elements contained within another (known) element (optionally several nodes up the node tree) and want to make them the same position.
getAbsoluteOffsetFromRelative - returns the absolute position relative to the first parent element with position: relative. This is similar to getAbsoluteOffsetFromGivenElement, for the same reason but will only go as far as the first matching element.
getAbsoluteOffsetFromBody = function( el )
{ // finds the offset of el from the body or html element
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
getAbsoluteOffsetFromGivenElement = function( el, relativeEl )
{ // finds the offset of el from relativeEl
var _x = 0;
var _y = 0;
while( el && el != relativeEl && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
getAbsoluteOffsetFromRelative = function( el )
{ // finds the offset of el from the first parent with position: relative
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
if (el != null)
{
if (getComputedStyle !== 'undefined')
valString = getComputedStyle(el, null).getPropertyValue('position');
else
valString = el.currentStyle['position'];
if (valString === "relative")
el = null;
}
}
return { top: _y, left: _x };
}
If you are still having problems, particularly relating to scrolling, you could try looking at http://www.greywyvern.com/?post=331 - I noticed at least one piece of questionable code in getStyle which should be fine assuming browsers behave, but haven't tested the rest at all.
The SHA1 hash of the commit is the equivalent to a Subversion revision number.
That's exactly what cursor: pointer;
is supposed to do.
If you want the cursor to remain normal, you should be using cursor: default
Whitespace is used to denote blocks. In other languages curly brackets ({
and }
) are common. When you indent, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it.
im_a_parent:
im_a_child:
im_a_grandchild
im_another_child:
im_another_grand_child
Off the top of my head, def
, if
, elif
, else
, try
, except
, finally
, with
, for
, while
, and class
all start blocks. To end a block, you simple outdent, and you will have siblings. In the above im_a_child
and im_another_child
are siblings.
If you want to remove all instances of 4 without needing to know the index:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();
Non-LINQ: (.NET Framework 2.0)
static bool isNotFour(int n)
{
return n != 4;
}
int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour).ToArray();
If you want to remove just the first instance:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
Non-LINQ: (.NET Framework 2.0)
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();
Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.
UPDATE now you can do: npm install git://github.com/foo/bar.git
or in package.json
:
"dependencies": {
"bar": "git://github.com/foo/bar.git"
}
I think i have the best answer for you, your git apps read your id_rsa.pub in root user directory
/home/root/.ssh/id_rsa.pub
That's why your key in /home/your_username/.ssh/id_rsa.pub can't be read by git. So you need to create the key in /home/root/.ssh/
$ sudo su
$ ssh-keygen
$ cd ~/.ssh
$ cat id_rsa.pub
Then copy the key in your github account. It's worked for me. You can try it.
For pre API 8 i solved the problem using a boolean flag, a dismiss listener and calling dialog.show again if in case the content of the editText wasn´t correct. Like this:
case ADD_CLIENT:
LayoutInflater factoryClient = LayoutInflater.from(this);
final View EntryViewClient = factoryClient.inflate(
R.layout.alert_dialog_add_client, null);
EditText ClientText = (EditText) EntryViewClient
.findViewById(R.id.client_edit);
AlertDialog.Builder builderClient = new AlertDialog.Builder(this);
builderClient
.setTitle(R.string.alert_dialog_client)
.setCancelable(false)
.setView(EntryViewClient)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
EditText newClient = (EditText) EntryViewClient
.findViewById(R.id.client_edit);
String newClientString = newClient
.getText().toString();
if (checkForEmptyFields(newClientString)) {
//If field is empty show toast and set error flag to true;
Toast.makeText(getApplicationContext(),
"Fields cant be empty",
Toast.LENGTH_SHORT).show();
add_client_error = true;
} else {
//Here save the info and set the error flag to false
add_client_error = false;
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
add_client_error = false;
dialog.cancel();
}
});
final AlertDialog alertClient = builderClient.create();
alertClient.show();
alertClient
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
//If the error flag was set to true then show the dialog again
if (add_client_error == true) {
alertClient.show();
} else {
return;
}
}
});
return true;
Quote from this post (it's written by the author of doxygen himself) :
run doxygen -g and change the following options of the generated Doxyfile:
EXTRACT_ALL = YES
HAVE_DOT = YES
UML_LOOK = YES
run doxygen again
put fonts in asset folder then apply fontfamily:''your fonts
json.loads
will load a json string into a python dict
, json.dumps
will dump a python dict
to a json string, for example:
>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': None}
>>> json_dump = json.dumps(value)
'{"favorited": false, "contributors": null}'
So that line is incorrect since you are trying to load
a python dict
, and json.loads
is expecting a valid json string
which should have <type 'str'>
.
So if you are trying to load the json, you should change what you are loading to look like the json_string
above, or you should be dumping it. This is just my best guess from the given information. What is it that you are trying to accomplish?
Also you don't need to specify the u
before your strings, as @Cld mentioned in the comments.
for me work this:
<input type="text"required id="autocomplete">_x000D_
_x000D_
<script>_x000D_
function initAutocomplete() {_x000D_
new google.maps.places.Autocomplete(_x000D_
(document.getElementById('autocomplete')),_x000D_
{types: ['geocode']}_x000D_
);_x000D_
}_x000D_
</script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"_x000D_
async defer></script>
_x000D_
This is one of the way to add google site search to websites:
<form action="https://www.google.com/search" class="searchform" method="get" name="searchform" target="_blank">_x000D_
<input name="sitesearch" type="hidden" value="example.com">_x000D_
<input autocomplete="on" class="form-control search" name="q" placeholder="Search in example.com" required="required" type="text">_x000D_
<button class="button" type="submit">Search</button>_x000D_
</form>
_x000D_
You can use // instead of single /. That converts to int
directly.
In Android 4
Go to Setting->Location services->
Uncheck Google`s location service.
Check GPS satelites.
For test you can use GPS Test.Please test Outdoor!
Offline maps are available on new version of Google map.
if you what to obtain "ONE" by giving in 100 then
initialize hash map by
hashmap = new HashMap<Object,String>();
haspmap.put(100,"one");
and retrieve value by
hashMap.get(100)
hope that helps.
i = 0x12345678
s = struct.pack('<I',i)
b = struct.unpack('BBBB',s)
To understand why, you need to know that the CPU represents signed numbers using the two's complement (maybe not all, but many).
byte n = 1; //0000 0001 = 1
n = ~n + 1; //1111 1110 + 0000 0001 = 1111 1111 = -1
And also, that the type int and unsigned int can be of different sized depending on your CPU. When doing specific stuff like this:
#include <stdint.h>
int8_t ibyte;
uint8_t ubyte;
int16_t iword;
//......
To get this to work with jupyter (version 4.0.6) I created ~/.jupyter/custom/custom.css
containing:
/* Make the notebook cells take almost all available width */
.container {
width: 99% !important;
}
/* Prevent the edit cell highlight box from getting clipped;
* important so that it also works when cell is in edit mode*/
div.cell.selected {
border-left-width: 1px !important;
}
Cleaned up @Wazime solution a little. Works great as a general solution.
$(document).on('shown.bs.dropdown', '.table-responsive', function (e) {
// The .dropdown container
var $container = $(e.target);
// Find the actual .dropdown-menu
var $dropdown = $container.find('.dropdown-menu');
if ($dropdown.length) {
// Save a reference to it, so we can find it after we've attached it to the body
$container.data('dropdown-menu', $dropdown);
} else {
$dropdown = $container.data('dropdown-menu');
}
$dropdown.css('top', ($container.offset().top + $container.outerHeight()) + 'px');
$dropdown.css('left', $container.offset().left + 'px');
$dropdown.css('position', 'absolute');
$dropdown.css('display', 'block');
$dropdown.appendTo('body');
});
$(document).on('hide.bs.dropdown', '.table-responsive', function (e) {
// Hide the dropdown menu bound to this button
$(e.target).data('dropdown-menu').css('display', 'none');
});
Every answer above is correct and I would like to add also a snapshot from my working codes.
recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//some code when initially scrollState changes
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//Some code while the list is scrolling
LinearLayoutManager lManager = (LinearLayoutManager) recycler.getLayoutManager();
int firstElementPosition = lManager.findFirstVisibleItemPosition();
}
});
Activate the virtualenv environment by issuing one of the following commands:
$ source ~/tensorflow/bin/activate # bash, sh, ksh, or zsh
$ source ~/tensorflow/bin/activate.csh # csh or tcsh
Hope this help
<html>
<head>
<style type="text/css">
#mydiv {
position:absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width:100px;
height:200px;
margin:auto;
border: 1px solid #ccc;
background-color: #f3f3f3;
}
</style>
</head>
<body>
<div id="mydiv">Maitrey</div>
</body>
</html>
Use the 'And' keyword for a logical and. Like this:
If Not ((filename = testFileName) And (fileName <> "")) Then
Previously, the question asked how to check whether there are files in a directory. The following code achieves that, but see rsp's answer for a better solution.
Commands don’t return values – they output them. You can capture this output by using command substitution; e.g. $(ls -A)
. You can test for a non-empty string in Bash like this:
if [[ $(ls -A) ]]; then
echo "there are files"
else
echo "no files found"
fi
Note that I've used -A
rather than -a
, since it omits the symbolic current (.
) and parent (..
) directory entries.
Note: As pointed out in the comments, command substitution doesn't capture trailing newlines. Therefore, if the command outputs only newlines, the substitution will capture nothing and the test will return false. While very unlikely, this is possible in the above example, since a single newline is a valid filename! More information in this answer.
If you want to check that the command completed successfully, you can inspect $?
, which contains the exit code of the last command (zero for success, non-zero for failure). For example:
files=$(ls -A)
if [[ $? != 0 ]]; then
echo "Command failed."
elif [[ $files ]]; then
echo "Files found."
else
echo "No files found."
fi
More info here.
No. There is no way you can edit the result grid. The result grid is mainly for displaying purposes of the query you executed.
This for the reason that anybody can execute complex queries. Hopefully for the next release they will include this kind of functionality.
I Hope that answer your question.
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
This is the simplest method. Only one step.
It has significant impact on speed. In my case, time taken for a training step almost halved.
Depends on which "cloud" you would want to use. If it is Google App Engine, you can use Java or Python. Groovy too is supported on Google App Engine which runs on jvm. If you are going with Amazon, you can pretty much install any OS (Amazon Machine Images) you would like with any application server and use any language depending on the application servers support for the language. But doing something like that would mean a lot of technical understanding of scalability concepts. Some of the services might be provided off the shelf like DB services, storage etc. I heard about ruby and Heroku (another cloud application platform). But dont have experience with it.
Personally I prefer Java/Groovy for such things because of the vast libraries and tools available.
Had a similar problem. My solution was to give the inner table a fixed height of 1px and set the height of the td in the inner table to 100%. Against all odds, it works fine, tested in IE, Chrome and FF!
var fs = require('fs');
var path = (process.cwd()+"\\text.txt");
fs.readFile(path , function(err,data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
Your pip
is a soft link to the same executable file path with pip3
.
you can use the commands below to check where your pip
and pip3
real paths are:
$ ls -l `which pip`
$ ls -l `which pip3`
You may also use the commands below to know more details:
$ pip show pip
$ pip3 show pip
When we install different versions of python, we may create such soft links to
It is the same situation with python
, python2
, python3
More information below if you're interested in how it happens in different cases:
There might be a semicolon or bracket missing a line before your pasted line.
It seems fine to me; every string is allowed as an array index.
I had used following which worked correctly.
$('#fileAttached').attr('value', $('#attachment').val())
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
As Phil noted, the empty string is treated as a NULL, and NULL is not equal or unequal to anything. If you expect empty strings or NULLs, you'll need to handle those with NVL()
:
DECLARE
str1 varchar2(4000);
str2 varchar2(4000);
BEGIN
str1:='';
str2:='sdd';
-- Provide an alternate null value that does not exist in your data:
IF(NVL(str1,'X') != NVL(str2,'Y')) THEN
dbms_output.put_line('The two strings are not equal');
END IF;
END;
/
Concerning null comparisons:
According to the Oracle 12c documentation on NULLS, null comparisons using IS NULL
or IS NOT NULL
do evaluate to TRUE
or FALSE
. However, all other comparisons evaluate to UNKNOWN
, not FALSE
. The documentation further states:
A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN.
A reference table is provided by Oracle:
Condition Value of A Evaluation
----------------------------------------
a IS NULL 10 FALSE
a IS NOT NULL 10 TRUE
a IS NULL NULL TRUE
a IS NOT NULL NULL FALSE
a = NULL 10 UNKNOWN
a != NULL 10 UNKNOWN
a = NULL NULL UNKNOWN
a != NULL NULL UNKNOWN
a = 10 NULL UNKNOWN
a != 10 NULL UNKNOWN
I also learned that we should not write PL/SQL assuming empty strings will always evaluate as NULL:
Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.
Remove a determinated string from start and end from a string.
s = '""Hello World""'
s.strip('""')
> 'Hello World'
Please try this code:
sorted(glob.glob( os.path.join(path, '*.png') ),key=lambda x:float(re.findall("([0-9]+?)\.png",x)[0]))
The {{variable}}
is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.
Having said that, you can put this kind of substitution into your JavaScript.
<script type="text/javascript">
var a = "{{someDjangoVariable}}";
</script>
This gives you "dynamic" javascript.
There is a jQuery plugin for the general case of scrolling to a DOM element, but if performance is an issue (and when is it not?), I would suggest doing it manually. This involves two steps:
quirksmode gives a good explanation of the mechanism behind the former. Here's my preferred solution:
function absoluteOffset(elem) {
return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);
}
It uses casting from null to 0, which isn't proper etiquette in some circles, but I like it :) The second part uses window.scroll
. So the rest of the solution is:
function scrollToElement(elem) {
window.scroll(absoluteOffset(elem));
}
Voila!
This works for me:
// Document click blurer
$(document).on('mousedown', '*:not(input,textarea)', function() {
try {
var $a = $(document.activeElement).prop("disabled", true);
setTimeout(function() {
$a.prop("disabled", false);
});
} catch (ex) {}
});