$("video").prop('muted', true); //mute
AND
$("video").prop('muted', false); //unmute
See all events here
(side note: use attr
if in jQuery < 1.6)
The shortest PHP solution
function solution($A) {
// write your code in PHP7.0
$lastNum = 1;
while(in_array($lastNum, $A)) {
$lastNum++;
}
return $lastNum;
}
sys.path
might include items that aren't specifically in your PYTHONPATH
environment variable. To query the variable directly, use:
import os
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
Just use break, like that:
int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
if(cont==50) { //if listViewItem reach 50 break out.
break;
}
cont++; //increment cont.
}
V-Play (v-play.net) is a cross-platform game engine based on Qt/QML with many useful V-Play QML game components for handling multiple display resolutions & aspect ratios, animations, particles, physics, multi-touch, gestures, path finding and more. API reference The engine core is written in native C++, combined with the custom renderer, the games reach a solid performance of 60fps across all devices.
V-Play also comes with ready-to-use game templates for the most successful game genres like tower defense, platform games or puzzle games.
If you are curious about games made with V-Play, here is a quick selection of them:
(Disclaimer: I'm one of the guys behind V-Play)
//You could place this code into viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.tintColor = [UIColor redColor];
//change the nav bar colour
self.navigationController.view.backgroundColor = [UIColor redColor];
//change the background colour
self.navigationController.navigationBar.translucent = NO;
}
//Or you can place it into viewDidAppear
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:(BOOL)animated];
self.navigationController.navigationBar.tintColor = [UIColor redColor];
//change the nav bar colour
self.navigationController.view.backgroundColor = [UIColor redColor];
//change the background colour
self.navigationController.navigationBar.translucent = NO;
}
If efficiency is not that important for you, you can use array_keys($yourArray)[0]
in PHP 5.4 (and higher).
Examples:
# 1
$arr = ["my" => "test", "is" => "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "my"
# 2
$arr = ["test", "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "0"
# 3
$arr = [1 => "test", 2 => "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "1"
The advantage over solution:
list($firstKey) = array_keys($yourArray);
is that you can pass array_keys($arr)[0]
as a function parameter (i.e. doSomething(array_keys($arr)[0], $otherParameter)
).
HTH
I think you missed this step:
source ~/.nvm/nvm.sh
You can run this command on the bash OR you can put it in the file /.bashrc or ~/.profile or ~/.zshrc to automatically load it
I use the FALLBACK option in the HTML5 cache manifest to check if my html5 app is online or offline by:
FALLBACK:
/online.txt /offline.txt
In the html page i use javascript tot read the contents of the online/offline txt file:
<script>$.get( "urlto/online.txt", function( data ) {
$( ".result" ).html( data );
alert( data );
});</script>
When offline the script will read the contents of the offline.txt. Based on the text in the files you can detect if the webpage is online of offline.
paramstr.Remove((paramstr.Length-1),1);
This does work to remove a single character from the end of a string. But if I use it to remove, say, 4 characters, this doesn't work:
paramstr.Remove((paramstr.Length-4),1);
As an alternative, I have used this approach instead:
DateFrom = DateFrom.Substring(0, DateFrom.Length-4);
This solution is useful when your object has Specific Type. Like when obtaining the object to other source.
let user: User = new User();
(user as any).otherProperty = 'hello';
//user did not lose its type here.
From the man read:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
int fd
file descriptor is an integer and not a file pointer. The file descriptor for stdin
is 0
void *buf
pointer to buffer to store characters read by the read
function
size_t count
maximum number of characters to read
So you can read character by character with the following code:
char buf[1];
while(read(0, buf, sizeof(buf))>0) {
// read() here read from stdin charachter by character
// the buf[0] contains the character got by read()
....
}
I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.
Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.
You can use the readonly
property in your input field
<input type="text" readonly="readonly" />
You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.
So if the MySQL Native Driver (mysqlnd) driver is not available, and therefore using bind_result and fetch instead of get_result, the code becomes:
include 'conn.php';
$conn = new Connection();
$query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?';
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('sss', $_POST['EmailID'], $_POST['SLA'], $_POST['Password']);
$stmt->execute();
$stmt->bind_result($EmailVerified, $Blocked);
while ($stmt->fetch())
{
/* Use $EmailVerified and $Blocked */
}
$stmt->close();
$conn->mysqli->close();
Initiating an array with a predefined count:
Array(repeating: 0, count: 10)
I often use this for mapping statements where I need a specified number of mock objects. For example,
let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }
For something quick:
//$db = new PDO(...);
//$ids = array(...);
$qMarks = str_repeat('?,', count($ids) - 1) . '?';
$sth = $db->prepare("SELECT * FROM myTable WHERE id IN ($qMarks)");
$sth->execute($ids);
After hours of searching and trying I found out that on a x64 server the MSOnline modules must be installed for x64, and some programs that need to run them are using the x86 PS version, so they will never find it.
[SOLUTION] What I did to solve the issue was:
Copy the folders called MSOnline
and MSOnline Extended
from the source
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\
to the folder
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\
And then in PS run the Import-Module MSOnline
, and it will automatically get the module :D
Or try user scripts: http://dev.chromium.org/developers/design-documents/user-scripts
Connect to the database with the "system" user, and execute the following command:
show parameter service_name
openssl pkcs12 -in YOUR_CERTIFICATE.p12 -out YOUR_CERTIFICATE.pem -nodes -clcerts
I believe that storing JSON in a mysql database does in fact defeat the purpose of using RDBMS as it is intended to be used. I would not use it in any data that would be manipulated at some point or reported on, since it not only adds complexity but also could easily impact performance depending on how it is used.
However, I was curious if anyone else thought of a possible reason to actually do this. I was thinking to make an exception for logging purposes. In my case, I want to log requests that have a variable amount of parameters and errors. In this situation, I want to use tables for the type of requests, and the requests themselves with a JSON string of different values that were obtained.
In the above situation, the requests are logged and never manipulated or indexed within the JSON string field. HOWEVER, in a more complex environment, I would probably try to use something that has more of an intention for this type of data and store it with that system. As others have said, it really depends on what you are trying to accomplish, but following standards always helps longevity and reliability!
I don't know if this was pointed out here. The settings for .container
width have to be set on the Bootstrap website. I personally did not have to edit or touch anything within CSS files to tune my .container
size which is 1600px. Under Customize tab, there are three sections responsible for media and the responsiveness of the web:
Besides Media queries breakpoints, which I believe most people refer to, I've also changed @container-desktop
to (1130px + @grid-gutter-width)
and @container-large-desktop
to (1530px + @grid-gutter-width)
. Now, the .container
changes its width if my browser is scaled up to ~1600px and ~1200px. Hope it can help.
See the Parameter Expansion section in the Bash man
page. A[@]
returns the contents of the array, :1:2
takes a slice of length 2, starting at index 1.
A=( foo bar "a b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}") # slice to the end of the array
echo "${B[@]}" # bar a b c
echo "${B[1]}" # a b c
echo "${C[@]}" # bar a b c 42
echo "${C[@]: -2:2}" # a b c 42 # The space before the - is necesssary
Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
json loads -> returns an object from a string representing a json object.
json dumps -> returns a string representing a json object from an object.
load and dump -> read/write from/to file instead of string
Array.prototype.clear = function() {
this.length = 0;
};
And call it: array.clear();
It's an if statement
all on one line.
So
var x=1;
(x == 1) ? y="true" : y="false";
alert(y);
The expression to be evaluated is in the ( )
If it matches true, execute the code after the ?
If it matches false, execute the code after the :
Try this (OSX)
Step 1:
ps -aux | grep mysql
Then kill the 4 digits PID number
Step 2: kill 1965
Step 3: mysql.server start
Or having hard time to locate those PID numbers, try this below
Step 1 again: ps -aux | grep mysql
Step 2 again: killall
Step 3 again: mysql.server start
Here is a step by step video of uploading eclipse projects to github
https://www.youtube.com/watch?v=BH4OqYHoHC0
Adding the Steps here.
Right click on your eclipse project -> Team -> Share project
Choose git from the list shown; check the box asking create or use repository -> click on create repository and click finish. - This will create a local git repo. (Assuming you already have git installed )
Right click on project -> Team -> Commit - Select only the files you want to commit and click on Commit. - Now the files are committed to your local repo.
Go to git repositories view in eclipse ( or Team -> Show in repositories View)
Expand the git repo of your project and Right click on Remotes -> Create Remote
Remote name will appear as origin, select 'Configure Push' Option and click ok
In the next dialog, click on change next to URI textbox and give your git url, username, password and click on 'Save and Push'. This configures git Push.
For configuring Fetch, go to Git Repositories -> Remote -> Configure Fetch -> Add -> Master Branch -> Next -> Finish -> Save and Fetch
For configuring Master Branch, Branch -> Local -> Master Branch -> Right click and configure branch -> Remote: origin and Upstream Branch : refs/heads/master -> click ok
On refreshing your repo, you will be able to see the files you committed and you can do push and pull from repo.
If anyone has similar issue of having a phone with a cracked screen and has a need to access adb:
If you forgot to enable developers mode and your adb isn't running, then do the following:
adb devices
you should see the device in the list.If so, type:
adb shell mount /system
abd shell
echo "persist.service.adb.enable=1" >> default.prop
echo "persist.service.debuggable=1" >> default.prop
echo "persist.sys.usb.config=mtp,adb" >> default.prop
echo "persist.service.adb.enable=1" >> /system/build.prop
echo "persist.service.debuggable=1" >> /system/build.prop
echo "persist.sys.usb.config=mtp,adb" >> /system/build.prop
Now if you are going to reboot into your phone android will tell you "oh your adb is working but please tap on this OK button, so we can trust your PC". And obviously if we can't tap on the phone stay in the recovery mode and do the following (assuming you are not in the adb shell mode, if so first type exit
):
cd ~/.android
adb push adbkey.pub /data/misc/adb/adb_keys
Hurray, it all should be hunky-dory now! Just reboot the phone and you should be able to access adb when the phone is running:
adb shell reboot
P.S. Was using OS X and Moto X Style that's with the cracked screen.
For JPA 2.1 the javax.persistence package can be found in here:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions
The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.7.Final</version>
</dependency>
Try this piece of code, rather than ObjectInputStream
.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}
If you want to open inside the app itself instead of leaving the app you can import SafariServices and work it out.
import UIKit
import SafariServices
let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
How about:
conditions = [a, b, c]
if any(conditions) and not all(conditions):
...
Other variant:
if 1 <= sum(map(bool, conditions)) <= 2:
...
to_date()
returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:
select *
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')
You probably want to create an index on trunc(es_date)
if that is something you are doing on a regular basis.
The literal '27-APR-12'
can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date()
with a proper format mask (or an ANSI literal: date '2012-04-27'
)
Although you did right in using to_date()
and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'
.
With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy')
when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy'
or 'yyyy-mm-dd'
Your second question is easy, GET has a size limitation of 1-2 kilobytes on both the server and browser side, so any kind of larger amounts of data you'd have to send through POST.
This code will work for Swift 4.2.
let controller:SecondViewController =
self.storyboard!.instantiateViewController(withIdentifier: "secondViewController") as!
SecondViewController
controller.view.frame = self.view.bounds;
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)
#! /bin/bash
^---
remove the indicated space. The shebang should be
#!/bin/bash
Unfortunately, adding the javaee-(web)-api as a dependency doesn't give you the Javadoc or the Source to the Servlet Api to browse them from within the IDE. This is also the case for all other dependencies (JPA, EJB, ...) If you need the Servlet API sources/javadoc, you can add the following to your pom.xml (works at least for JBoss&Glassfish):
Repository:
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Repository Group</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
Dependency:
<!-- Servlet 3.0 Api Specification -->
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.0_spec</artifactId>
<version>1.0.0.Beta2</version>
<scope>provided</scope>
</dependency>
I completely removed the javaee-api from my dependencies and replaced it with the discrete parts (javax.ejb, javax.faces, ...) to get the sources and Javadocs for all parts of Java EE 6.
EDIT:
Here is the equivalent Glassfish dependency (although both dependencies should work, no matter what appserver you use).
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.servlet</artifactId>
<version>3.0</version>
<scope>provided</scope>
</dependency>
The problem with VBA is that there are both dynamic and static arrays...
Dynamic Array Example
Dim myDynamicArray() as Variant
Static Array Example
Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant
Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.
So for clarity's sake, I named my function "IsZeroLengthArray".
Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
'Tell VBA to proceed if there is an error to the next line.
On Error Resume Next
Dim UpperBound As Integer
Dim ErrorNumber As Long
Dim ErrorDescription As String
Dim ErrorSource As String
'If the array is empty this will throw an error because a zero-length
'array has no UpperBound (or LowerBound).
'This only works for dynamic arrays. If this was a static array there
'would be both an upper and lower bound.
UpperBound = UBound(subject)
'Store the Error Number and then clear the Error object
'because we want VBA to treat unintended errors normally
ErrorNumber = Err.Number
ErrorDescription = Err.Description
ErrorSource = Err.Source
Err.Clear
On Error GoTo 0
'Check the Error Object to see if we have a "subscript out of range" error.
'If we do (the number is 9) then we can assume that the array is zero-length.
If ErrorNumber = 9 Then
IsZeroLengthArray = True
'If the Error number is something else then 9 we want to raise
'that error again...
ElseIf ErrorNumber <> 0 Then
Err.Raise ErrorNumber, ErrorSource, ErrorDescription
'If the Error number is 0 then we have no error and can assume that the
'array is not of zero-length
ElseIf ErrorNumber = 0 Then
IsZeroLengthArray = False
End If
End Function
I hope that this helps others as it helped me.
You can simply pass the functions as a list:
In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:
mean sum
dummy
1 0.036901 0.369012
or as a dictionary:
In [21]: df.groupby('dummy').agg({'returns':
{'Mean': np.mean, 'Sum': np.sum}})
Out[21]:
returns
Mean Sum
dummy
1 0.036901 0.369012
Bash script to convert each page of a PDF into its own SVG file.
#!/bin/bash
#
# Make one PDF per page using PDF toolkit.
# Convert this PDF to SVG using inkscape
#
inputPdf=$1
pageCnt=$(pdftk $inputPdf dump_data | grep NumberOfPages | cut -d " " -f 2)
for i in $(seq 1 $pageCnt); do
echo "converting page $i..."
pdftk ${inputPdf} cat $i output ${inputPdf%%.*}_${i}.pdf
inkscape --without-gui "--file=${inputPdf%%.*}_${i}.pdf" "--export-plain-svg=${inputPdf%%.*}_${i}.svg"
done
To generate in png, use --export-png
, etc...
You don't have to install PyQt4 with all its side features, you just need the PyQt4 package itself. Inside the package you could use the module pyuic.py ("C:\Python27\Lib\site-packages\PyQt4\uic") to convert your Ui file.
C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py -help
update python3: use pyuic5 -help
# add filepath if needed. pyuic version = 4 or 5.
You will get all options listed:
Usage: pyuic4 [options] <ui-file>
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-p, --preview show a preview of the UI instead of generating code
-o FILE, --output=FILE
write generated code to FILE instead of stdout
-x, --execute generate extra code to test and display the class
-d, --debug show debug output
-i N, --indent=N set indent width to N spaces, tab if N is 0 [default:
4]
-w, --pyqt3-wrapper generate a PyQt v3 style wrapper
Code generation options:
--from-imports generate imports relative to '.'
--resource-suffix=SUFFIX
append SUFFIX to the basename of resource files
[default: _rc]
So your command will look like this:
C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py test_dialog.ui -o test.py -x
You could also use full file paths to your file to convert it.
Why do you want to convert it anyway? I prefer creating widgets in the designer and implement them with via the *.ui file. That makes it much more comfortable to edit it later. You could also write your own widget plugins and load them into the Qt Designer with full access. Having your ui hard coded doesn't makes it very flexible.
I reuse a lot of my ui's not only in Maya, also for Max, Nuke, etc.. If you have to change something software specific, you should try to inherit the class (with the parented ui file) from a more global point of view and patch or override the methods you have to adjust. That saves a lot of work time. Let me know if you have more questions about it.
It's because savefig
overrides the facecolor for the background of the figure.
(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor
kwarg to savefig
. It's a confusing and inconsistent default, though!)
The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none')
(I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)
Hope that helps!
I just wrote a simple script to collect the dependencies in ./node_modules. It fulfills my requirement at the moment. This may help some others, I post it here.
var fs = require("fs");
function main() {
fs.readdir("./node_modules", function (err, dirs) {
if (err) {
console.log(err);
return;
}
dirs.forEach(function(dir){
if (dir.indexOf(".") !== 0) {
var packageJsonFile = "./node_modules/" + dir + "/package.json";
if (fs.existsSync(packageJsonFile)) {
fs.readFile(packageJsonFile, function (err, data) {
if (err) {
console.log(err);
}
else {
var json = JSON.parse(data);
console.log('"'+json.name+'": "' + json.version + '",');
}
});
}
}
});
});
}
main();
In my case, the above script outputs:
"colors": "0.6.0-1",
"commander": "1.0.5",
"htmlparser": "1.7.6",
"optimist": "0.3.5",
"progress": "0.1.0",
"request": "2.11.4",
"soupselect": "0.2.0", // Remember: remove the comma character in the last line.
Now, you can copy&paste them. Have fun!
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
In that case, you don't need to use angular.copy()
Explanation :
=
represents a reference whereas angular.copy()
creates a new object as a deep copy.
Using =
would mean that changing a property of response.data
would change the corresponding property of $scope.example
or vice versa.
Using angular.copy()
the two objects would remain seperate and changes would not reflect on each other.
Another good example might be: you have a class that supports the use of cartesian (x, y, z), spherical (r, theta, phi) and cylindrical coordinates (r, phi, z). For purposes of establishing equality (equals method), you would probably want to convert all representations to one "canonical" representation of your choosing, e.g. spherical coordinates. (Or maybe you would want to do this in general - i.e. use one internal representation.) I am not an expert, but this did occur to me as maybe a good concrete example.
This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.
import java.util.Random;
If you want to test it out try something like this.
Random rn = new Random();
for(int i =0; i < 100; i++)
{
int answer = rn.nextInt(10) + 1;
System.out.println(answer);
}
Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).
The most simple and the correct way is to use Record type Record<string, string>
const myVar : Record<string, string> = {
key1: 'val1',
key2: 'val2',
}
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
No. You can't. But it is very possible in Scala:
class Foo {val bar = "a"}
class Bar {val foo = "b"}
A good solution is provided here. We have a HashMap
that stores values in unspecified order. We define an auxiliary TreeMap
and we copy all data from HashMap into TreeMap using the putAll
method. The resulting entries in the TreeMap are in the key-order.
You can set initial view controller
using Interface Builder as well as programmatically.
Below is approach used for programmatically.
Objective-C :
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"]; // <storyboard id>
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
return YES;
Swift :
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var objMainViewController: MainViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainController") as! MainViewController
self.window?.rootViewController = objMainViewController
self.window?.makeKeyAndVisible()
return true
You have to create a different state drawable for each color you want to use.
For example: list_selector_read.xml
and list_selector_unread.xml
.
All you need to do is set everything to transparent except the android:state_window_focused="false"
item.
Then when you are drawing your list you call setBackgroundResource(R.drawable.list_selector_unread/read)
for each row.
You don't set a listSelector on the ListView at all. That will maintain the default selector for your particular flavor of Android.
You can simply add multiple conditions by adding them as where() inside the join closure
->leftJoin('table2 AS b', function($join){
$join->on('a.field1', '=', 'b.field2')
->where('b.field3', '=', true)
->where('b.field4', '=', '1');
})
From "Find duplicate rows with PostgreSQL" here's smart solution:
select * from (
SELECT id,
ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
FROM tbl
) dups
where
dups.Row > 1
Here is a working Swift 3 solution from one of my apps.
/**
*
* Convert unix time to human readable time. Return empty string if unixtime
* argument is 0. Note that EMPTY_STRING = ""
*
* @param unixdate the time in unix format, e.g. 1482505225
* @param timezone the user's time zone, e.g. EST, PST
* @return the date and time converted into human readable String format
*
**/
private func getDate(unixdate: Int, timezone: String) -> String {
if unixdate == 0 {return EMPTY_STRING}
let date = NSDate(timeIntervalSince1970: TimeInterval(unixdate))
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
dayTimePeriodFormatter.timeZone = NSTimeZone(name: timezone) as TimeZone!
let dateString = dayTimePeriodFormatter.string(from: date as Date)
return "Updated: \(dateString)"
}
I was having the same issue and fixed it by changing the default program to open .ps1 files to PowerShell. It was set to Notepad.
The JSON data can be written to a file as follows
hist1 = [{'val_loss': [0.5139984398465246],
'val_acc': [0.8002029867684085],
'loss': [0.593220705309384],
'acc': [0.7687131817929321]},
{'val_loss': [0.46456472964199463],
'val_acc': [0.8173602046780344],
'loss': [0.4932038113037539],
'acc': [0.8063946213802453]}]
Write to a file:
with open('text1.json', 'w') as f:
json.dump(hist1, f)
You can also get them with pure javascript.
For example:
new URL(location.href).searchParams.get('page')
For this url: websitename.com/user/?page=1, it would return a value of 1
If BranchA has not been pushed to a remote then you can reorder the commits using rebase
and then simply merge
. It's preferable to use merge
over rebase
when possible because it doesn't create duplicate commits.
git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]
I like to simplify the code without using conditional operators in such cases:
TEMP=/mnt/silo/bin
[[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP
First of all, Navigate to your Folder using cd ( change directory) command. Then make sure you are in the correct git branch which you want to work by using the command
git branch
If you want to delete the entire files. you can do the same by using
git rm -r .
for deleting a single file,
git rm file1.txt
( file1.txt - file Name )
for delete a folder,
git rm -r foldername
After deleting the files or folders, you should commit it:
git commit -m "your comment"
Then you can push the branch:
git push
// for example,
git push origin develop
(it will update the origin repository)
I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
which allows one-to-many connections.
The above answers are good but with Express and node this will work fine.
Since express create the app for you, I'll skip that here.
var express = require('express')
, fs = require('fs')
, routes = require('./routes');
var privateKey = fs.readFileSync('cert/key.pem').toString();
var certificate = fs.readFileSync('cert/certificate.pem').toString();
// To enable HTTPS
var app = module.exports = express.createServer({key: privateKey, cert: certificate});
If you really want a vba solution you can loop through a range like this:
Sub Check()
Dim dat As Variant
Dim rng As Range
Dim i As Long
Set rng = Range("A1:A100")
dat = rng
For i = LBound(dat, 1) To UBound(dat, 1)
If dat(i, 1) <> "" Then
rng(i, 2).Value = "My Text"
End If
Next
End Sub
*EDIT*
Instead of using varients you can just loop through the range like this:
Sub Check()
Dim rng As Range
Dim i As Long
'Set the range in column A you want to loop through
Set rng = Range("A1:A100")
For Each cell In rng
'test if cell is empty
If cell.Value <> "" Then
'write to adjacent cell
cell.Offset(0, 1).Value = "My Text"
End If
Next
End Sub
Edit: As stated in the comments, the following solution applies to PowerShell V1 only.
See this blog post on "Technical Adventures of Adam Weigert" for details on how to implement this.
Example usage (copy/paste from Adam Weigert's blog):
Try {
echo " ::Do some work..."
echo " ::Try divide by zero: $(0/0)"
} -Catch {
echo " ::Cannot handle the error (will rethrow): $_"
#throw $_
} -Finally {
echo " ::Cleanup resources..."
}
Otherwise you'll have to use exception trapping.
Or you can put the terminal in raw mode, like this:
struct termios term;
term.c_iflag |= IGNBRK;
term.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF);
term.c_lflag &= ~(ICANON | ECHO | ECHOK | ECHOE | ECHONL | ISIG | IEXTEN);
term.c_cc[VMIN] = 1;
term.c_cc[VTIME] = 0;
tcsetattr(fileno(stdin), TCSANOW, &term);
Now it should be possible to read Ctrl+C keystrokes using fgetc(stdin)
. Beware using this though because you can't Ctrl+Z, Ctrl+Q, Ctrl+S, etc. like normally any more either.
foo->bar
is only shorthand for (*foo).bar
. That's all there is to it.
Say you have a makefile like this:
action:
echo argument is $(argument)
You would then call it make action argument=something
Each row in /proc/$PID/maps
describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:
address perms offset dev inode pathname
08048000-08056000 r-xp 00000000 03:0c 64593 /usr/sbin/gpm
-
will appear instead of the r
/w
/x
. If a region is not shared, it is private, so a p
will appear instead of an s
. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect
system call.mmap
), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.[heap]
, [stack]
, or [vdso]
. [vdso]
stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"You might notice a lot of anonymous regions. These are usually created by mmap
but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.
I used jruby-1.7.4 to compile my ruby code.
require 'roman-numerals.rb'
is the code which threw the below error.
LoadError: no such file to load -- roman-numerals
require at org/jruby/RubyKernel.java:1054
require at /Users/amanoharan/.rvm/rubies/jruby-1.7.4/lib/ruby/shared/rubygems/custom_require.rb:36
(root) at /Users/amanoharan/Documents/Aptana Studio 3 Workspace/RubyApplication/RubyApplication1/Ruby2.rb:2
I removed rb from require and gave
require 'roman-numerals'
It worked fine.
Try the method rstrip()
(see doc Python 2 and Python 3)
>>> 'test string\n'.rstrip()
'test string'
Python's rstrip()
method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp
.
>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
To strip only newlines:
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
There are also the methods strip()
, lstrip()
and strip()
:
>>> s = " \n\r\n \n abc def \n\r\n \n "
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def \n\r\n \n '
>>> s.rstrip()
' \n\r\n \n abc def'
For xlsx I like the solution posted earlier as https://web.archive.org/web/20180216070531/https://stackoverflow.com/questions/4371163/reading-xlsx-files-using-python. I uses modules from the standard library only.
def xlsx(fname):
import zipfile
from xml.etree.ElementTree import iterparse
z = zipfile.ZipFile(fname)
strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
rows = []
row = {}
value = ''
for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
if el.tag.endswith('}v'): # Example: <v>84</v>
value = el.text
if el.tag.endswith('}c'): # Example: <c r="A3" t="s"><v>84</v></c>
if el.attrib.get('t') == 's':
value = strings[int(value)]
letter = el.attrib['r'] # Example: AZ22
while letter[-1].isdigit():
letter = letter[:-1]
row[letter] = value
value = ''
if el.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
Improvements added are fetching content by sheet name, using re to get the column and checking if sharedstrings are used.
def xlsx(fname,sheet):
import zipfile
from xml.etree.ElementTree import iterparse
import re
z = zipfile.ZipFile(fname)
if 'xl/sharedStrings.xml' in z.namelist():
# Get shared strings
strings = [element.text for event, element
in iterparse(z.open('xl/sharedStrings.xml'))
if element.tag.endswith('}t')]
sheetdict = { element.attrib['name']:element.attrib['sheetId'] for event,element in iterparse(z.open('xl/workbook.xml'))
if element.tag.endswith('}sheet') }
rows = []
row = {}
value = ''
if sheet in sheets:
sheetfile = 'xl/worksheets/sheet'+sheets[sheet]+'.xml'
#print(sheet,sheetfile)
for event, element in iterparse(z.open(sheetfile)):
# get value or index to shared strings
if element.tag.endswith('}v') or element.tag.endswith('}t'):
value = element.text
# If value is a shared string, use value as an index
if element.tag.endswith('}c'):
if element.attrib.get('t') == 's':
value = strings[int(value)]
# split the row/col information so that the row leter(s) can be separate
letter = re.sub('\d','',element.attrib['r'])
row[letter] = value
value = ''
if element.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
If you want to go to the previous page without knowing the url, you could use the new History api.
history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.
But you can't manipulate the content of the history stack on browser that doesn't support the HTML5 History API
For more information see the doc
From https://mariadb.com/kb/en/mysql_secure_installation/ :
In order to log into MariaDB to secure it, we'll need the current password for the root user. If you've just installed MariaDB, and you haven't set the root password yet, the password will be blank, so you should just press enter here.
the password will be blank
I think that's your answer.
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
Dictionary data type has a method called dict_name.pop(item)
and this can be used to delete a key:value pair from a dictionary.
a={9:4,2:3,4:2,1:3}
a.pop(9)
print(a)
This will give the output as:
{2: 3, 4: 2, 1: 3}
This way you can delete an item from a dictionary in one line.
Short answer: No.
The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.
So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.
Long answer #1 has been given by others.
Long answer #2:
Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.
Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.
The example you gave in your question would then look like this:
var commandList = new List<Command>() { new MyABCCommand() };
foreach (Command c in commandList)
{
if (c.Accept(mystring))
{
c.Execute(mystring);
break;
}
}
class MyABCCommand : Command
{
override bool Accept(string mystring)
{
return mystring.StartsWith("abc");
}
}
Set
android:focusable="true"
in your <EditText/>
Ran into the same issue, using Unity3D
=> Xcode 6.3
requires Unity 4.6.4
If you're using an older Unity
version (e.g. 4.6.3
) you'll always get your devices in the Ineligible Devices
section
Disclaimer: this is an update to Cascabel's answer, which I'm writing to save the curious some time.
I tried in vain to replicate (in Git 2.0.1) the remote HEAD is ambiguous
message that Cascabel mentions in his answer; so I did a bit of digging (by cloning https://github.com/git/git and searching the log). It used to be that
Determining HEAD is ambiguous since it is done by comparing SHA1s. In the case of multiple matches we return refs/heads/master if it matches, else we return the first match we encounter. builtin-remote needs all matches returned to it, so add a flag for it to request such.
(Commit 4229f1fa325870d6b24fe2a4c7d2ed5f14c6f771
, dated Feb 27, 2009, found with git log --reverse --grep="HEAD is ambiguous"
)
However, the ambiguity in question has since been lifted:
One long-standing flaw in the pack transfer protocol used by "git clone" was that there was no way to tell the other end which branch "HEAD" points at, and the receiving end needed to guess. A new capability has been defined in the pack protocol to convey this information so that cloning from a repository with more than one branches pointing at the same commit where the HEAD is at now reliably sets the initial branch in the resulting repository.
(Commit 9196a2f8bd46d36a285bdfa03b4540ed3f01f671
, dated Nov 8, 2013, found with git log --grep="ambiguous" --grep="HEAD" --all-match
)
Edit (thanks to torek):
$ git name-rev --name-only 9196a2f8bd46d36a285bdfa03b4540ed3f01f671
tags/v1.8.4.3~3
This means that, if you're using Git v1.8.4.3 or later, you shouldn't run into any ambiguous-remote-HEAD problem.
Web API works very nicely if you accept the fact that you are using HTTP. It's when you start trying to pretend that you are sending objects over the wire that it starts to get messy.
public class TextController : ApiController
{
public HttpResponseMessage Post(HttpRequestMessage request) {
var someText = request.Content.ReadAsStringAsync().Result;
return new HttpResponseMessage() {Content = new StringContent(someText)};
}
}
This controller will handle a HTTP request, read a string out of the payload and return that string back.
You can use HttpClient to call it by passing an instance of StringContent. StringContent will be default use text/plain as the media type. Which is exactly what you are trying to pass.
[Fact]
public void PostAString()
{
var client = new HttpClient();
var content = new StringContent("Some text");
var response = client.PostAsync("http://oak:9999/api/text", content).Result;
Assert.Equal("Some text",response.Content.ReadAsStringAsync().Result);
}
Note: I found this question (varchar(255) v tinyblob v tinytext), which says that VARCHAR(n) requires n+1 bytes of storage for n<=255, n+2 bytes of storage for n>255. Is this the only reason? That seems kind of arbitrary, since you would only be saving two bytes compared to VARCHAR(256), and you could just as easily save another two bytes by declaring it VARCHAR(253).
No. you don't save two bytes by declaring 253. The implementation of the varchar is most likely a length counter and a variable length, nonterminated array. This means that if you store "hello" in a varchar(255) you will occupy 6 bytes: one byte for the length (the number 5) and 5 bytes for the five letters.
for me this works
unicode(data).encode('utf-8')
Personally, I would say that you should just make sure there is an @ symbol in there, with possibly a . character. There's many regexes you could use of varying correctness, but I think most of these leave out valid email addresses, or let invalid ones through. If people want to put in a fake email address, they will put in a fake one. If you need to verify that the email address is legit, and that the person is in control of that email address, then you will need to send them an email with a special coded link so they can verify that it indeed is a real address.
select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
from table1
where IsCurrent = 1
concat()
function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
I honestly suggest that you use moment.js. Just download moment.min.js
and then use this snippet to get your date in whatever format you want:
<script>
$(document).ready(function() {
// set an element
$("#date").val( moment().format('MMM D, YYYY') );
// set a variable
var today = moment().format('D MMM, YYYY');
});
</script>
Use following chart for date formats:
In Laravel 6 you can get it like this:
try {
window.$ = window.jQuery = require('jquery');
} catch (e) {}
gradle supports ndk compilation by generating another Android.mk file with absolute paths to your sources. NDK supports absolute paths since r9 on OSX, r9c on Windows, so you need to upgrade your NDK to r9+.
You may run into other troubles as NDK support by gradle is preliminary. If so you can deactivate the ndk compilation from gradle by setting:
sourceSets.main {
jni.srcDirs = []
jniLibs.srcDir 'src/main/libs'
}
to be able to call ndk-build yourself and integrate libs from libs/.
btw, you have any issue compiling for x86 ? I see you haven't included it in your APP_ABI.
Ripping off Luc's comment here, but to return a blank response, like a 201
the simplest option is to use the following return in your route.
return "", 201
So for example:
@app.route('/database', methods=["PUT"])
def database():
update_database(request)
return "", 201
One possible cause, it that you've enabled the "pause on exceptions" (the little stop-sign shaped icon with the pause (||) symbol with in in the lower left of the window). Try clicking that back to the off/grey state (not red nor blue states) and reload the page.
UPDATE: Adding a screenshot for reference:
It would depend on why you want it to restart itself.
If you are just looking for a way to have the service clean itself out periodically then you could have a timer running in the service that periodically causes a purge routine.
If you are looking for a way to restart on failure - the service host itself can provide that ability when it is setup.
So why do you need to restart the server? What are you trying to achieve?
$ adb shell
$ cd /data
$ ls
opendir failed, Permission denied
You should do this:
$ adb shell
$ cd /data
shell@android:/data $ run-as com.your.package
shell@android:/data/data/com.your.package $ ls
OK!
This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:
String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
Spaces are initially left in the input so the split will still work.
By removing the rubbish characters before splitting, you avoid having to loop through the elements.
This command helped me on linux mint when i had exact same problem
gcc filename.c -L/usr/include -lreadline -o filename
You could use alias if you compile it many times Forexample:
alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
Have you thought about using the TAG "dt" instead of "ul" for nesting lists? It's inherit style and structure allow you to have a title per section and it automatically tabulates the content that goes inside.
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
VS
<ul>
<li>Choice A</li>
<li>Choice B
<ul>
<li>Sub 1</li>
<li>Sub 2</li>
</ul>
</li>
</ul>
Use an iterator.
List comprehension:
>>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
>>> [c+next(si, '') for c in si]
['abcde', 'fghijklmn', 'opqr']
Generator expression:
>>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
>>> pair_iter = (c+next(si, '') for c in si)
>>> pair_iter # can be used in a for loop
<generator object at 0x4ccaa8>
>>> list(pair_iter)
['abcde', 'fghijklmn', 'opqr']
Using map, str.__add__, iter
>>> si = iter(['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r'])
>>> map(str.__add__, si, si)
['abcde', 'fghijklmn', 'opqr']
next(iterator[, default]) is available starting in Python 2.6
2017 update
The original answer below assumes that the OP wants to include non-empty text node and other node types as well as elements. It doesn't seem clear to me now from the question whether this is a valid assumption.
Assuming instead you just want the element index, previousElementSibling
is now well-supported (which was not the case in 2012) and is the obvious choice now. The following (which is the same as some other answers here) will work in everything major except IE <= 8.
function getElementIndex(node) {
var index = 0;
while ( (node = node.previousElementSibling) ) {
index++;
}
return index;
}
Original answer
Just use previousSibling
until you hit null
. I'm assuming you want to ignore white space-only text nodes; if you want to filter other nodes then adjust accordingly.
function getNodeIndex(node) {
var index = 0;
while ( (node = node.previousSibling) ) {
if (node.nodeType != 3 || !/^\s*$/.test(node.data)) {
index++;
}
}
return index;
}
use the fusion API that google developer have developed with fusion of GPS Sensor,Magnetometer,Accelerometer also using Wifi or cell location to calculate or estimate the location. It is also able to give location updates also inside the building accurately.
package com.example.ashis.gpslocation;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Location sample.
*
* Demonstrates use of the Location API to retrieve the last known location for a device.
* This sample uses Google Play services (GoogleApiClient) but does not need to authenticate a user.
* See https://github.com/googlesamples/android-google-accounts/tree/master/QuickStart if you are
* also using APIs that need authentication.
*/
public class MainActivity extends Activity implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final long ONE_MIN = 500;
private static final long TWO_MIN = 500;
private static final long FIVE_MIN = 500;
private static final long POLLING_FREQ = 1000 * 20;
private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
private static final float MIN_ACCURACY = 1.0f;
private static final float MIN_LAST_READ_ACCURACY = 1;
private LocationRequest mLocationRequest;
private Location mBestReading;
TextView tv;
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!servicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv1);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(POLLING_FREQ);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onPause() {d
super.onPause();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
tv.setText(location + "");
// Determine whether new location is better than current best
// estimate
if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {
mBestReading = location;
if (mBestReading.getAccuracy() < MIN_ACCURACY) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
@Override
public void onConnected(Bundle dataBundle) {
// Get first reading. Get additional location updates if necessary
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
//Schedule a runnable to unregister location listeners
@Override
public void run() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);
}
}, ONE_MIN, TimeUnit.MILLISECONDS);
}
}
}
@Override
public void onConnectionSuspended(int i) {
}
private Location bestLastKnownLocation(float minAccuracy, long minTime) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
// Get the best most recent location currently available
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//tv.setText(mCurrentLocation+"");
if (mCurrentLocation != null) {
float accuracy = mCurrentLocation.getAccuracy();
long time = mCurrentLocation.getTime();
if (accuracy < bestAccuracy) {
bestResult = mCurrentLocation;
bestAccuracy = accuracy;
bestTime = time;
}
}
// Return best reading or null
if (bestAccuracy > minAccuracy || bestTime < minTime) {
return null;
}
else {
return bestResult;
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private boolean servicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
}
else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0).show();
return false;
}
}
}
Should be able to do something like this also:
Select (id :> VARCHAR(10)) as converted__id_int
from t9
Okay, I think I know what you're looking for. It appears that GGT is a pretty good solution, as Reed Copsey suggested.
Personally, we rolled our own little library, because we deal with rational points a lot - lots of rational NURBS and Beziers.
It turns out that most 3D graphics libraries do computations with projective points that have no basis in projective math, because that's what gets you the answer you want. We ended up using Grassmann points, which have a solid theoretical underpinning and decreased the number of point types. Grassmann points are basically the same computations people are using now, with the benefit of a robust theory. Most importantly, it makes things clearer in our minds, so we have fewer bugs. Ron Goldman wrote a paper on Grassmann points in computer graphics called "On the Algebraic and Geometric Foundations of Computer Graphics".
Not directly related to your question, but an interesting read.
To control the location of the title you may want to set a custom font as explained here (by twaddington): Link
Then to relocate the position of the text, in updateMeasureState()
you would add p.baselineShift += (int) (p.ascent() * R);
Similarly in updateDrawState()
add tp.baselineShift += (int) (tp.ascent() * R);
Where R is double between -1 and 1.
A more direct way would be:
myvar=$(mysql mydatabase -u $user -p$password -se "SELECT a, b, c FROM table_a")
if (card1.getRarity() < card2.getRarity()) {
return 1;
However, if card2.getRarity()
is less than card1.getRarity()
you might not return -1.
You similarly miss other cases. I would do this, you can change around depending on your intent:
public int compareTo(Object o) {
if(this == o){
return 0;
}
CollectionItem item = (CollectionItem) o;
Card card1 = CardCache.getInstance().getCard(cardId);
Card card2 = CardCache.getInstance().getCard(item.getCardId());
int comp=card1.getSet() - card2.getSet();
if (comp!=0){
return comp;
}
comp=card1.getRarity() - card2.getRarity();
if (comp!=0){
return comp;
}
comp=card1.getSet() - card2.getSet();
if (comp!=0){
return comp;
}
comp=card1.getId() - card2.getId();
if (comp!=0){
return comp;
}
comp=card1.getCardType() - card2.getCardType();
return comp;
}
}
#include<stdio.h>
void main()
{
char a;
scanf("%c",&a);
printf("%d",a);
}
Functionally, you should be able to use
SELECT column_name
FROM table_name
WHERE TRIM(column_name) IS NULL
The problem there is that an index on COLUMN_NAME would not be used. You would need to have a function-based index on TRIM(column_name) if that is a selective condition.
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.
Given an array declared as:
byte[] array = new byte[4];
You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException
to be thrown. Remember this when you create and access an array.
Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1
(where Length
is total number of items in the array) so this code doesn't work:
array[array.Length] = 0;
Moreover please note that if you have a multidimensional array then you can't use Array.Length
for both dimension, you have to use Array.GetLength()
:
int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
for (int j=0; j < data.GetLength(1); ++j) {
data[i, j] = 1;
}
}
Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color
. Each item represents a pixel, indices are from (0, 0)
to (imageWidth - 1, imageHeight - 1)
.
Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
for (int y = 0; y <= imageHeight; ++y) {
pixels[x, y] = backgroundColor;
}
}
This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]
:
pixels[imageWidth, imageHeight] = Color.Black;
In another scenario you may get ArgumentOutOfRangeException
for this code (for example if you're using GetPixel
method on a Bitmap
class).
Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>()
, this example adds a new entry to an existing array:
Array.Resize(ref array, array.Length + 1);
Don't forget that valid indices are from 0
to Length - 1
. If you simply try to assign an item at Length
you'll get IndexOutOfRangeException
(this behavior may confuse you if you think they may increase with a syntax similar to Insert
method of other collections).
Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:
var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });
In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.
Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:
private static string[] RomanNumbers =
new string[] { "I", "II", "III", "IV", "V" };
public static string Romanize(int number)
{
return RomanNumbers[number];
}
Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:
// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.IndexOf(myArray, "Debug")]);
// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);
This will fail if no items in myArray
will satisfy search condition because Array.IndexOf()
will return -1 and then array access will throw.
Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):
static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
int[] result = new int[maximum + 1]; // Includes 0
foreach (int number in numbers)
++result[number];
return result;
}
Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum
.
How it applies to List<T>
?
Same cases as array - range of valid indexes - 0 (List
's indexes always start with 0) to list.Count
- accessing elements outside of this range will cause the exception.
Note that List<T>
throws ArgumentOutOfRangeException
for the same cases where arrays use IndexOutOfRangeException
.
Unlike arrays, List<T>
starts empty - so trying to access items of just created list lead to this exception.
var list = new List<int>();
Common case is to populate list with indexing (similar to Dictionary<int, T>
) will cause exception:
list[0] = 42; // exception
list.Add(42); // correct
IDataReader and Columns
Imagine you're trying to read data from a database with this code:
using (var connection = CreateConnection()) {
using (var command = connection.CreateCommand()) {
command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
ProcessData(reader.GetString(2)); // Throws!
}
}
}
}
GetString()
will throw IndexOutOfRangeException
because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).
Please note that this behavior is shared with most IDataReader
implementations (SqlDataReader
, OleDbDataReader
and so on).
You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with
var data = dr["Colum1"]; // Missing the n in Column1.
This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".
Others
There is another (documented) case when this exception is thrown: if, in DataView
, data column name being supplied to the DataViewSort
property is not valid.
In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0
with GetLowerBound(0)
and .Length
with GetUpperBound(0)
(of course if you have parameters of type System.Arra
y, it doesn't apply for T[]
). Please note that in this case, upper bound is inclusive then this code:
for (int i=0; i < array.Length; ++i) { }
Should be rewritten like this:
for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }
Please note that this is not allowed (it'll throw InvalidCastException
), that's why if your parameters are T[]
you're safe about custom lower bound arrays:
void foo<T>(T[] array) { }
void test() {
// This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}
Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException
or ArgumentOutOfRangeException
). In the next example, wrong parameters may cause IndexOutOfRangeException
, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:
static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
if (from < 0 || from>= array.Length)
throw new ArgumentOutOfRangeException("from");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (from + length > array.Length)
throw new ArgumentException("...");
for (int i=from; i < from + length; ++i)
array[i] = function(i);
}
If function is private you may simply replace if
logic with Debug.Assert()
:
Debug.Assert(from >= 0 && from < array.Length);
Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert()
, throw a proper exception (more descriptive about the problem) or handle that like in this example:
class Table {
public int SelectedIndex { get; set; }
public Row[] Rows { get; set; }
public Row SelectedRow {
get {
if (Rows == null)
throw new InvalidOperationException("...");
// No or wrong selection, here we just return null for
// this case (it may be the reason we use this property
// instead of direct access)
if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
return null;
return Rows[SelectedIndex];
}
}
Validate Return Values
In one of previous examples we directly used Array.IndexOf()
return value. If we know it may fail then it's better to handle that case:
int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }
In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.
You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:
array[index] = newValue;
You found your error, check how index
increases. Is it right? Check how array is allocated, is coherent with how index
increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!
A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.
If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).
Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.
In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.
' declares an array with space for 5 integer
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer
So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException
For i As Integer = 0 To 4
myArray(i) = i
Next
This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration
How about this:
SELECT all_fields.*
FROM (SELECT id, MAX(rev) FROM yourtable GROUP BY id) AS max_recs
LEFT OUTER JOIN yourtable AS all_fields
ON max_recs.id = all_fields.id
This one Works for me with asp label control.
function changeEmaillbl() {
if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
}
}
It indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. The max limit of watches has been reacherd, you can viewed the limit by running:
cat /proc/sys/fs/inotify/max_user_watches
run below code resolve this issue:
fs.inotify.max_user_watches=524288
If you want to get rid of the pointer you can do this with css using cursor.
In order to execute multiple programs, I also needed a profiles
section:
<profiles>
<profile>
<id>traverse</id>
<activation>
<property>
<name>traverse</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<argument>org.dhappy.test.NeoTraverse</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
This is then executable as:
mvn exec:exec -Ptraverse
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
i had the same case on linux ubuntu and just fixed it, it seems that OS was confused between the /root/.ssh/ and home/user/.ssh/ dir, what i did was:
heroku keys
heroku keys:clear
heroku keys:add
now in here if heroku couldn't find a key and asked to generate one right no, and this mean you have the same issue as mine, do the add command like this heroku keys:add /root/.ssh/id_rsa.pub
the path that you'll add will be the one that you got in step 2.git push heroku master
nowA base R option is the split()
-lapply()
-do.call()
idiom:
> do.call(rbind, lapply(split(test, test$id), head, 1))
id string
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
A more direct option is to lapply()
the [
function:
> do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
id string
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
The comma-space 1, )
at the end of the lapply()
call is essential as this is equivalent of calling [1, ]
to select first row and all columns.
Basically it depends on the precision you need for your locations. Using DOUBLE you'll have a 3.5nm precision. DECIMAL(8,6)/(9,6) goes down to 16cm. FLOAT is 1.7m...
This very interesting table has a more complete list: http://mysql.rjweb.org/doc.php/latlng :
Datatype Bytes Resolution
Deg*100 (SMALLINT) 4 1570 m 1.0 mi Cities
DECIMAL(4,2)/(5,2) 5 1570 m 1.0 mi Cities
SMALLINT scaled 4 682 m 0.4 mi Cities
Deg*10000 (MEDIUMINT) 6 16 m 52 ft Houses/Businesses
DECIMAL(6,4)/(7,4) 7 16 m 52 ft Houses/Businesses
MEDIUMINT scaled 6 2.7 m 8.8 ft
FLOAT 8 1.7 m 5.6 ft
DECIMAL(8,6)/(9,6) 9 16cm 1/2 ft Friends in a mall
Deg*10000000 (INT) 8 16mm 5/8 in Marbles
DOUBLE 16 3.5nm ... Fleas on a dog
Hope this helps.
As JavaScript is client side and JSP is Server side.
So Javascript does not execute until it gets to the browser, But Java executes on the server. So, Java does not know the value of the JavaScript variable.
However you assign value of Java variable to JavaScript variable.
This works with Windows 10, 8.x, 7, and possibly further back:
@echo Started: %date% %time%
.
.
.
@echo Completed: %date% %time%
I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.
Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.
In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.
Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.
For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :
20/2 = 10
10/2 = 5
Hence our answer is 5 + 1 + 1 = 7
. (The 1 + 1 because we divided the number 20 twice).
Use the below code to resolve the issue.
import json
from numpyencoder import NumpyEncoder
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08
15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8',cls=NumpyEncoder))
afile.close()
in Winforms, there is a Screen class you can use to get data about screen dimensions and color depth for all displays connected to the computer. Here's the docs page: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx
CHANGING the screen resolution is trickier. There is a Resolution third party class that wraps the native code you'd otherwise hook into. Use its CResolution nested class to set the screen resolution to a new height and width; but understand that doing this will only work for height/width combinations the display actually supports (800x600, 1024x768, etc, not 817x435).
You can easily set a pandas.DataFrame column to a constant. This constant can be an int such as in your example. If the column you specify isn't in the df, then pandas will create a new column with the name you specify. So after your dataframe is constructed, (from your question):
df = pd.DataFrame({'a':[np.nan, 2, 3], 'b':[4, 5, 6]}, index=[3, 5, 6])
You can just run:
df['s1'], df['s2'] = 5, 6
You could write a loop or comprehension to make it do this for all the elements in a list of tuples, or keys and values in a dictionary depending on how you have your real data stored.
Null pointer is a special reserved value of a pointer. A pointer of any type has such a reserved value. Formally, each specific pointer type (int *
, char *
etc.) has its own dedicated null-pointer value. Conceptually, when a pointer has that null value it is not pointing anywhere.
Void pointer is a specific pointer type - void *
- a pointer that points to some data location in storage, which doesn't have any specific type.
So, once again, null pointer is a value, while void pointer is a type. These concepts are totally different and non-comparable. That essentially means that your question, as stated, is not exactly valid. It is like asking, for example, "What is the difference between a triangle and a car?".
you can create one image for bottom border and set it to the background of your UITextField :
yourTextField.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yourBorderedImageName"]];
or set borderStyle to none and put image of line exactly equal length to textfield!
<p id="text" onclick="func()">
Click on text to change
</p>
<script>
function func()
{
document.getElementById("text").style.color="red";
document.getElementById("text").style.font="calibri";
}
</script>
In case you have a predicate
and/or a non empty output
to fill with the filtered string, I would consider:
output.reserve(str.size() + output.size());
std::copy_if(str.cbegin(),
str.cend(),
std::back_inserter(output),
predicate});
In the original question the predicate is [](char c){return c != 'a';}
In Mac there is a fast method with brew:
brew search node
You see some version, for example: node@10 node@12 ... Then
brew unlink node
And now select a before version for example node@12
brew link --overwrite --force node@12
Ready, you have downgraded you node version.
Multiple rows with checkboxes and select all using useState()
hooks. Requires minor implementation to adjust to own project.
const data;
const [ allToggled, setAllToggled ] = useState(false);
const [ toggled, setToggled ] = useState(Array.from(new Array(data.length), () => false));
const [ selected, setSelected ] = useState([]);
const handleToggleAll = allToggled => {
let selectAll = !allToggled;
setAllToggled(selectAll);
let toggledCopy = [];
let selectedCopy = [];
data.forEach(function (e, index) {
toggledCopy.push(selectAll);
if(selectAll) {
selectedCopy.push(index);
}
});
setToggled(toggledCopy);
setSelected(selectedCopy);
};
const handleToggle = index => {
let toggledCopy = [...toggled];
toggledCopy[index] = !toggledCopy[index];
setToggled(toggledCopy);
if( toggledCopy[index] === false ){
setAllToggled(false);
}
else if (allToggled) {
setAllToggled(false);
}
};
....
Header: state => (
<input
type="checkbox"
checked={allToggled}
onChange={() => handleToggleAll(allToggled)}
/>
),
Cell: row => (
<input
type="checkbox"
checked={toggled[row.index]}
onChange={() => handleToggle(row.index)}
/>
),
....
<ReactTable
...
getTrProps={(state, rowInfo, column, instance) => {
if (rowInfo && rowInfo.row) {
return {
onClick: (e, handleOriginal) => {
let present = selected.indexOf(rowInfo.index);
let selectedCopy = selected;
if (present === -1){
selected.push(rowInfo.index);
setSelected(selected);
}
if (present > -1){
selectedCopy.splice(present, 1);
setSelected(selectedCopy);
}
handleToggle(rowInfo.index);
},
style: {
background: selected.indexOf(rowInfo.index) > -1 ? '#00afec' : 'white',
color: selected.indexOf(rowInfo.index) > -1 ? 'white' : 'black'
},
}
}
else {
return {}
}
}}
/>
For Xcode 5 I add:
####
# Xcode 5 - VCS metadata
#
*.xccheckout
From Berik's Answer
In my case this was a syntax issue in the .yml file. I had:
@Value("${spring.kafka.bootstrap-servers}")
public List<String> BOOTSTRAP_SERVERS_LIST;
and the list in my .yml file:
bootstrap-servers:
- s1.company.com:9092
- s2.company.com:9092
- s3.company.com:9092
was not reading into the @Value-annotated field. When I changed the syntax in the .yml file to:
bootstrap-servers >
s1.company.com:9092
s2.company.com:9092
s3.company.com:9092
it worked fine.
You can use something like this
("{:0%db}"%length).format(num)
One cool solution might be separating all environment-specific values into some separate angular module, that all other modules depend on:
angular.module('configuration', [])
.constant('API_END_POINT','123456')
.constant('HOST','localhost');
Then your modules that need those entries can declare a dependency on it:
angular.module('services',['configuration'])
.factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
return $resource(API_END_POINT + 'user');
});
Now you could think about further cool stuff:
The module, that contains the configuration can be separated into configuration.js, that will be included at your page.
This script can be easily edited by each of you, as long as you don’t check this separate file into git. But it's easier to not check in the configuration if it is in a separate file. Also, you could branch it locally.
Now, if you have a build-system, like ANT or Maven, your further steps could be implementing some placeholders for the values API_END_POINT, that will be replaced during build-time, with your specific values.
Or you have your configuration_a.js
and configuration_b.js
and decide at the backend which to include.
If you want to move that commit to another branch, get the SHA of the commit in question
git rev-parse HEAD
Then switch the current branch
git checkout other-branch
And cherry-pick
the commit to other-branch
git cherry-pick <sha-of-the-commit>
You can just delete that directory that you cloned the repo into, and re-clone it wherever you'd like.
Wrap your $adr
in urlencode()
.
I was having this problem and this solved it for me.
Use this code, it is working perfectly. I have create a sql function that accept two parameters, the first param is the long string that we want to search into it,and it can accept string length up to 1500 character(of course you can extend it or even change it to text datatype). And the second parameter is the substring that we want to calculate the number of its occurance(its length is up to 200 character, of course you can change it to what your need). and the output is an integer, represent the number of frequency.....enjoy it.
CREATE FUNCTION [dbo].[GetSubstringCount]
(
@InputString nvarchar(1500),
@SubString NVARCHAR(200)
)
RETURNS int
AS
BEGIN
declare @K int , @StrLen int , @Count int , @SubStrLen int
set @SubStrLen = (select len(@SubString))
set @Count = 0
Set @k = 1
set @StrLen =(select len(@InputString))
While @K <= @StrLen
Begin
if ((select substring(@InputString, @K, @SubStrLen)) = @SubString)
begin
if ((select CHARINDEX(@SubString ,@InputString)) > 0)
begin
set @Count = @Count +1
end
end
Set @K=@k+1
end
return @Count
end
Try:
<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>
Use the "Display" style attribute with your bool model attribute to define the div's visibility.
My current solution is to run:
my_string.unpack("C*").pack("U*")
This will at least get rid of the exceptions which was my main problem
Constructors don't return a type , just remove the return type which is void in your case. It would run fine then.
In the class definitions:
private static final String PREFERENCES = "shared_prefs";
private static final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(PREFERENCES, MODE_PRIVATE);
Inside the class:
public static void deleteAllSharedPrefs(){
sharedPreferences.edit().clear().commit();
}
you may also want to look at
var hours = (datevalue1 - datevalue2).TotalHours;
There are many ways to get a page from the command line... but it also depends if you want the code source or the page itself:
If you need the code source:
with curl:
curl $url
with wget:
wget -O - $url
but if you want to get what you can see with a browser, lynx can be useful:
lynx -dump $url
I think you can find so many solutions for this little problem, maybe you should read all man pages for those commands. And don't forget to replace $url
by your URL :)
Good luck :)
I prefer using a bit test:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
This tests whether the first bit is on which signifies an odd number.
You can't as most of the posts are explaining, let me add another area:
On many websites you will find people saying that the way to avoid this is using a different AppDomain so if this happens the domain will be unloaded. That is absolutely wrong (unless you host your CLR) as the default behavior of the CLR will raise a KillProcess event, bringing down your default AppDomain.
Here is another method using .loc
to replace inf with nan on a Series:
s.loc[(~np.isfinite(s)) & s.notnull()] = np.nan
So, in response to the original question:
df = pd.DataFrame(np.ones((3, 3)), columns=list('ABC'))
for i in range(3):
df.iat[i, i] = np.inf
df
A B C
0 inf 1.000000 1.000000
1 1.000000 inf 1.000000
2 1.000000 1.000000 inf
df.sum()
A inf
B inf
C inf
dtype: float64
df.apply(lambda s: s[np.isfinite(s)].dropna()).sum()
A 2
B 2
C 2
dtype: float64
Axivion Bauhaus Suite is a static analysis tool that works with C# (as well as C, C++ and Java).
It provides the following capabilities:
These features can be run on a one-off basis or as part of a Continuous Integration process. Issues can be highlighted on a per project basis or per developer basis when the system is integrated with a source code control system.
If the other solutions don't work for you, try this:
Step 1: (if your installation is in webroot)
Replace
#RewriteBase /magento/
with
RewriteBase /
Step 2:
Add following lines (inclusive exclude admin because backend needs index.php internally)
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.yourdomain.com/$1 [R=301,L]
RewriteRule ^index.php/(admin|user)($|/) - [L]
RewriteRule ^index.php/(.*) $1 [R=301,QSA,L]
right after
RewriteRule .* index.php [L]
This works for me
In case it is still not working, double check Magento configuration: System->Configuration->Web->Search Engine Optimization. Rewrites must be enabled.
For MIUI users, apart for usual USB debugging option be sure to enable these settings as well:
Install via USB
USB debugging(Security settings)
then accept the prompt when you try installing app again.
It could be that the plugin is case-sensitive. Try inputting Te
instead of te
. You can probably have your results setup to not be case-sensitive. This question might help.
For a custom sort function on an Array
, you can use any JavaScript function and pass it as parameter to an Array
's sort()
method like this:
var array = ['White 023', 'White', 'White flower', 'Teatr'];_x000D_
_x000D_
array.sort(function(x, y) {_x000D_
if (x < y) {_x000D_
return -1;_x000D_
}_x000D_
if (x > y) {_x000D_
return 1;_x000D_
}_x000D_
return 0;_x000D_
});_x000D_
_x000D_
// Teatr White White 023 White flower_x000D_
document.write(array);
_x000D_
you can get the current url with window.location.href
but I think you will need the jQuery query plugin to manipulate the query string: http://plugins.jquery.com/project/query-object
java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.
You are right. If you want to delete the User and all associated objects -> destroy_all
However, if you just want to delete the User without suppressing all associated objects -> delete_all
According to this post : Rails :dependent => :destroy VS :dependent => :delete_all
destroy
/ destroy_all
: The associated objects are destroyed alongside this object by calling their destroy methoddelete
/ delete_all
: All associated objects are destroyed immediately without calling their :destroy methodstoi is available "since C++11". Make sure your compiler is up to date.
You can try atoi(hours0.c_str()) instead.
The best time for Kruskal's is O(E logV). For Prim's using fib heaps we can get O(E+V lgV). Therefore on a dense graph, Prim's is much better.
A string is a char[]
containing a series of UTF-16 code units, an int
offset into that array, and an int
length.
For example.
String s
It creates space for a string reference. Assigning copies references around but does not modify the objects to which those references refer.
You should also be aware that
new String(s)
doesn't really do anything useful. It merely creates another instance backed by the same array, offset, and length as s
. There is very rarely a reason to do this so it is considered bad practice by most Java programmers.
Java double quoted strings like "my string"
are really references to interned String
instances so "bar"
is a reference to the same String instance regardless of how many times it appears in your code.
The "hello" creates one instance that is pooled, and the new String(...)
creates a non-pooled instance. Try System.out.println(("hello" == "hello") + "," + (new String("hello") == "hello") + "," + (new String("hello") == new String("hello")));
and you should see true,false,false
Laravel 6 or above: just use the old() function for instance @if (old('cat')==$cat->id), it will do the rest of the work for you.
How its works: select tag store the selected option value into its name attribute in bellow case if you select any option it will store into cat. At the first time when page loaded there is nothing inside cat, when user chose a option the value of that selected option is stored into cat so when user were redirected old() function pull the previous value from cat.
{!!Form::open(['action'=>'CategoryController@storecat', 'method'=>'POST']) !!}
<div class="form-group">
<select name="cat" id="cat" class="form-control input-lg">
<option value="">Select App</option>
@foreach ($cats as $cat)
@if (old('cat')==$cat->id)
<option value={{$cat->id}} selected>{{ $cat->title }}</option>
@else
<option value={{$cat->id}} >{{ $cat->title }}</option>
@endif
@endforeach
</select>
</div>
<div class="from-group">
{{Form::label('name','Category name:')}}
{{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
</div>
<br>
{!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
{!!Form::close()!!}
You can change the color of EditText programmatically just using this line of code:edittext.setBackgroundTintList(ColorStateList.valueOf(yourcolor));
Well, like (almost) every console program for unix-like systems, git does not tell you anything if a command succeeds. It prints out something only if there's something wrong.
However if you want to be sure of what just happened, just type
git status
and see which changes are going to be committed and which not. I suggest you to use this before every commit, just to be sure that you are not forgetting anything.
Since you seem new to git, here is a link to a free online book that introduces you to git. It's very useful, it writes about basics as well as well known different workflows: http://git-scm.com/book
You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.
However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.
If you are using Linux File is a command that will do a similar task.
The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db
file.
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
Let's try this way:
select
a.ip,
a.os,
a.hostname,
a.port,
a.protocol,
b.state
from a
left join b
on a.ip = b.ip
and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/
So, in where
clause you can filter result set by column from right table only on this way:
...
where b.somecolumn <> (=) null
We can use signals for the same. I think the below example will be useful for you. It is very simple compared to threads.
import signal
def timeout(signum, frame):
raise myException
#this is an infinite loop, never ending under normal circumstances
def main():
print 'Starting Main ',
while 1:
print 'in main ',
#SIGALRM is only usable on a unix platform
signal.signal(signal.SIGALRM, timeout)
#change 5 to however many seconds you need
signal.alarm(5)
try:
main()
except myException:
print "whoops"
I think your best bet is going to be to convert those lists into something parcelable such as a string (or map?) to get it to the Activity. Then the Activity will have to convert it back to an array.
Implementing custom parcelables is a pain in the neck IMHO so I would avoid it if possible.
Check out NanoHttpd
NanoHTTPD is a light-weight HTTP server designed for embedding in other applications, released under a Modified BSD licence.
It is being developed at Github and uses Apache Maven for builds & unit testing"
.find_all()
returns list of all found elements, so:
input_tag = soup.find_all(attrs={"name" : "stainfo"})
input_tag
is a list (probably containing only one element). Depending on what you want exactly you either should do:
output = input_tag[0]['value']
or use .find()
method which returns only one (first) found element:
input_tag = soup.find(attrs={"name": "stainfo"})
output = input_tag['value']
Look closely at the two dashes in
unzipRelease –Src '$ReleaseFile' -Dst '$Destination'
This first one is not a normal dash but an en-dash (–
in HTML). Replace that with the dash found before Dst
.
Create unique constraint that two numbers together CANNOT together be repeated:
ALTER TABLE someTable
ADD UNIQUE (col1, col2)
In some cases, static methods can be difficult to test, especially if they need to be mocked, which is why most mocking frameworks don't support them. I found this blog post to be very useful in determining how to mock static methods and classes.
Technically, 'char
' could have the same range as either 'signed char
' or 'unsigned char
'. For the unsigned characters, your range is correct; theoretically, for signed characters, your condition is wrong. In practice, very few compilers will object - and the result will be the same.
Nitpick: the last &&
in the assert
is a syntax error.
Whether the assertion is appropriate depends on whether you can afford to crash when the code gets to the customer, and what you could or should do if the assertion condition is violated but the assertion is not compiled into the code. For debug work, it seems fine, but you might want an active test after it for run-time checking too.
char *a = "stack overflow";
char *b = "new string, it's real";
int d = strlen(a);
b = malloc(d * sizeof(char));
b = strcpy(b,a);
printf("%s %s\n", a, b);
$('.login').toggle(
function(){
$('#panel').animate({
height: "150",
padding:"20px 0",
backgroundColor:'#000000',
opacity:.8
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
},
function(){
$('#panel').animate({
height: "0",
padding:"0px 0",
opacity:.2
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
});
public string getMaximumSequenceOfUser(string columnName, string tableName, string username)
{
string result = "";
var query = string.Format("Select MAX ({0})from {1} where CREATED_BY = {2}", columnName, tableName, username.ToLower());
OracleConnection conn = new OracleConnection(_context.Database.Connection.ConnectionString);
OracleCommand cmd = new OracleCommand(query, conn);
try
{
conn.Open();
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
result = dr[0].ToString();
dr.Dispose();
}
finally
{
conn.Close();
}
return result;
}
Adding MaxHeight
and VerticalScrollBarVisibility="Auto"
on the DataGrid
solved my problem.
Did you took a look at this? http://developer.yahoo.com/yui/history/
It is not clear what you mean by auto-generate a guid into an insert statement but at a guess, I think you are trying to do something like the following:
INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Adams');
INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Baker');
In that case I believe the ID column should be declared as RAW(16);
I am doing this off the top of my head. I don't have an Oracle instance handy to test against, but I think that is what you want.
I suppose you want to commit the changes to one branch and then make those changes visible in the other branch. In git you should have no changes on top of HEAD when changing branches.
You commit only the changed files by:
git commit [some files]
Or if you are sure that you have a clean staging area you can
git add [some files] # add [some files] to staging area
git add [some more files] # add [some more files] to staging area
git commit # commit [some files] and [some more files]
If you want to make that commit available on both branches you do
git stash # remove all changes from HEAD and save them somewhere else
git checkout <other-project> # change branches
git cherry-pick <commit-id> # pick a commit from ANY branch and apply it to the current
git checkout <first-project> # change to the other branch
git stash pop # restore all changes again
once you start work with jpa and some driver is in your class path spring boot right away puts it inside as your data source (e.g h2 ) for using the defult data source therefore u will need only to define
spring.datasource.url= jdbc:mysql://localhost:3306/
spring.datasource.username=test
spring.datasource.password=test
if we go one step farther and u want to use two I would reccomend to use two data sources such as explained here : Spring Boot Configure and Use Two DataSources
Alex Martelli's solution set(queries) <= set(my_dict)
is the shortest code but may not be the fastest. Assume Q = len(queries) and D = len(my_dict).
This takes O(Q) + O(D) to make the two sets, and then (one hopes!) only O(min(Q,D)) to do the subset test -- assuming of course that Python set look-up is O(1) -- this is worst case (when the answer is True).
The generator solution of hughdbrown (et al?) all(k in my_dict for k in queries)
is worst-case O(Q).
Complicating factors:
(1) the loops in the set-based gadget are all done at C-speed whereas the any-based gadget is looping over bytecode.
(2) The caller of the any-based gadget may be able to use any knowledge of probability of failure to order the query items accordingly whereas the set-based gadget allows no such control.
As always, if speed is important, benchmarking under operational conditions is a good idea.
Buffer contains metadata which helps improve write performance
Cache contains the file content itself (sometimes yet to write to disk) which improves read performance
JPA is a layered API, the different levels have their own annotations. The highest level is the (1) Entity level which describes persistent classes then you have the (2) relational database level which assume the entities are mapped to a relational database and (3) the java model.
Level 1 annotations: @Entity
, @Id
, @OneToOne
, @OneToMany
, @ManyToOne
, @ManyToMany
.
You can introduce persistency in your application using these high level annotations alone. But then you have to create your database according to the assumptions JPA makes. These annotations specify the entity/relationship model.
Level 2 annotations: @Table
, @Column
, @JoinColumn
, ...
Influence the mapping from entities/properties to the relational database tables/columns if you are not satisfied with JPA's defaults or if you need to map to an existing database. These annotations can be seen as implementation annotations, they specify how the mapping should be done.
In my opinion it is best to stick as much as possible to the high level annotations and then introduce the lower level annotations as needed.
To answer the questions: the @OneToMany
/mappedBy
is nicest because it only uses the annotations from the entity domain. The @oneToMany
/@JoinColumn
is also fine but it uses an implementation annotation where this is not strictly necessary.
You could also change resolution of your bluestacks emulator. For example from 800x1280 to 1280x800
Here are instructions for how to change the screen resolution.
To change screen resolution in BlueStacks Android emulator you need to edit two registry items:
Run regedit.exe
Set new resolution (in decimal):
HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks\Guests\Android\FrameBuffer\0\Height
and
HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks\Guests\Android\FrameBuffer\0\Width
Kill all BlueStacks processes.
Restart BlueStacks
def xml_to_dict(node):
u'''
@param node:lxml_node
@return: dict
'''
return {'tag': node.tag, 'text': node.text, 'attrib': node.attrib, 'children': {child.tag: xml_to_dict(child) for child in node}}
UPDATE test SET a = CONCAT(a, "more text")
set up a new postgresql server and replace its data folder with the files from your external disk.
You will then be able to start that postgresql server up and retrieve the data using pg_dump (pg_dump -s for the schema-only as mentioned)
I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.
eg:
componentDidUpdate: function() {
$(".tbl-tr").height($(".tbl-tr ").height());
}
you can also add below code in AndroidManifest.xml.
android:icon="@android:color/transparent"
It will work fine.
But I found that this gives a problem as the launcher icon also become transparent.
So I used:
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
and it worked fine.
But if you are having more than one activity and want to make the icon on an activity transparent then the previous approach will work.