...this is obviously performing a 'string' comparison
No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:
WHERE int_column = '1'
...where the string value of "1" is converted to an INTeger because int_column
's data type is INT, not CHAR/VARCHAR/TEXT.
If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:
WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')
in my case I create a NSDictionary
called appSettings
and add all needed keys. For this case, the solution is:
if let dict = NSBundle.mainBundle().objectForInfoDictionaryKey("appSettings") {
if let configAppToken = dict["myKeyInsideAppSettings"] as? String {
}
}
In Android Studio 1.2.1.1
Just copy the image and paste the image into the app > res > drawable folder and it will shows you "Choose Destination Directory" popup screen as shown below screen
Now you can select option whatever resolution you want to place and if you want to view the those image into the folders then simply right click on the drawable folder > select copy paths option and open it. It will help you.
cat /proc/<PROCESS_PID>/status | grep Threads
On THL W100 running the device as root (as described above) worked only together with tethering enabled (I used AirDroid for that).
In my case, the website just can use TLSv1.2. and i use apache httpclient 4.5.6, i use this code and install jce to solve this (JDK1.7):
jce
jdk7 http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
jdk 8 http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
code:
SSLContext sslContext = SSLContext.getDefault();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1.2"}, // important
null,
NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionFactory)
.register("http", PlainConnectionSocketFactory.INSTANCE)
.build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
httpclient = HttpClientBuilder.create().
.setSSLSocketFactory(sslConnectionFactory)
.setConnectionManager(ccm)
.build();
The alternative, if you don't want to install libjpeg:
CFLAGS="--disable-jpeg" pip install pillow
From https://pillow.readthedocs.io/en/3.0.0/installation.html#external-libraries
In Java 9, you can now use Matcher#results()
to get a Stream<MatchResult>
which you can use to get a list/array of matches.
import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
.matcher("string to search from here")
.results()
.map(MatchResult::group)
.toArray(String[]::new);
// or .collect(Collectors.toList())
use this
if (userProfile.AccountType == AccountType.Retailer)
{
...
}
If you want to get int from your AccountType enum and compare it (don't know why) do this:
if((int)userProfile.AccountType == 1)
{
...
}
Objet reference not set to an instance of an object
exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.
EDIT (thanks to @Rik and @KonradMorawski) :
Maybe you can do some check before:
if(userProfile!=null)
{
}
or
if(userProfile==null)
{
throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}
Try this
load data infile 'datafile location' into table schema.tablename fields terminated by ',' optionally enclosed by '|' (field1,field2,field3....)
In command prompt:
sqlldr system@databasename/password control='control file location'
The similar problem occurs in aspdotnet core with the same error The program '[xxxx] iisexpress.exe' has exited with code -1073741816 (0xc0000008).
Log file setup in web.config did not produce any info also:
<aspNetCore stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
To find exact error the next step with log info in command prompt helped:
> dotnet restore
> dotnet run
In my case the problem was in dotnet core v 1.0.0
installed, while version 1.0.1
was required to be globally installed.
An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:
Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);
// This is not possible: It would throw an
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");
// This is still possible:
realMap.put("E", "F");
// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F".
In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.
Update:
As pointed out in a comment, an immutable map can also be created with the standard API using
Map<String, String> immutableMap =
Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap));
This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap
without having to add the dependency to Guava.
to print only the certificate chain and not the server's certificate:
# MYHOST=myhost.com
# MYPORT=443
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}'
to update CA trust on CentOS/RHEL 6/7 :
# update-ca-trust enable
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}' >/etc/pki/ca-trust/source/anchors/myca.cert
# update-ca-trust extract
on CentOS/RHEL 5:
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}' >>/etc/pki/tls/certs/ca-bundle.crt
Make sure you Double-Check that the version you refer to in the child-pom is the same as that in the parent-pom. For me, I'd bumped version in the parent and had it as 3.1.0.0-RELEASE, but in the child-pom, I was still referring to the previous version via relativePath, and had it defined as 2.0.0.0-SNAPSHOT. It did not make any difference if I included just the parent directory, or had the "pom.xml" appended to the directory:
<parent>
<artifactId>eric-project-parent</artifactId>
<groupId>com.eric.common</groupId>
<!-- Should be 3.1.0.0-RELEASE -->
<version>2.0.0.0-SNAPSHOT</version>
<relativePath>
../../EricParentAsset/projects/eric-project-parent</relativePath>
</parent>
Here's a function I use a lot. The result is yyyy-mm-dd hh:mm:ss.nnn.
function date_and_time() {
var date = new Date();
//zero-pad a single zero if needed
var zp = function (val){
return (val <= 9 ? '0' + val : '' + val);
}
//zero-pad up to two zeroes if needed
var zp2 = function(val){
return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
}
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
var h = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
var ms = date.getMilliseconds();
return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + ':' + zp(min) + ':' + zp(s) + '.' + zp2(ms);
}
I hope is will work for you.
/**
* Image re-size
* @param int $width
* @param int $height
*/
function ImageResize($width, $height, $img_name)
{
/* Get original file size */
list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']);
/*$ratio = $w / $h;
$size = $width;
$width = $height = min($size, max($w, $h));
if ($ratio < 1) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}*/
/* Calculate new image size */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* set new file name */
$path = $img_name;
/* Save image */
if($_FILES['logo_image']['type']=='image/jpeg')
{
/* Get binary data from image */
$imgString = file_get_contents($_FILES['logo_image']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
imagejpeg($tmp, $path, 100);
}
else if($_FILES['logo_image']['type']=='image/png')
{
$image = imagecreatefrompng($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h);
imagepng($tmp, $path, 0);
}
else if($_FILES['logo_image']['type']=='image/gif')
{
$image = imagecreatefromgif($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagefill($tmp, 0, 0, $transparent);
imagealphablending($tmp, true);
imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h);
imagegif($tmp, $path);
}
else
{
return false;
}
return true;
imagedestroy($image);
imagedestroy($tmp);
}
rename your image to username/image-name docker tag your-current-image/current-image dockerhub-username/some-name:your-tag(example: latest)
One should use a third party script for this called called ngStorage here is a example how to use.It updates localstorage with change in scope/view.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<!-- CDN Link -->
<!--https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js-->
<script src="angular.min.js"></script>
<script src="ngStorage.min.js"></script>
<script>
var app = angular.module('app', ['ngStorage']);
app.factory("myfactory", function() {
return {
data: ["ram", "shyam"]
};
})
app.controller('Ctrl', function($scope, $localStorage, $sessionStorage, myfactory) {
$scope.abcd = $localStorage; //Pass $localStorage (or $sessionStorage) by reference to a hook under $scope
// Delete from Local Storage
//delete $scope.abcd.counter;
// delete $localStorage.counter;
// $localStorage.$reset(); // clear the localstorage
/* $localStorage.$reset({
counter: 42 // reset with default value
});*/
// $scope.abcd.mydata=myfactory.data;
});
</script>
</head>
<body ng-app="app" ng-controller="Ctrl">
<button ng-click="abcd.counter = abcd.counter + 1">{{abcd.counter}}</button>
</body>
</html>
edit/update: Xcode 8.3.1 • Swift 3.1
extension NSView {
var backgroundColor: NSColor? {
get {
guard let color = layer?.backgroundColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.backgroundColor = newValue?.cgColor
}
}
}
usage:
let myView = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
print(myView.backgroundColor ?? "none") // NSView's background hasn't been set yet = nil
myView.backgroundColor = .red // set NSView's background color to red color
print(myView.backgroundColor ?? "none")
view.addSubview(myView)
I know this is very Old post. Since we don't have any thing sun.misc in maven we can easily use
StringUtils.newStringUtf8(Base64.encodeBase64(encVal)); From org.apache.commons.codec.binary.Base64
For example:
hr {
border:none;
border-top:1px dotted #f00;
color:#fff;
background-color:#fff;
height:1px;
width:50%;
}
See also Styling <hr>
with CSS.
Try username = root and password is blank.
Something like Decimal(19,4)
usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "money
" as it's non-standard.
$a = "This", "Is", "a", "cat"
foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)
Write-Host $sent
iContribute: It's never too late for a right answer.
var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
form.submit();
}else{
console.log("Required field missing.");
}
This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.
From requests 2.4.2 (https://pypi.python.org/pypi/requests), the "json" parameter is supported. No need to specify "Content-Type". So the shorter version:
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
I had to remove packages folder close and re-open (VS2015) solution. I was not migrating and I did not have packages checked into source control. All I can say is something got messed up and this fixed it.
I made use of sendkeys in shell scripting using a vbsscript file. Below is the code in vbs file,
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "C:\Demo.txt"
WshShell.SendKeys "{ENTER}"
Below is the selenium code line to run this vbs file,
driver.findElement(By.id("uploadname1")).click();
Thread.sleep(1000);
Runtime.getRuntime().exec( "wscript C:/script.vbs" );
You can definitely try this way
.col-form-label{
display: inline-block;
width:200px;}
append()
creates a new array which can be the old array with the appended element.
I think it's more normal to use the proper method for adding an element:
a = numpy.append(a, a[0])
I think what you are looking for is:
list(im.getdata())
or, if the image is too big to load entirely into memory, so something like that:
for pixel in iter(im.getdata()):
print pixel
from PIL documentation:
getdata
im.getdata() => sequence
Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).
The short answer for lazy people like me:
type Overrided = Omit<YourInterface, 'overrideField'> & { overrideField: <type> };
JPA doesn't provide any specification on mapping annotations to select fetch strategy. In general, related entities can be fetched in any one of the ways given below
So SELECT
and JOIN
are two extremes and SUBSELECT
falls in between. One can choose suitable strategy based on her/his domain model.
By default SELECT
is used by both JPA/EclipseLink and Hibernate. This can be overridden by using:
@Fetch(FetchMode.JOIN)
@Fetch(FetchMode.SUBSELECT)
in Hibernate. It also allows to set SELECT
mode explicitly using @Fetch(FetchMode.SELECT)
which can be tuned by using batch size e.g. @BatchSize(size=10)
.
Corresponding annotations in EclipseLink are:
@JoinFetch
@BatchFetch
It is also possible to use this:
var user_name = document.forms[0].elements[0];
var user_email = document.forms[0].elements[1];
var user_message = document.forms[0].elements[2];
All the elements of forms are stored in an array by Javascript. This takes the elements from the first form and stores each value into a unique variable.
There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.
The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.
I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.
vector<pair<int,int> >a;
for (i = 0 ;i < n ; i++) {
// filling the original array
cin >> k;
a.push_back (make_pair (k,i)); // k = value, i = original index
}
sort (a.begin(),a.end());
for (i = 0 ; i < n ; i++){
cout << a[i].first << " " << a[i].second << "\n";
}
Now a
contains both both our values and their respective indices in the sorted.
a[i].first = value
at i
'th.
a[i].second = idx
in initial array.
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
yourContext.Entry(yourEntity).Reload();
I would use the back-tick ``.
let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'
But if you don't know name1
when you create msg1
.
For exemple if msg1
came from an API.
You can use :
let name2 = 'Geoffrey';
let msg2 = 'Hello ${name2}';
console.log(msg2); // 'Hello ${name2}'
const regexp = /\${([^{]+)}/g;
let result = msg2.replace(regexp, function(ignore, key){
return eval(key);
});
console.log(result); // 'Hello Geoffrey'
It will replace ${name2}
with his value.
If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...
console.log($target); // jQuery object
$target.remove(); // remove target from the DOM
console.log($target); // $target still exists
Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)
$target = $();
console.log($target); // empty jQuery object
Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)
delete $target;
console.log($target); // error: $target is not defined
More reading: info about empty jQuery object, and info about delete
string outString= number.ToString("####0.00");
You could also use a LEFT JOIN and IS NULL condition:
SELECT
mac,
creation_date
FROM
logs
LEFT JOIN consols ON logs.mac = consols.mac
WHERE
logs_type_id=11
AND
consols.mac IS NULL;
An index on the "mac" columns might improve performance.
If you are receiving the warning: Setter for 'statusBarStyle' was deprecated in iOS 9.0: Use -[UIViewController preferredStatusBarStyle], then to set the status bar to light or dark use the following code:
//To set the status bar to white
self.navigationController?.navigationBar.barStyle = .black //or .blackTranslucent
//To set the status bar to black
self.navigationController?.navigationBar.barStyle = .default
This will not make your navBar change it purely indicates the style and therefore changes the status bar accordingly.
NB. You need to ensure that you set in your info.plist.
View controller-based status bar appearance to YES
If you don't need it to be human-readable/editable, the easiest solution is to just use pickle
.
To write:
with open(the_filename, 'wb') as f:
pickle.dump(my_list, f)
To read:
with open(the_filename, 'rb') as f:
my_list = pickle.load(f)
If you do need them to be human-readable, we need more information.
If my_list
is guaranteed to be a list of strings with no embedded newlines, just write them one per line:
with open(the_filename, 'w') as f:
for s in my_list:
f.write(s + '\n')
with open(the_filename, 'r') as f:
my_list = [line.rstrip('\n') for line in f]
If they're Unicode strings rather than byte strings, you'll want to encode
them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)
If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.
Let's use unicode-escape
here to solve both of the above problems at once:
with open(the_filename, 'w') as f:
for s in my_list:
f.write((s + u'\n').encode('unicode-escape'))
with open(the_filename, 'r') as f:
my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]
You can also use the 3.x-style solution in 2.x, with either the codecs
module or the io
module:*
import io
with io.open(the_filename, 'w', encoding='unicode-escape') as f:
f.writelines(line + u'\n' for line in my_list)
with open(the_filename, 'r') as f:
my_list = [line.rstrip(u'\n') for line in f]
* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs
; if not, use io
.
typeof document.location; // 'object'
typeof document.location.href; // 'string'
The href
property is a string, while document.location
itself is an object.
for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running
If you know how tall your text is going to be you can use a combination of top:50%
and margin-top:-x px
where x is half the height of your text.
Working example: http://jsfiddle.net/Qy4yy/
You are looking for an sprintf
implementation for JavaScript, so that you can write out floats with small errors in them (since they are stored in binary format) in a format that you expect.
Try javascript-sprintf, you would call it like this:
var yourString = sprintf("%.2f", yourNumber);
to print out your number as a float with two decimal places.
You may also use Number.toFixed() for display purposes, if you'd rather not include more files merely for floating point rounding to a given precision.
Please check if the tableview is grouped/plain. In my case I have changed the style to plain and it worked. Now the extra spacing above the header has disappeared.
Since the count is the intended final value, in your query pass
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
Epoch and iteration describe different things.
An epoch describes the number of times the algorithm sees the entire data set. So, each time the algorithm has seen all samples in the dataset, an epoch has completed.
An iteration describes the number of times a batch of data passed through the algorithm. In the case of neural networks, that means the forward pass and backward pass. So, every time you pass a batch of data through the NN, you completed an iteration.
An example might make it clearer.
Say you have a dataset of 10 examples (or samples). You have a batch size of 2, and you've specified you want the algorithm to run for 3 epochs.
Therefore, in each epoch, you have 5 batches (10/2 = 5). Each batch gets passed through the algorithm, therefore you have 5 iterations per epoch. Since you've specified 3 epochs, you have a total of 15 iterations (5*3 = 15) for training.
Using Python 3 you can have both required and non-required keyword arguments:
Optional: (default value defined for param 'b')
def func1(a, *, b=42):
...
func1(value_for_a) # b is optional and will default to 42
Required (no default value defined for param 'b'):
def func2(a, *, b):
...
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`
This can help in cases where you have many similar arguments next to each other especially if they are of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.
I could not install lombok.jar on my MacBook Pro because of the version of Java. I had to downgrade to Java 1.6 to install and then I reused Java 1.7 when the installation worked !
You can see the different JVM installed on your machine here : /System/Library/Java/JavaVirtualMachines
I'd the same problem while I was developing a simple Java application that listens on a specific TCP. Usually, I had no problem, but when I run some stress test I noticed that some connection broke with error socket write exception
.
After Investigation I found a solution that solves my problem. I know this question is quite old, but I prefer to share my solution, someone can find it useful.
The problem was on ServerSocket creation. I read from Javadoc there is a default limit of 50 pending sockets. If you try opening another connection, these will be refused. The solution consist simply in change this default configuration at server side. In the following case, I create a Socket server that listen at TCP port 10_000
and accept max 200
pending sockets.
new Thread(() -> {
try (ServerSocket serverSocket = new ServerSocket(10_000, 200)) {
logger.info("Server starts listening on TCP port {}", port);
while (true) {
try {
ClientHandler clientHandler = clientHandlerProvider.getObject(serverSocket.accept(), this);
executor.execute(clientHandler::start);
} catch (Exception e) {
logger.error(e.getMessage());
}
}
} catch (IOException | SecurityException | IllegalArgumentException e) {
logger.error("Could not open server on TCP port {}. Reason: {}", port, e.getMessage());
}
}).start();
From Javadoc of ServerSocket:
The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused.
Assign empty value:
document.getElementById('numquest').value=null;
or, if want to clear all form fields. Just call form reset method as:
document.forms['form_name'].reset()
In python 3.x. you use
print("Hello, World")
In Python 2.x. you use
print "Hello, World!"
This is due to the series df[cat]
containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna
operation.
In other words
pandas data type 'Object' indicates mixed types rather than str type
so using the following line:
df[cat] = le.fit_transform(df[cat].astype(str))
should help
If you aren't allowing the column to be Null you need to provide a default to populate existing rows. e.g.
ALTER TABLE dbo.YourTbl ADD
newcol int NOT NULL CONSTRAINT DF_YourTbl_newcol DEFAULT 0
On Enterprise Edition this is a metadata only change since 2012
Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li>
elements with class="dropdown-menu"
. It automatically displays the proper caret indicator as well.
<head>
...
<script src=".../jquery.smartmenus.min.js"></script>
<script src=".../jquery.smartmenus.bootstrap.min.js"></script>
...
<link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
...
</head>
Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html
The initialize
method is called after all @FXML
annotated members have been injected. Suppose you have a table view you want to populate with data:
class MyController {
@FXML
TableView<MyModel> tableView;
public MyController() {
tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point.
}
@FXML
public void initialize() {
tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members.
}
}
req.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
You can set MY_SOCKET_TIMEOUT_MS
as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES
can be 0 default is 1.
I have learned it is also possible to do this with the exec-maven-plugin if you're doing a "standalone" java app.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven.exec.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>${exec.main-class}</mainClass>
<systemProperties>
<systemProperty>
<key>myproperty</key>
<value>myvalue</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
One the elements are added, use the rules method to add the rules
//bug fixed thanks to @Sparky
$('input[name^="fileupload"]').each(function () {
$(this).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
})
Demo: Fiddle
Update
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
var $li = $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
$('#FileUpload' + filenumber).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
filenumber++;
return false;
});
$('input[type="text"]').get().some(item => item.value !== '');
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Note: for those using pandas 0.20.3 and above, and are looking for an answer, all these options will work:
df = pd.DataFrame(np.ones((5,6)),columns=['one','two','three',
'four','five','six'])
df.one *=5
df.two = df.two*5
df.three = df.three.multiply(5)
df['four'] = df['four']*5
df.loc[:, 'five'] *=5
df.iloc[:, 5] = df.iloc[:, 5]*5
which results in
one two three four five six
0 5.0 5.0 5.0 5.0 5.0 5.0
1 5.0 5.0 5.0 5.0 5.0 5.0
2 5.0 5.0 5.0 5.0 5.0 5.0
3 5.0 5.0 5.0 5.0 5.0 5.0
4 5.0 5.0 5.0 5.0 5.0 5.0
There are two ways to handle CGI scripts, SetHandler
and AddHandler
.
SetHandler cgi-script
applies to all files in a given context, no matter how they are named, even index.html
or style.css
.
AddHandler cgi-script .pl
is similar, but applies to files ending in .pl
, in a given context. You may choose another extension or several, if you like.
Additionally, the CGI module must be loaded and Options +ExecCGI
configured. To activate the module, issue
a2enmod cgi
and restart or reload Apache. Finally, the Perl CGI script must be executable. So the execute bits must be set
chmod a+x script.pl
and it should start with
#! /usr/bin/perl
as its first line.
When you use SetHandler
or AddHandler
(and Options +ExecCGI
) outside of any directive, it is applied globally to all files. But you may restrict the context to a subset by enclosing these directives inside, e.g. Directory
<Directory /path/to/some/cgi-dir>
SetHandler cgi-script
Options +ExecCGI
</Directory>
Now SetHandler
applies only to the files inside /path/to/some/cgi-dir instead of all files of the web site. Same is with AddHandler
inside a Directory
or Location
directive, of course. It then applies to the files inside /path/to/some/cgi-dir, ending in .pl
.
While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.
Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.
In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py
However you'd need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.
For example, you might run: C:\Python2.5.2\python.exe mymodule
Yet, the environment variables may point to the wrong version as such:
PYTHONPATH = D:\Python27
PYTHONLIB = D:\Python27\lib
Loads of horrible fun!
So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.
Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py
import sys
import subprocess
if sys.argv[2] == '272':
env272 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)
if sys.argv[1] == '252'
env252 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)
I have not tested this.
Way less code than all other solutions:
Objective-C version:
- (UIViewController *)getTopViewController {
UIViewController *topViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
while (topViewController.presentedViewController) topViewController = topViewController.presentedViewController;
return topViewController;
}
Swift 2.0 version: (credit goes to Steve.B)
func getTopViewController() -> UIViewController {
var topViewController = UIApplication.sharedApplication().delegate!.window!!.rootViewController!
while (topViewController.presentedViewController != nil) {
topViewController = topViewController.presentedViewController!
}
return topViewController
}
Works anywhere in your app, even with modals.
I suggest you also add separate checkboxes or a textfield for the special flags. That way it is clear that the user does not need to add any //
's. In the case of a replace, provide two textfields. This will make your life a lot easier.
Why? Because otherwise some users will add //
's while other will not. And some will make a syntax error. Then, after you stripped the //
's, you may end up with a syntactically valid regex that is nothing like what the user intended, leading to strange behaviour (from the user's perspective).
helloworld.png: file not recognized: File format not recognized
Obviously, you should format your hard drive.
Really, these errors aren't that hard to read.
If u are using Android X: https://material.io/develop/android/docs/getting-started/ follow the instruction here
when the latest library is
implementation 'com.google.android.material:material:1.2.1'
Update : Get latest material design library from here https://maven.google.com/web/index.html?q=com.google.android.material#com.google.android.material:material
For older SDK
Add the design support library version as same as of your appcompat-v7 library
You can get the latest library from android developer documentation https://developer.android.com/topic/libraries/support-library/packages#design
implementation 'com.android.support:design:28.0.0'
You can test this function
function html2text($Document) {
$Rules = array ('@<script[^>]*?>.*?</script>@si',
'@<[\/\!]*?[^<>]*?>@si',
'@([\r\n])[\s]+@',
'@&(quot|#34);@i',
'@&(amp|#38);@i',
'@&(lt|#60);@i',
'@&(gt|#62);@i',
'@&(nbsp|#160);@i',
'@&(iexcl|#161);@i',
'@&(cent|#162);@i',
'@&(pound|#163);@i',
'@&(copy|#169);@i',
'@&(reg|#174);@i',
'@&#(d+);@e'
);
$Replace = array ('',
'',
'',
'',
'&',
'<',
'>',
' ',
chr(161),
chr(162),
chr(163),
chr(169),
chr(174),
'chr()'
);
return preg_replace($Rules, $Replace, $Document);
}
I think the root for this confusion is well explained in this wikipedia article.
While the IANA-registered MIME type for ICO files is image/vnd.microsoft.icon, it was submitted to IANA in 2003 by a third party and is not recognised by Microsoft software, which uses image/x-icon instead.
If even the inventor of the ICO format does not use the official MIME type, I will use image/x-icon
, too.
Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:
-Xmx512m -ea -Djava.awt.headless=true
The first thing that comes to my mind is a one-liner regex:
var pageNum = $("#specificLink").attr("href").match(/page=([0-9]+)/)[1];
For Xamarin iOS
btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
I got to this thread while looking for the current directory of an executing process. In .net 1.1 Microsoft introduced:
Directory.GetCurrentDirectory();
Seems to work well (but doesn't return the name of the process itself).
I was also facing this issue but in a little different scenario.
Scenario:
param = 1
def param():
.....
def func():
if param:
var = {passing a dict here}
param(var)
It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.
Changed function name to something else and it worked.
So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code. So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.
I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.
Hope this helps!
From your post I gather that you want to compare dates, not arrays. If this is the case, then use the appropriate object: a datetime
object.
Please check the documentation for the datetime module. Dates are a tough cookie. Use reliable algorithms.
Well if you are using a DataTable at all then rather than comparing two 'DataTables' could you just compare the DataTable that is going to have changes with the original data when it was loaded AKA DataTable.GetChanges Method (DataRowState)
CSS has different pseudo selector by which you can achieve such effect. In your case you can use
:active : if you want background color only when the button is clicked and don't want to persist.
:focus: if you want background color untill the focus is on the button.
button:active{
background:olive;
}
and
button:focus{
background:olive;
}
P.S.: Please don't give the number in Id
attribute of html elements.
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
Neither, because both are quite verbose for a very simple task. You can just do:
let result = ({
1: 'One',
2: 'Two',
3: 'Three'
})[opt] ?? 'Default' // opt can be 1, 2, 3 or anything (default)
This, of course, also works with strings, a mix of both or without a default case:
let result = ({
'first': 'One',
'second': 'Two',
3: 'Three'
})[opt] // opt can be 'first', 'second' or 3
It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.
This returns undefined
if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ??
and return a default value.
console.log('Using a valid case:', ({
1: 'One',
2: 'Two',
3: 'Three'
})[1] ?? 'Default')
console.log('Using an invalid case/defaulting:', ({
1: 'One',
2: 'Two',
3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
I like to go with easy process. First Change string into Array for easy iterating, then using map function change each word as you want it to be.
function capitalizeCase(str) {
var arr = str.split(' ');
var t;
var newt;
var newarr = arr.map(function(d){
t = d.split('');
newt = t.map(function(d, i){
if(i === 0) {
return d.toUpperCase();
}
return d.toLowerCase();
});
return newt.join('');
});
var s = newarr.join(' ');
return s;
}
START_STICKY
: It will restart the service in case if it terminated and the Intent data which is passed to the onStartCommand()
method is NULL
. This is suitable for the service which are not executing commands but running independently and waiting for the job.START_NOT_STICKY
: It will not restart the service and it is useful for the services which will run periodically. The service will restart only when there are a pending startService()
calls. It’s the best option to avoid running a service in case if it is not necessary.START_REDELIVER_INTENT
: It’s same as STAR_STICKY
and it recreates the service, call onStartCommand()
with last intent that was delivered to the service.You should have 64-bit OS on hardware that supports 64-bit OS, 64-bit Apache version and the same for PHP. But this does not guarantee that functions that are work with PDF can use such big sizes of memory. You'd better not load the whole file into memory, split it into chunks or use file functions to seek on it without loading to RAM.
This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.
var dat1 = document.getElementById('inputDate').value;
var date1 = new Date(dat1)//converts string to date object
alert(date1);
var dat2 = document.getElementById('inputFinishDate').value;
var date2 = new Date(dat2)
alert(date2);
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
alert(diffDays);
Another option is to use an array, e.g.
void method(SomeClass[] v) { v[0] = ...; }
but 1) the array must be initialized before method invoked, 2) still one cannot implement e.g. swap method in this way...
This way is used in JDK, e.g. in java.util.concurrent.atomic.AtomicMarkableReference.get(boolean[])
.
You can use the DataFrame apply
method:
order_df['Value'] = order_df.apply(lambda row: (row['Prices']*row['Amount']
if row['Action']=='Sell'
else -row['Prices']*row['Amount']),
axis=1)
It is usually faster to use these methods rather than over for loops.
You can use "dd/MM/yyyy"
format for using it in DateTime.ParseExact
.
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Here is a DEMO
.
For more informations, check out Custom Date and Time Format Strings
Use this code to reset all selection fields to the default option, where the attribute selected is defined.
<select id="name1" >
<option value="1">Text 1</option>
<option value="2" selected="selected" >Default Text 2</option>
<option value="3">Text 3</option>
</select>
<select id="name2" >
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3" selected="selected" >Default Text 3</option>
</select>
<script>
$('select').each( function() {
$(this).val( $(this).find("option[selected]").val() );
});
</script>
In the same spirit as https://stackoverflow.com/a/6943976/7154924:
cat -A
-A, --show-all
equivalent to -vET
-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB
-E, --show-ends
display $ at end of each line
-T, --show-tabs
display TAB characters as ^I
Alternatively, or at the same time, you can pipe to tr
to substitute arbitrary characters to the desired ones for display, before piping to a pager like less
if desired.
Create a file named .gitignore on the root of your repository. In this file you put the relative path to each file you wish to ignore in a single line. You can use the *
wildcard.
Use the below attribute in tag to open it in next tab
target="_blank"
I was getting this problem and I'm using Spring's RestTemplate on the client and Spring Web on the server. Both APIs have very poor error reporting, making them extremely difficult to develop with.
After many hours of trying all sorts of experiments I figured out that the issue was being caused by passing in a null reference for the POST body instead of the expected List. I presume that RestTemplate cannot determine the content-type from a null object, but doesn't complain about it. After adding the correct headers, I started getting a different server-side exception in Spring before entering my service method.
The fix was to pass in an empty List from the client instead of null. No headers are required since the default content-type is used for non-null objects.
In following code, we don't need to hard code the credentials.
service.Proxy = WebRequest.DefaultWebProxy;
service.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
service.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
Add this code to the beginning:
Application.ScreenUpdating = False
With ThisWorkbook
Dim ws As Worksheet
For Each ws In Worksheets: ws.Visible = True: Next ws
End With
Add this code to the end:
With ThisWorkbook
Dim ws As Worksheet
For Each ws In Worksheets: ws.Visible = False: Next ws
End With
Application.ScreenUpdating = True
Adjust Code at the end if you want more than the first sheet to be active and visible. Such as the following:
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name = "_DataRecords" Then
Else: ws.Visible = False
End If
Next ws
To ensure the new sheet is the one renamed, adjust your code similar to the following:
Sheets(Me.cmbxSheetCopy.value).Copy After:=Sheets(Sheets.Count)
Sheets(Me.cmbxSheetCopy.value & " (2)").Select
Sheets(Me.cmbxSheetCopy.value & " (2)").Name = txtbxNewSheetName.value
This code is from my user form that allows me to copy a particular sheet (chosen from a dropdown box) with the formatting and formula's that I want to a new sheet and then rename new sheet with the user Input. Note that every time a sheet is copied it is automatically given the old sheet name with the designation of " (2)". Example "OldSheet" becomes "OldSheet (2)" after the copy and before the renaming. So you must select the Copied sheet with the programs naming before renaming.
if you have long processing server side code, I don't think it does fall into 404 as you said ("it goes to a webpage is not found error page")
Browser should report request timeout error.
You may do 2 things:
Based on CGI/Server side engine increase timeout there
PHP : http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time - default is 30 seconds
In php.ini:
max_execution_time 60
Increase apache timeout - default is 300 (in version 2.4 it is 60).
In your httpd.conf (in server config or vhost config)
TimeOut 600
Note that first setting allows your PHP script to run longer, it will not interferre with network timeout.
Second setting modify maximum amount of time the server will wait for certain events before failing a request
Sorry, I'm not sure if you are using PHP as server side processing, but if you provide more info I will be more accurate.
XML is so versatile...
<DATA>
<BINARY>
<BIT index="0">0</BIT>
<BIT index="1">0</BIT>
<BIT index="2">1</BIT>
...
<BIT index="n">1</BIT>
</BINARY>
</DATA>
XML is like violence - If it doesn't solve your problem, you're not using enough of it.
EDIT:
BTW: Base64 + CDATA is probably the best solution
(EDIT2:
Whoever upmods me, please also upmod the real answer. We don't want any poor soul to come here and actually implement my method because it was the highest ranked on SO, right?)
The iPhone 6+ renders internally using @3x assets at a virtual resolution of 2208×1242 (with 736x414 points), then samples that down for display. The same as using a scaled resolution on a Retina MacBook — it lets them hit an integral multiple for pixel assets while still having e.g. 12 pt text look the same size on the screen.
So, yes, the launch screens need to be that size.
The 6, the 5s, the 5, the 4s and the 4 are all 326 pixels per inch, and use @2x assets to stick to the approximately 160 points per inch of all previous devices.
The 6+ is 401 pixels per inch. So it'd hypothetically need roughly @2.46x assets. Instead Apple uses @3x assets and scales the complete output down to about 84% of its natural size.
In practice Apple has decided to go with more like 87%, turning the 1080 into 1242. No doubt that was to find something as close as possible to 84% that still produced integral sizes in both directions — 1242/1080 = 2208/1920 exactly, whereas if you'd turned the 1080 into, say, 1286, you'd somehow need to render 2286.22 pixels vertically to scale well.
Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).
javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456
Then load the properties to your environment from your code. This makes your application configurable.
FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);
From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.
In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).
Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family
list or to use a downloadable font. See my Guide to using special characters in HTML.
Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?
as PHP relies on server, the real-time location cant be provided only static location can be provided it is better to avoid to rely on the JS for location rather than using php. But there is a need to post the js data to php so that it can be easily be accesible to program on server
First I executed:
sudo chown -R $(whoami):admin /usr/local
Then:
cd $(brew --prefix) && git fetch origin && git reset --hard origin/master
There are a few ways to do this it seems.
Angular provides an $anchorScroll
service, but the documentation is severely lacking and I've not been able to get it to work.
Check out http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html for some insight into $anchorScroll
.
Another way I tested out was creating a custom directive and using el.scrollIntoView()
.
This works pretty decently by basically doing the following in your directive link function:
var el = document.getElementById(attrs.href);
el.scrollIntoView();
However, it seems a bit overblown to do both of these when the browser natively supports this, right?
If you take a look at http://docs.angularjs.org/guide/dev_guide.services.$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:
Links that contain target element
Example:
<a href="/ext/link?a=b" target="_self">link</a>
So, all you have to do is add the target
attribute to your links, like so:
<a href="#anchorLinkID" target="_self">Go to inpage section</a>
Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.
I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.
Gotta note that after a successful scroll and hash change, Angular does follow up and rewrite the hash to its custom style. However, the browser has already completed its business and you are good to go.
or you can use java 8 lambda
test.removeIf(i -> i==2);
it will simply remove all object that meet the condition
I use FLTK because Qt is not free. I don't choose wxWidgets, because my first test with a simple Hello, World! program produced an executable of 24 MB, FLTK 0.8 MB...
To understand this, you must take a step back. In OO, the customer owns the orders (orders are a list in the customer object). There can't be an order without a customer. So the customer seems to be the owner of the orders.
But in the SQL world, one item will actually contain a pointer to the other. Since there is 1 customer for N orders, each order contains a foreign key to the customer it belongs to. This is the "connection" and this means the order "owns" (or literally contains) the connection (information). This is exactly the opposite from the OO/model world.
This may help to understand:
public class Customer {
// This field doesn't exist in the database
// It is simulated with a SQL query
// "OO speak": Customer owns the orders
private List<Order> orders;
}
public class Order {
// This field actually exists in the DB
// In a purely OO model, we could omit it
// "DB speak": Order contains a foreign key to customer
private Customer customer;
}
The inverse side is the OO "owner" of the object, in this case the customer. The customer has no columns in the table to store the orders, so you must tell it where in the order table it can save this data (which happens via mappedBy
).
Another common example are trees with nodes which can be both parents and children. In this case, the two fields are used in one class:
public class Node {
// Again, this is managed by Hibernate.
// There is no matching column in the database.
@OneToMany(cascade = CascadeType.ALL) // mappedBy is only necessary when there are two fields with the type "Node"
private List<Node> children;
// This field exists in the database.
// For the OO model, it's not really necessary and in fact
// some XML implementations omit it to save memory.
// Of course, that limits your options to navigate the tree.
@ManyToOne
private Node parent;
}
This explains for the "foreign key" many-to-one design works. There is a second approach which uses another table to maintain the relations. That means, for our first example, you have three tables: The one with customers, the one with orders and a two-column table with pairs of primary keys (customerPK, orderPK).
This approach is more flexible than the one above (it can easily handle one-to-one, many-to-one, one-to-many and even many-to-many). The price is that
That's why I rarely recommend this approach.
You could do it like:
Person.where("name = ? OR age = ?", 'Pearl', 24)
or more elegant, install rails_or gem and do it like:
Person.where(:name => 'Pearl').or(:age => 24)
http://api.jquery.com/on/ states:
When jQuery calls a handler, the
this
keyword is a reference to the element where the event is being delivered; for directly bound eventsthis
is the element where the event was attached and for delegated eventsthis
is an element matching selector. (Note thatthis
may not be equal toevent.target
if the event has bubbled from a descendant element.)To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).
If we have
<input type="button" class="btn" value ="btn1">
<input type="button" class="btn" value ="btn2">
<input type="button" class="btn" value ="btn3">
<div id="outer">
<input type="button" value ="OuterB" id ="OuterB">
<div id="inner">
<input type="button" class="btn" value ="InnerB" id ="InnerB">
</div>
</div>
Check the below output:
<script>
$(function(){
$(".btn").on("click",function(event){
console.log($(this));
console.log($(event.currentTarget));
console.log($(event.target));
});
$("#outer").on("click",function(event){
console.log($(this));
console.log($(event.currentTarget));
console.log($(event.target));
})
})
</script>
Note that I use $
to wrap the dom element in order to create a jQuery object, which is how we always do.
You would find that for the first case, this
,event.currentTarget
,event.target
are all referenced to the same element.
While in the second case, when the event delegate to some wrapped element are triggered, event.target
would be referenced to the triggered element, while this
and event.currentTarget
are referenced to where the event is delivered.
For this
and event.currentTarget
, they are exactly the same thing according to http://api.jquery.com/event.currenttarget/
It seems to me, this is a cross-domain issue since you're not allowed to make a request to a different domain.
You have to find solutions to this problem: - Use a proxy script, running on your server that will forward your request and will handle the response sending it to the browser Or - The service you're making the request should have JSONP support. This is a cross-domain technique. You might want to read this http://en.wikipedia.org/wiki/JSONP
select replace(myFloat, '', '')
from REPLACE() documentation:
Returns nvarchar if one of the input arguments is of the nvarchar data type; otherwise, REPLACE returns varchar.
Returns NULL if any one of the arguments is NULL.
tests:
null ==> [NULL]
1.11 ==> 1.11
1.10 ==> 1.1
1.00 ==> 1
0.00 ==> 0
-1.10 ==> -1.1
0.00001 ==> 1e-005
0.000011 ==> 1.1e-005
try this
set a=%~$dir:1
If "%for%"=="" (Echo %1 not found) else (echo %1 found at %a%)
You can use the following command:
svn status -q
According to svnbook:
With --quiet (-q), it prints only summary information about locally modified items.
WARNING: The output of this command only shows your modification. So I suggest to do a svn up
to get latest version of the file and then use svn status -q
to get the files you have modified.
Afterall, you could edit the .vimrc,then add the conf
set tabstop=4
Or exec the command
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
The first few lines are simply to demonstrate the :strLen function.
@echo off
set "strToMeasure=This is a string"
call :strLen strToMeasure strlen
echo.String is %strlen% characters long
exit /b
:strLen
setlocal enabledelayedexpansion
:strLen_Loop
if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof
Of course, this is not quite as efficient at the "13 loop" version provided by jeb. But it is easier to understand, and your 3GHz computer can slip through a few thousand iterations in a small fraction of a second.
Do you have to do it with Ajax? Coouldn't it be a possibility to load it in an iframe?
you can use
getElementsByClassName
suppose you have some elements and applied a class name 'test', so, you can get elements like as following
var tests = document.getElementsByClassName('test');
its returns an instance NodeList
, or its superset: HTMLCollection
(FF).
I face this same issue. I just use this command that will help me.
sudo apt install tesseract-ocr
Note that this will only work on Ubuntu.
sudo
is a Unix exclusive command (Linux, Mac, Rasbian, etc.) while apt
is Ubuntu specific.
Another variation of answer suggested by JAR.JAR.beans
(Math.random()*1e32).toString(36)
By changing multiplicator 1e32
you can change length of random string.
The range function in python has the syntax:
range(start, end, step)
It has the same syntax as python lists where the start is inclusive but the end is exclusive.
So if you want to count from 5 to 1, you would use range(5,0,-1)
and if you wanted to count from last
to posn
you would use range(last, posn - 1, -1)
.
var logFile = File.ReadAllLines(LOG_PATH);
var logList = new List<string>(logFile);
Since logFile
is an array, you can pass it to the List<T>
constructor. This eliminates unnecessary overhead when iterating over the array, or using other IO classes.
Actual constructor implementation:
public List(IEnumerable<T> collection)
{
...
ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
...
}
I have the same error and it fixed it including in the file the following
#include <stdint.h>
at the beginning of your file.
A bit of a lengthier way (if interested in it):
In your typescript code do this:
this.objectLength = Object.keys(this.previous_info).length != 0;
And in the template:
ngIf="objectLength != 0"
I managed to do it with
var html_string= "content";
document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(html_string);
You should use the OpenFileDialog class like this
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
strFileName = fd.FileName
End If
Then you can use the File class.
You can disable sending SNI records with the System property jsse.enableSNIExtension=false.
If you can change the code it helps to use SSLCocketFactory#createSocket()
(with no host parameter or with a connected socket). In this case it will not send a server_name indication.
I had the same issue. And I was able to solve it by using a formatter.
file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()
I hope this helps.
There is a really simple way to change the colour of Font Awesome icons.
<!-- Font Awesome insert code -->_x000D_
<script src="https://use.fontawesome.com/49b98aaeb5.js"></script>_x000D_
<!-- End -->_x000D_
<i class="fa fa-thumbs-up fa-5x" aria-hidden="true" style="color:#00cc6a"></i>_x000D_
<i class="fa fa-thumbs-up fa-4x" aria-hidden="true" style="color:#00cc6a"></i>_x000D_
<i class="fa fa-thumbs-up fa-3x" aria-hidden="true" style="color:#00cc6a"></i>_x000D_
<i class="fa fa-thumbs-up fa-2x" aria-hidden="true" style="color:#00cc6a"></i>_x000D_
<i class="fa fa-thumbs-up" aria-hidden="true" style="color:#00cc6a"></i>
_x000D_
You can change the hex code to your preference.
NOTE: The text colour will change the icon colour as well unless there is a style="color:#00cc6a"
within the i
tag.
Use the -s
option BEFORE the command to specify the device, for example:
adb -s 7f1c864e shell
See also http://developer.android.com/tools/help/adb.html#directingcommands
The kind folks at FutureTap have made the FTLocationSimulator available for free at GitHub. It allows you to prepare a test route using for instance Google Earth, and then have the simulator feed these coordinates to your app.
I've written a blog post about how to use FTLocationSimulator to easily switch between multiple routes during testing of the location features.
A multidimensional array creates a nice linear memory layout while a jagged array implies several extra levels of indirection.
Looking up the value jagged[3][6]
in a jagged array var jagged = new int[10][5]
works like this: Look up the element at index 3 (which is an array) and look up the element at index 6 in that array (which is a value). For each dimension in this case, there's an additional look up (this is an expensive memory access pattern).
A multidimensional array is laid out linearly in memory, the actual value is found by multiplying together the indexes. However, given the array var mult = new int[10,30]
, the Length
property of that multidimensional array returns the total number of elements i.e. 10 * 30 = 300.
The Rank
property of a jagged array is always 1, but a multidimensional array can have any rank. The GetLength
method of any array can be used to get the length of each dimension. For the multidimensional array in this example mult.GetLength(1)
returns 30.
Indexing the multidimensional array is faster. e.g. given the multidimensional array in this example mult[1,7]
= 30 * 1 + 7 = 37, get the element at that index 37. This is a better memory access pattern because only one memory location is involved, which is the base address of the array.
A multidimensional array therefore allocates a continuous memory block, while a jagged array does not have to be square, e.g. jagged[1].Length
does not have to equal jagged[2].Length
, which would be true for any multidimensional array.
Performance wise, multidimensional arrays should be faster. A lot faster, but due to a really bad CLR implementation they are not.
23.084 16.634 15.215 15.489 14.407 13.691 14.695 14.398 14.551 14.252
25.782 27.484 25.711 20.844 19.607 20.349 25.861 26.214 19.677 20.171
5.050 5.085 6.412 5.225 5.100 5.751 6.650 5.222 6.770 5.305
The first row are timings of jagged arrays, the second shows multidimensional arrays and the third, well that's how it should be. The program is shown below, FYI this was tested running mono. (The windows timings are vastly different, mostly due to the CLR implementation variations).
On windows, the timings of the jagged arrays are greatly superior, about the same as my own interpretation of what multidimensional array look up should be like, see 'Single()'. Sadly the windows JIT-compiler is really stupid, and this unfortunately makes these performance discussions difficult, there are too many inconsistencies.
These are the timings I got on windows, same deal here, the first row are jagged arrays, second multidimensional and third my own implementation of multidimensional, note how much slower this is on windows compared to mono.
8.438 2.004 8.439 4.362 4.936 4.533 4.751 4.776 4.635 5.864
7.414 13.196 11.940 11.832 11.675 11.811 11.812 12.964 11.885 11.751
11.355 10.788 10.527 10.541 10.745 10.723 10.651 10.930 10.639 10.595
Source code:
using System;
using System.Diagnostics;
static class ArrayPref
{
const string Format = "{0,7:0.000} ";
static void Main()
{
Jagged();
Multi();
Single();
}
static void Jagged()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var jagged = new int[dim][][];
for(var i = 0; i < dim; i++)
{
jagged[i] = new int[dim][];
for(var j = 0; j < dim; j++)
{
jagged[i][j] = new int[dim];
for(var k = 0; k < dim; k++)
{
jagged[i][j][k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
static void Multi()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var multi = new int[dim,dim,dim];
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
for(var k = 0; k < dim; k++)
{
multi[i,j,k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
static void Single()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var single = new int[dim*dim*dim];
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
for(var k = 0; k < dim; k++)
{
single[i*dim*dim+j*dim+k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
}
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
\0 will be interpreted as an octal escape sequence if it is followed by other digits, so \00 will be interpreted as a single character. (\0 is technically an octal escape sequence as well, at least in C).
The way you're doing it:
std::string ("0\0" "0", 3) // String concatenation
works because this version of the constructor takes a char array; if you try to just pass "0\0" "0" as a const char*, it will treat it as a C string and only copy everything up until the null character.
Here is a list of escape sequences.
.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.
All the answers above are correct, What I prefer is to use tui mode (ctrl+X A or 'tui enable') which shows your location and the function in a separate window which is very helpful for the users. Hope that helps too.
For folks searching for solution to set spacing between N
divs, here is another approach using pseudo selectors:
div:not(:last-child) {
margin-right: 40px;
}
You can also combine child pseudo selectors:
div:not(:first-child):not(:last-child) {
margin-left: 20px;
margin-right: 20px;
}
ES6 approach...
Imagine you have this object below:
const developers = {
1: {
id: 1,
name: "Brendan",
family: "Eich"
},
2: {
id: 2,
name: "John",
family: "Resig"
},
3: {
id: 3,
name: "Alireza",
family: "Dezfoolian"
}
};
Create a function:
const filterObject = (obj, filter, filterValue) =>
Object.keys(obj).reduce((acc, val) =>
(obj[val][filter] === filterValue ? acc : {
...acc,
[val]: obj[val]
}
), {});
And call it:
filterObject(developers, "name", "Alireza");
and will return:
{
1: {
id: 1,
name: "Brendan",
family: "Eich"
},
2: {
id: 2,
name: "John",
family: "Resig"
}
}
I made a couple genius methods in C# that you can take advantage of in your production environment:
public static int GetIntMaxValueGenius1()
{
int n = 0;
while (++n > 0) { }
return --n;
}
public static int GetIntMaxValueGenius2()
{
int n = 0;
try
{
while (true)
n = checked(n + 1);
}
catch { }
return n;
}
If you want to use spring jdbctemplate and don't want to deal with connection staff, you can use following:
jdbcTemplate.query("select * from books", new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
ResultSetMetaData rsmd = resultSet.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
}
});
The i
element is non-semantic, so for the screen readers, Googlebot, etc., it should be some kind of transparent (just like span
or div
elements). But it's not a good choice for the developer, because it joins the presentation layer with the structure layer - and that's a bad practice.
em
element (strong
as well) should be always used in a semantic context, not a presentation one. It has to be used whenever some word or sentence is important. Just for an example in the previous sentence, I should use em
to put more emphasis on the 'should be always used' part. Browsers provides some default CSS properties for these elements, but you can and you're supposed to override the default values if your design requires this to keep the correct semantic meaning of these elements.
<span class="italic">Italic Text</span>
is the most wrong way. First of all, it's inconvenient in use. Secondly, it suggest that the text should be italic. And the structure layer (HTML, XML, etc.) shouldn't ever do it. Presentation should be always kept separated from the structure.
<span class="footnote">Italic Text</span>
seems to be the best way for a footnote. It doesn't suggest any presentation and just describes the markup. You can't predict what will happen in the feature. If a footnote will grow up in the feature, you might be forced to change its class name (to keep some logic in your code).
So whenever you've some important text, use em
or strong
to emphasis it. But remember that these elements are inline elements and shouldn't be used to emphasis large blocks of text.
Use CSS if you care only about how something looks like and always try to avoid any extra markup.
join() is a instance method of java.lang.Thread class which we can use join() method to ensure all threads that started from main must end in order in which they started and also main should end in last. In other words waits for this thread to die.
Exception: join() method throws InterruptedException.
Thread state: When join() method is called on thread it goes from running to waiting state. And wait for thread to die.
synchronized block: Thread need not to acquire object lock before calling join() method i.e. join() method can be called from outside synchronized block.
Waiting time: join(): Waits for this thread to die.
public final void join() throws InterruptedException;
This method internally calls join(0). And timeout of 0 means to wait forever;
join(long millis) – synchronized method Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
public final synchronized void join(long millis)
throws InterruptedException;
public final synchronized void join(long millis, int nanos)
throws InterruptedException;
Example of join method
class MyThread implements Runnable {
public void run() {
String threadName = Thread.currentThread().getName();
Printer.print("run() method of "+threadName);
for(int i=0;i<4;i++){
Printer.print("i="+i+" ,Thread="+threadName);
}
}
}
public class TestJoin {
public static void main(String...args) throws InterruptedException {
Printer.print("start main()...");
MyThread runnable = new MyThread();
Thread thread1=new Thread(runnable);
Thread thread2=new Thread(runnable);
thread1.start();
thread1.join();
thread2.start();
thread2.join();
Printer.print("end main()");
}
}
class Printer {
public static void print(String str) {
System.out.println(str);
}
}
Output:
start main()...
run() method of Thread-0
i=0 ,Thread=Thread-0
i=1 ,Thread=Thread-0
i=2 ,Thread=Thread-0
i=3 ,Thread=Thread-0
run() method of Thread-1
i=0 ,Thread=Thread-1
i=1 ,Thread=Thread-1
i=2 ,Thread=Thread-1
i=3 ,Thread=Thread-1
end main()
Note: calling thread1.join() made main thread to wait until Thread-1 dies.
Let’s check a program to use join(long millis)
First, join(1000) will be called on Thread-1, but once 1000 millisec are up, main thread can resume and start thread2 (main thread won’t wait for Thread-1 to die).
class MyThread implements Runnable {
public void run() {
String threadName = Thread.currentThread().getName();
Printer.print("run() method of "+threadName);
for(int i=0;i<4;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Printer.print("i="+i+" ,Thread="+threadName);
}
}
}
public class TestJoin {
public static void main(String...args) throws InterruptedException {
Printer.print("start main()...");
MyThread runnable = new MyThread();
Thread thread1=new Thread(runnable);
Thread thread2=new Thread(runnable);
thread1.start();
// once 1000 millisec are up,
// main thread can resume and start thread2.
thread1.join(1000);
thread2.start();
thread2.join();
Printer.print("end main()");
}
}
class Printer {
public static void print(String str) {
System.out.println(str);
}
}
Output:
start main()...
run() method of Thread-0
i=0 ,Thread=Thread-0
run() method of Thread-1
i=1 ,Thread=Thread-0
i=2 ,Thread=Thread-0
i=0 ,Thread=Thread-1
i=1 ,Thread=Thread-1
i=3 ,Thread=Thread-0
i=2 ,Thread=Thread-1
i=3 ,Thread=Thread-1
end main()
For more information see my blog:
http://javaexplorer03.blogspot.in/2016/05/join-method-in-java.html
For multiple text boxes - add them into a list and show all errors into 1 messagebox.
// Append errors into 1 Message Box
List<string> errors = new List<string>();
if (string.IsNullOrEmpty(textBox1.Text))
{
errors.Add("User");
}
if (string.IsNullOrEmpty(textBox2.Text))
{
errors.Add("Document Ref Code");
}
if (errors.Count > 0)
{
errors.Insert(0, "The following fields are empty:");
string message = string.Join(Environment.NewLine, errors);
MessageBox.Show(message, "errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.
select * from emp, dept where emp.dept_id=dept.dept_id(+)
So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!
Here's a small improvement that to @UltraInstinct's Tee class, modified to be a context manager and also captures any exceptions.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
To use the context manager:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
<?php
header("Location: index.html");
?>
Just make sure nothing is actually written to the page prior to this code, or it won't work.
If you're using MySQL, then you can use insert ... on duplicate.
If your project is not a Maven project, right-click on your project and choose Properties to open the Project Properties dialog.
There is a Project Facets item on the left, select it, look for the Java facet on the list, choose which version you want to use for the project and apply.
The spec files are unit tests for your source files. The convention for Angular applications is to have a .spec.ts file for each .ts file. They are run using the Jasmine javascript test framework through the Karma test runner (https://karma-runner.github.io/) when you use the ng test
command.
You can use this for some further reading:
in my case I have to update the records which are more than 1000, for this instead of hitting the update query each time I preferred this,
UPDATE mst_users
SET base_id = CASE user_id
WHEN 78 THEN 999
WHEN 77 THEN 88
ELSE base_id END WHERE user_id IN(78, 77)
78,77 are the user Ids and for those user id I need to update the base_id 999 and 88 respectively.This works for me.
dynamic data = List<x> val;
List<y> val2 = ((IEnumerable)data).Cast<y>().ToList();
if you wanna ng-model value, if you can write like this in the triggered event: $scope.searchText
this did it for me. you can vary the options for the output format to Base64.Default whatsoever.
// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
If you want to access the property without creating an intermediate variable, use the {}
notation:
$something = $object->{'something'};
That also allows you to build the property name in a loop for example:
for ($i = 0; $i < 5; $i++) {
$something = $object->{'something' . $i};
// ...
}
As of today November 2017
Bootstrap v4 - beta
Responsive utilities
All @screen- variables have been removed in v4.0.0. Use the media-breakpoint-up(), media-breakpoint-down(), or media-breakpoint-only() Sass mixins or the $grid-breakpoints Sass map instead.
Removed from v3: .hidden-xs .hidden-sm .hidden-md .hidden-lg .visible-xs-block .visible-xs-inline .visible-xs-inline-block .visible-sm-block .visible-sm-inline .visible-sm-inline-block .visible-md-block .visible-md-inline .visible-md-inline-block .visible-lg-block .visible-lg-inline .visible-lg-inline-block
Removed from v4 alphas: .hidden-xs-up .hidden-xs-down .hidden-sm-up .hidden-sm-down .hidden-md-up .hidden-md-down .hidden-lg-up .hidden-lg-down
https://getbootstrap.com/docs/4.0/migration/#responsive-utilities
Using the sheet codename was the answer I needed too to stop a series of macros falling over - ccampj's answer above mirrors this solution (with screen pics)
You can publicly expose Input
facade via an alias in config/app.php
:
'aliases' => [
...
'Input' => Illuminate\Support\Facades\Input::class,
]
And access url $_GET
parameter values using the facade directly inside Blade view/template:
{{ Input::get('a') }}
Open your startup project's properties (Project ? {ProjectName} Properties... from the main menu or right click your project in the Solution Explorer and choose Properties), then navigate to the Web tab and under Start Action choose Don't open a page. Wait for a request from an external application.
You will still be able to use any browser (or Fiddler, whatever) to access the running application, but it won't open the browser window automatically, it'll just start in the background and wait for any requests.
It is very simple
public void onClick(View v) {
imgButton.setImageResource(R.drawable.ic_launcher);
}
Using set Background image resource will chanage the background of the button
Using the attribute method is, in fact, easier and more straightforward.
Using Ruby with the Selenium and PageObject gems, to get the class associated with a certain element, the line would be element.attribute(Class)
.
The same concept applies if you wanted to get other attributes tied to the element. For example, if I wanted the string of an element, element.attribute(String)
.
From the JDK source:
static <T> Function<T, T> identity() {
return t -> t;
}
So, no, as long as it is syntactically correct.
You can use OutputDebugString
. OutputDebugString
is a macro that depending on your build options either maps to OutputDebugStringA(char const*)
or OutputDebugStringW(wchar_t const*)
. In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L
prefix:
OutputDebugStringW(L"My output string.");
Normally you will use the macro version together with the _T
macro like this:
OutputDebugString(_T("My output string."));
If you project is configured to build for UNICODE it will expand into:
OutputDebugStringW(L"My output string.");
If you are not building for UNICODE it will expand into:
OutputDebugStringA("My output string.");
Any data type which is lower than "int" (except Boolean) is implicitly converts to "int".
In your case:
short a = 2;
short b = 3;
short c = a + b;
The result of (a+b) is implicitly converted to an int. And now you are assigning it to "short".So that you are getting the error.
short,byte,char --for all these we will get same error.
Mainly this problem occurs because your library files get deleted. The simple way to work your project as it was working previously is 1) Go to Project properties 2) Select java Build Path 3) Remove all library except jre. 4) Now add the same same jar file by clicking "Add external jars".
There are (at least) three different things you might conceive of as a "character", and consequently, three different categories of approach you might want to use.
JavaScript strings were originally invented as sequences of UTF-16 code units, back at a point in history when there was a one-to-one relationship between UTF-16 code units and Unicode code points. The .length
property of a string measures its length in UTF-16 code units, and when you do someString[i]
you get the ith UTF-16 code unit of someString
.
Consequently, you can get an array of UTF-16 code units from a string by using a C-style for-loop with an index variable...
const yourString = 'Hello, World!';_x000D_
const charArray = [];_x000D_
for (let i=0; i<=yourString.length; i++) {_x000D_
charArray.push(yourString[i]);_x000D_
}_x000D_
console.log(charArray);
_x000D_
There are also various short ways to achieve the same thing, like using .split()
with the empty string as a separator:
const charArray = 'Hello, World!'.split('');_x000D_
console.log(charArray);
_x000D_
However, if your string contains code points that are made up of multiple UTF-16 code units, this will split them into individual code units, which may not be what you want. For instance, the string ''
is made up of four unicode code points (code points 0x1D7D8 through 0x1D7DB) which, in UTF-16, are each made up of two UTF-16 code units. If we split that string using the methods above, we'll get an array of eight code units:
const yourString = '';_x000D_
console.log('First code unit:', yourString[0]);_x000D_
const charArray = yourString.split('');_x000D_
console.log('charArray:', charArray);
_x000D_
So, perhaps we want to instead split our string into Unicode Code Points! That's been possible since ECMAScript 2015 added the concept of an iterable to the language. Strings are now iterables, and when you iterate over them (e.g. with a for...of
loop), you get Unicode code points, not UTF-16 code units:
const yourString = '';_x000D_
const charArray = [];_x000D_
for (const char of yourString) {_x000D_
charArray.push(char);_x000D_
}_x000D_
console.log(charArray);
_x000D_
We can shorten this using Array.from
, which iterates over the iterable it's passed implicitly:
const yourString = '';_x000D_
const charArray = Array.from(yourString);_x000D_
console.log(charArray);
_x000D_
However, unicode code points are not the largest possible thing that could possibly be considered a "character" either. Some examples of things that could reasonably be considered a single "character" but be made up of multiple code points include:
We can see below that if we try to convert a string with such characters into an array via the iteration mechanism above, the characters end up broken up in the resulting array. (In case any of the characters don't render on your system, yourString
below consists of a capital A with an acute accent, followed by the flag of the United Kingdom, followed by a black woman.)
const yourString = 'A´';_x000D_
const charArray = Array.from(yourString);_x000D_
console.log(charArray);
_x000D_
If we want to keep each of these as a single item in our final array, then we need an array of graphemes, not code points.
JavaScript has no built-in support for this - at least not yet. So we need a library that understands and implements the Unicode rules for what combination of code points constitute a grapheme. Fortunately, one exists: orling's grapheme-splitter. You'll want to install it with npm or, if you're not using npm, download the index.js file and serve it with a <script>
tag. For this demo, I'll load it from jsDelivr.
grapheme-splitter gives us a GraphemeSplitter
class with three methods: splitGraphemes
, iterateGraphemes
, and countGraphemes
. Naturally, we want splitGraphemes
:
const splitter = new GraphemeSplitter();_x000D_
const yourString = 'A´';_x000D_
const charArray = splitter.splitGraphemes(yourString);_x000D_
console.log(charArray);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/index.js"></script>
_x000D_
And there we are - an array of three graphemes, which is probably what you wanted.
Edit Although using the Intel images gets some performance gains, the performance gained by using Genymotion is much greater. See Paul Lammertsma's answer.
Previous Answer
With ADT rev 17 the emulator supports running x86 system images in virtualization mode on Windows and Mac OS X. This has a noticeable impact on performance.
ADT rev 17 notes: http://android-developers.blogspot.jp/2012/03/updated-sdk-tools-and-adt-revision-17.html
Configuring Virtual Machine Acceleration: http://developer.android.com/guide/developing/devices/emulator.html#accel-vm
You should add %NODE_PATH%
to the system variable Path
if the other answers don't work.
The point is, command prompt only executes programs under the Path
system variable, not the user variables. If you have NODE_PATH
set as a user variable, add %NODE_PATH%
to Path
.
I asked here and got marked duplicate for a question with different intention :(
NPM Windows doesn't execute program under the User Variable path [duplicate]
You can always add the "!" into your float-options. This way, latex tries really hard to place the figure where you want it (I mostly use [h!tb]), stretching the normal rules of type-setting.
I have found another solution:
Use the float-package. This way you can place the figures where you want them to be.
You can pip install pickle by running command pip install pickle-mixin
.
Proceed to import it using import pickle
.
This can be then used normally.
It depends upon lower_case_table_names
system variable:
show variables where Variable_name='lower_case_table_names'
There are three possible values for this:
0
- lettercase specified in the CREATE TABLE
or CREATE DATABASE
statement. Name comparisons are case sensitive. 1
- Table names are stored in lowercase on disk and name comparisons are not case sensitive. 2
- lettercase specified in the CREATE TABLE
or CREATE DATABASE
statement, but MySQL converts them to lowercase on lookup.
Name comparisons are not case sensitive.Python 3.9 adds the zoneinfo
module so now only the standard library is needed!
from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)
Attach a timezone:
>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'
Attach the system's local timezone:
>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'
Subsequently it is properly converted to other timezones:
>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'
Wikipedia list of available time zones
Windows has no system time zone database, so here an extra package is needed:
pip install tzdata
There is a backport to allow use of zoneinfo
in Python 3.6 to 3.8:
pip install backports.zoneinfo
Then:
from backports.zoneinfo import ZoneInfo
If you can edit all documents in aggregate :
"TimeStamp": {$toDecimal: {$toDate: "$Your Date"}}
And for the client, you set the query :
Date.parse("Your date".toISOString())
That's what makes you whole work with ISODate.
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
If your label is long and goes on multiple rows setting the width and display:inline-block will help.
.form-field * {
vertical-align: middle;
}
.form-field input {
clear:left;
}
.form-field label {
width:200px;
display:inline-block;
}
<div class="form-field">
<input id="option1" type="radio" name="opt" value="1"/>
<label for="option1">Option 1 is very long and is likely to go on two lines.</label>
<input id="option2" type="radio" name="opt" value="2"/>
<label for="option2">Option 2 might fit into one line.</label>
</div>
new
allocates objects on the heap. Otherwise, objects are allocated on the stack. Look up the difference between the two.
echo 5a | python -c "import sys; print chr(int(sys.stdin.read(),base=16))"
pullFiles.sh
:#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"
for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
file=$(echo -e $file | tr -d "\r\n"); # EOL fix
adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done
Make it executable: chmod +x pullFiles.sh
Run it: ./pullFiles.sh
You can use max-height
in an inline style
attribute, as below:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
To use scrolling with content that overflows a given max-height
, you can alternatively try the following:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>
To restrict the height to a fixed value you can use something like this.
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
Specify the same value for both max-height
and min-height
(either in pixels or in points – as long as it’s consistent).
You can also put the same styles in css class in a stylesheet (or a style
tag as shown below) and then include the same in your tag. See below:
Style Code:
.fixed-panel {
min-height: 10;
max-height: 10;
overflow-y: scroll;
}
Apply Style :
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>
Hope this helps with your need.
plz change %HTTPPORT% as 8080 its working for me
It is good practice when you start creating website to reset all the margins and paddings. So I recommend on start just to simple do:
* { margin: 0, padding: 0 }
This will make margins and paddings of all elements to be 0, and then you can style them as you wish, because each browser has a different default margin and padding of the elements.
You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.
For your purpose, it would make most sense to define a custom filter, so you could for example do the following:
The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{ splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{ splitpart(1) }}
The filter function could then look like this:
def splitpart (value, index, char = ','):
return value.split(char)[index]
An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.
JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:
send an email without refreshing the page
You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)
If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.
You should try using nohup
and running it in the background:
nohup sleep 3600 &
Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.
According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:
for %%f in (*.in) do call process.cmd %%~nf
Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:
echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt
There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.
EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...
You won't need a plugin to see commit history with Visual Studio Code 1.42 or more.
Timeline view
In this milestone, we've made progress on the new Timeline view, and have an early preview to share.
This is a unified view for visualizing time-series events (e.g. commits, saves, test runs, etc.) for a resource (file, folder, etc.).
To enable the Timeline view, you must be using
the Insiders Edition(VSCode 1.44 March 2020) and then add the following setting:
"timeline.showView": true
Try the following work-around to start emulator-x86:
export LD_LIBRARY_PATH=$SDK/tools/lib:$LD_LIBRARY_PATH
$SDK/tools/emulator-x86 <your-other-options>
Where $SDK is the path to your SDK installation. That's in a nutshell what 'emulator' tries to do. You might want to start emulator64-x86 instead of emulator-x86 if the former exists though.
No, you can't use underscore in subdomain but hypen (dash). i.e my-subdomain.agahost.com is acceptable and my_subdomain.agahost.com would not be acceptable.
@Query("SELECT rd FROM ReleaseDateType rd, CacheMedia cm WHERE ...")
Zapping - you can use this javascript lib; DefiantJS. There is no need to restructure JSON data into objects to ease searching. Instead, you can search the JSON structure with an XPath expression like this:
var data = [
{
"id": "one",
"pId": "foo1",
"cId": "bar1"
},
{
"id": "two",
"pId": "foo2",
"cId": "bar2"
},
{
"id": "three",
"pId": "foo3",
"cId": "bar3"
}
],
res = JSON.search( data, '//*[id="one"]' );
console.log( res[0].cId );
// 'bar1'
DefiantJS extends the global object JSON with a new method; "search" which returns array with the matches (empty array if none were found). You can try it out yourself by pasting your JSON data and testing different XPath queries here:
http://www.defiantjs.com/#xpath_evaluator
XPath is, as you know, a standardised query language.
You can use this library: https://github.com/stil/curl-easy
It's pretty straightforward then:
<?php
$request = new cURL\Request('http://yahoo.com/');
$request->getOptions()->set(CURLOPT_RETURNTRANSFER, true);
// Specify function to be called when your request is complete
$request->addListener('complete', function (cURL\Event $event) {
$response = $event->response;
$httpCode = $response->getInfo(CURLINFO_HTTP_CODE);
$html = $response->getContent();
echo "\nDone.\n";
});
// Loop below will run as long as request is processed
$timeStart = microtime(true);
while ($request->socketPerform()) {
printf("Running time: %dms \r", (microtime(true) - $timeStart)*1000);
// Here you can do anything else, while your request is in progress
}
Below you can see console output of above example. It will display simple live clock indicating how much time request is running:
Bootstrap 3 now has Responsive tables out of the box. Hooray! :)
You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive
Add a <div class="table-responsive">
surrounding your table and you should be good to go:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
To make it work on all layouts you can do this:
.table-responsive
{
overflow-x: auto;
}
They are different functions. You should decide for your situation what do you need.
I don't consider using any of them as a bad practice. Most of the time IsNullOrEmpty()
is enough. But you have the choice :)